test_cond.py 2.1 KB

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