test_cond.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. import json
  2. from typing import Any, Union
  3. import pytest
  4. from reflex.components.base.fragment import Fragment
  5. from reflex.components.core.cond import Cond, cond
  6. from reflex.components.radix.themes.typography.text import Text
  7. from reflex.state import BaseState
  8. from reflex.utils.format import format_state_name
  9. from reflex.vars.base import LiteralVar, Var, computed_var
  10. @pytest.fixture
  11. def cond_state(request):
  12. class CondState(BaseState):
  13. value: request.param["value_type"] = request.param["value"] # pyright: ignore [reportInvalidTypeForm, reportUndefinedVariable] # noqa: F821
  14. return CondState
  15. def test_f_string_cond_interpolation():
  16. # make sure backticks inside interpolation don't get escaped
  17. var = LiteralVar.create(f"x {cond(True, 'a', 'b')}")
  18. assert str(var) == '("x "+(true ? "a" : "b"))'
  19. @pytest.mark.parametrize(
  20. "cond_state",
  21. [
  22. pytest.param({"value_type": bool, "value": True}),
  23. pytest.param({"value_type": int, "value": 0}),
  24. pytest.param({"value_type": str, "value": "true"}),
  25. ],
  26. indirect=True,
  27. )
  28. def test_validate_cond(cond_state: BaseState):
  29. """Test if cond can be a rx.Var with any values.
  30. Args:
  31. cond_state: A fixture.
  32. """
  33. cond_component = cond(
  34. cond_state.value,
  35. Text.create("cond is True"),
  36. Text.create("cond is False"),
  37. )
  38. cond_dict = cond_component.render() if type(cond_component) is Fragment else {}
  39. assert cond_dict["name"] == "Fragment"
  40. [condition] = cond_dict["children"]
  41. assert condition["cond_state"] == f"isTrue({cond_state.get_full_name()}.value)"
  42. # true value
  43. true_value = condition["true_value"]
  44. assert true_value["name"] == "Fragment"
  45. [true_value_text] = true_value["children"]
  46. assert true_value_text["name"] == "RadixThemesText"
  47. assert true_value_text["children"][0]["contents"] == '{"cond is True"}'
  48. # false value
  49. false_value = condition["false_value"]
  50. assert false_value["name"] == "Fragment"
  51. [false_value_text] = false_value["children"]
  52. assert false_value_text["name"] == "RadixThemesText"
  53. assert false_value_text["children"][0]["contents"] == '{"cond is False"}'
  54. @pytest.mark.parametrize(
  55. "c1, c2",
  56. [
  57. (True, False),
  58. (32, 0),
  59. ("hello", ""),
  60. (2.3, 0.0),
  61. (LiteralVar.create("a"), LiteralVar.create("b")),
  62. ],
  63. )
  64. def test_prop_cond(c1: Any, c2: Any):
  65. """Test if cond can be a prop.
  66. Args:
  67. c1: truth condition value
  68. c2: false condition value
  69. """
  70. prop_cond = cond(
  71. True,
  72. c1,
  73. c2,
  74. )
  75. assert isinstance(prop_cond, Var)
  76. if not isinstance(c1, Var):
  77. c1 = json.dumps(c1)
  78. if not isinstance(c2, Var):
  79. c2 = json.dumps(c2)
  80. assert str(prop_cond) == f"(true ? {c1!s} : {c2!s})"
  81. def test_cond_no_mix():
  82. """Test if cond can't mix components and props."""
  83. with pytest.raises(ValueError):
  84. cond(True, LiteralVar.create("hello"), Text.create("world"))
  85. def test_cond_no_else():
  86. """Test if cond can be used without else."""
  87. # Components should support the use of cond without else
  88. comp = cond(True, Text.create("hello"))
  89. assert isinstance(comp, Fragment)
  90. comp = comp.children[0]
  91. assert isinstance(comp, Cond)
  92. assert comp.cond._decode() is True
  93. assert comp.comp1.render() == Fragment.create(Text.create("hello")).render() # pyright: ignore [reportOptionalMemberAccess]
  94. assert comp.comp2 == Fragment.create()
  95. # Props do not support the use of cond without else
  96. with pytest.raises(ValueError):
  97. cond(True, "hello") # pyright: ignore [reportArgumentType]
  98. def test_cond_computed_var():
  99. """Test if cond works with computed vars."""
  100. class CondStateComputed(BaseState):
  101. @computed_var
  102. def computed_int(self) -> int:
  103. return 0
  104. @computed_var
  105. def computed_str(self) -> str:
  106. return "a string"
  107. comp = cond(True, CondStateComputed.computed_int, CondStateComputed.computed_str)
  108. # TODO: shouldn't this be a ComputedVar?
  109. assert isinstance(comp, Var)
  110. state_name = format_state_name(CondStateComputed.get_full_name())
  111. assert (
  112. str(comp) == f"(true ? {state_name}.computed_int : {state_name}.computed_str)"
  113. )
  114. assert comp._var_type == Union[int, str]