test_cond.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import json
  2. from typing import Any
  3. import pytest
  4. import pynecone as pc
  5. from pynecone.components.layout.cond import Cond, cond
  6. from pynecone.components.layout.fragment import Fragment
  7. from pynecone.components.typography.text import Text
  8. from pynecone.var import Var
  9. @pytest.fixture
  10. def cond_state(request):
  11. class CondState(pc.State):
  12. value: request.param["value_type"] = request.param["value"] # noqa
  13. return CondState
  14. @pytest.mark.parametrize(
  15. "cond_state",
  16. [
  17. pytest.param({"value_type": bool, "value": True}),
  18. pytest.param({"value_type": int, "value": 0}),
  19. pytest.param({"value_type": str, "value": "true"}),
  20. ],
  21. indirect=True,
  22. )
  23. def test_validate_cond(cond_state: pc.Var):
  24. """Test if cond can be a pc.Var with any values.
  25. Args:
  26. cond_state: A fixture.
  27. """
  28. cond_component = cond(
  29. cond_state.value,
  30. Text.create("cond is True"),
  31. Text.create("cond is False"),
  32. )
  33. assert str(cond_component) == (
  34. "<Fragment>{cond_state.value ? "
  35. "<Fragment><Text>{`cond is True`}</Text></Fragment> : "
  36. "<Fragment><Text>{`cond is False`}</Text></Fragment>}</Fragment>"
  37. )
  38. @pytest.mark.parametrize(
  39. "c1, c2",
  40. [
  41. (True, False),
  42. (32, 0),
  43. ("hello", ""),
  44. (2.3, 0.0),
  45. ],
  46. )
  47. def test_prop_cond(c1: Any, c2: Any):
  48. """Test if cond can be a prop.
  49. Args:
  50. c1: truth condition value
  51. c2: false condition value
  52. """
  53. prop_cond = cond(
  54. True,
  55. c1,
  56. c2,
  57. )
  58. assert isinstance(prop_cond, Var)
  59. c1 = json.dumps(c1).replace('"', "`")
  60. c2 = json.dumps(c2).replace('"', "`")
  61. assert str(prop_cond) == f"{{true ? {c1} : {c2}}}"
  62. def test_cond_no_else():
  63. """Test if cond can be used without else."""
  64. # Components should support the use of cond without else
  65. comp = cond(True, Text.create("hello"))
  66. assert isinstance(comp, Fragment)
  67. comp = comp.children[0]
  68. assert isinstance(comp, Cond)
  69. assert comp.cond == True # noqa
  70. assert comp.comp1 == Fragment.create(Text.create("hello"))
  71. assert comp.comp2 == Fragment.create()
  72. # Props do not support the use of cond without else
  73. with pytest.raises(ValueError):
  74. cond(True, "hello")