test_cond.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. from typing import Any
  2. import pytest
  3. import pynecone as pc
  4. from pynecone.components import cond
  5. from pynecone.components.layout.cond import Cond
  6. from pynecone.components.layout.fragment import Fragment
  7. from pynecone.components.tags.tag import PropCond
  8. from pynecone.components.typography.text import Text
  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.Val 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. "{cond_state.value ? "
  35. "<Text>{`cond is True`}</Text> : "
  36. "<Text>{`cond is False`}</Text>}"
  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, PropCond)
  59. assert prop_cond.prop1 == c1
  60. assert prop_cond.prop2 == c2
  61. assert prop_cond.cond == True # noqa
  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, Cond)
  67. assert comp.cond == True # noqa
  68. assert comp.comp1 == Text.create("hello")
  69. assert comp.comp2 == Fragment.create()
  70. # Props do not support the use of cond without else
  71. with pytest.raises(ValueError):
  72. cond(True, "hello")