fix tests for cond and var

This commit is contained in:
Khaleel Al-Adhami 2025-01-16 16:02:41 -08:00
parent 94c9e52474
commit f9d45d5562
2 changed files with 56 additions and 54 deletions

View File

@ -3,8 +3,7 @@ from typing import Any, Union
import pytest import pytest
from reflex.components.base.fragment import Fragment from reflex.components.core.cond import cond
from reflex.components.core.cond import Cond, cond
from reflex.components.radix.themes.typography.text import Text from reflex.components.radix.themes.typography.text import Text
from reflex.state import BaseState from reflex.state import BaseState
from reflex.utils.format import format_state_name from reflex.utils.format import format_state_name
@ -22,7 +21,10 @@ def cond_state(request):
def test_f_string_cond_interpolation(): def test_f_string_cond_interpolation():
# make sure backticks inside interpolation don't get escaped # make sure backticks inside interpolation don't get escaped
var = LiteralVar.create(f"x {cond(True, 'a', 'b')}") var = LiteralVar.create(f"x {cond(True, 'a', 'b')}")
assert str(var) == '("x "+(true ? "a" : "b"))' assert (
str(var)
== '("x "+((((_condition, _if_true, _if_false) => (_condition ? _if_true : _if_false))(true, (() => "a"), (() => "b")))()))'
)
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -40,32 +42,23 @@ def test_validate_cond(cond_state: BaseState):
Args: Args:
cond_state: A fixture. cond_state: A fixture.
""" """
cond_component = cond( first_component = Text.create("cond is True")
second_component = Text.create("cond is False")
cond_var = cond(
cond_state.value, cond_state.value,
Text.create("cond is True"), first_component,
Text.create("cond is False"), second_component,
) )
cond_dict = cond_component.render() if type(cond_component) is Fragment else {}
assert cond_dict["name"] == "Fragment"
[condition] = cond_dict["children"] assert isinstance(cond_var, Var)
assert condition["cond_state"] == f"isTrue({cond_state.get_full_name()}.value)" assert (
str(cond_var)
== f'((((_condition, _if_true, _if_false) => (_condition ? _if_true : _if_false))({cond_state.value.bool()!s}, (() => (jsx(RadixThemesText, ({{ ["as"] : "p" }}), (jsx(Fragment, ({{ }}), "cond is True"))))), (() => (jsx(RadixThemesText, ({{ ["as"] : "p" }}), (jsx(Fragment, ({{ }}), "cond is False")))))))())'
)
# true value var_data = cond_var._get_all_var_data()
true_value = condition["true_value"] assert var_data is not None
assert true_value["name"] == "Fragment" assert var_data.components == (first_component, second_component)
[true_value_text] = true_value["children"]
assert true_value_text["name"] == "RadixThemesText"
assert true_value_text["children"][0]["contents"] == '{"cond is True"}'
# false value
false_value = condition["false_value"]
assert false_value["name"] == "Fragment"
[false_value_text] = false_value["children"]
assert false_value_text["name"] == "RadixThemesText"
assert false_value_text["children"][0]["contents"] == '{"cond is False"}'
@pytest.mark.parametrize( @pytest.mark.parametrize(
@ -96,25 +89,31 @@ def test_prop_cond(c1: Any, c2: Any):
c1 = json.dumps(c1) c1 = json.dumps(c1)
if not isinstance(c2, Var): if not isinstance(c2, Var):
c2 = json.dumps(c2) c2 = json.dumps(c2)
assert str(prop_cond) == f"(true ? {c1!s} : {c2!s})" assert (
str(prop_cond)
== f"((((_condition, _if_true, _if_false) => (_condition ? _if_true : _if_false))(true, (() => {c1!s}), (() => {c2!s})))())"
)
def test_cond_no_mix(): def test_cond_mix():
"""Test if cond can't mix components and props.""" """Test if cond can mix components and props."""
with pytest.raises(ValueError): x = cond(True, LiteralVar.create("hello"), Text.create("world"))
cond(True, LiteralVar.create("hello"), Text.create("world")) assert isinstance(x, Var)
assert (
str(x)
== '((((_condition, _if_true, _if_false) => (_condition ? _if_true : _if_false))(true, (() => "hello"), (() => (jsx(RadixThemesText, ({ ["as"] : "p" }), (jsx(Fragment, ({ }), "world")))))))())'
)
def test_cond_no_else(): def test_cond_no_else():
"""Test if cond can be used without else.""" """Test if cond can be used without else."""
# Components should support the use of cond without else # Components should support the use of cond without else
comp = cond(True, Text.create("hello")) comp = cond(True, Text.create("hello"))
assert isinstance(comp, Fragment) assert isinstance(comp, Var)
comp = comp.children[0] assert (
assert isinstance(comp, Cond) str(comp)
assert comp.cond._decode() is True # type: ignore == '((((_condition, _if_true, _if_false) => (_condition ? _if_true : _if_false))(true, (() => (jsx(RadixThemesText, ({ ["as"] : "p" }), (jsx(Fragment, ({ }), "hello"))))), (() => (jsx(Fragment, ({ }))))))())'
assert comp.comp1.render() == Fragment.create(Text.create("hello")).render() )
assert comp.comp2 == Fragment.create()
# Props do not support the use of cond without else # Props do not support the use of cond without else
with pytest.raises(ValueError): with pytest.raises(ValueError):
@ -140,7 +139,8 @@ def test_cond_computed_var():
state_name = format_state_name(CondStateComputed.get_full_name()) state_name = format_state_name(CondStateComputed.get_full_name())
assert ( assert (
str(comp) == f"(true ? {state_name}.computed_int : {state_name}.computed_str)" str(comp)
== f"((((_condition, _if_true, _if_false) => (_condition ? _if_true : _if_false))(true, (() => {state_name}.computed_int), (() => {state_name}.computed_str)))())"
) )
assert comp._var_type == Union[int, str] assert comp._var_type == Union[int, str]

View File

@ -346,8 +346,14 @@ def test_basic_operations(TestObj):
str(LiteralNumberVar.create(1) ** 2) str(LiteralNumberVar.create(1) ** 2)
== "(((_lhs, _rhs) => (_lhs ** _rhs))(1, 2))" == "(((_lhs, _rhs) => (_lhs ** _rhs))(1, 2))"
) )
assert str(LiteralNumberVar.create(1) & v(2)) == "(((_a, _b) => (_a && _b))(1, 2))" assert (
assert str(LiteralNumberVar.create(1) | v(2)) == "(((_a, _b) => (_a || _b))(1, 2))" str(LiteralNumberVar.create(1) & v(2))
== "(((_a, _b) => (_a() && _b()))((() => 1), (() => 2)))"
)
assert (
str(LiteralNumberVar.create(1) | v(2))
== "(((_a, _b) => (_a() || _b()))((() => 1), (() => 2)))"
)
assert ( assert (
str(LiteralArrayVar.create([1, 2, 3])[0]) str(LiteralArrayVar.create([1, 2, 3])[0])
== "(((...args) => (((_array, _index_or_slice) => atSliceOrIndex(_array, _index_or_slice))([1, 2, 3], ...args)))(0))" == "(((...args) => (((_array, _index_or_slice) => atSliceOrIndex(_array, _index_or_slice))([1, 2, 3], ...args)))(0))"
@ -507,25 +513,21 @@ def test_var_types(var, var_type):
def test_str_contains(var, expected): def test_str_contains(var, expected):
assert ( assert (
str(var.contains("1")) str(var.contains("1"))
== f'(((...args) => (((_haystack, _needle, _field = "") => isTrue(_field) ? _haystack.some(obj => obj[_field] === _needle) : _haystack.some(obj => obj === _needle))({expected!s}, ...args)))("1"))' == f'(((...args) => (((_haystack, _needle) => _haystack.includes(_needle))({expected!s}, ...args)))("1"))'
) )
assert ( assert (
str(var.contains(v("1"))) str(var.contains(v("1")))
== f'(((...args) => (((_haystack, _needle, _field = "") => isTrue(_field) ? _haystack.some(obj => obj[_field] === _needle) : _haystack.some(obj => obj === _needle))({expected!s}, ...args)))("1"))' == f'(((...args) => (((_haystack, _needle) => _haystack.includes(_needle))({expected!s}, ...args)))("1"))'
) )
other_state_var = Var(_js_expr="other")._var_set_state("state").to(str) other_state_var = Var(_js_expr="other")._var_set_state("state").to(str)
other_var = Var(_js_expr="other").to(str) other_var = Var(_js_expr="other").to(str)
assert ( assert (
str(var.contains(other_state_var)) str(var.contains(other_state_var))
== f'(((...args) => (((_haystack, _needle, _field = "") => isTrue(_field) ? _haystack.some(obj => obj[_field] === _needle) : _haystack.some(obj => obj === _needle))({expected!s}, ...args)))(state.other))' == f"(((...args) => (((_haystack, _needle) => _haystack.includes(_needle))({expected!s}, ...args)))(state.other))"
) )
assert ( assert (
str(var.contains(other_var)) str(var.contains(other_var))
== f'(((...args) => (((_haystack, _needle, _field = "") => isTrue(_field) ? _haystack.some(obj => obj[_field] === _needle) : _haystack.some(obj => obj === _needle))({expected!s}, ...args)))(other))' == f"(((...args) => (((_haystack, _needle) => _haystack.includes(_needle))({expected!s}, ...args)))(other))"
)
assert (
str(var.contains("1", "hello"))
== f'(((...args) => (((_haystack, _needle, _field = "") => isTrue(_field) ? _haystack.some(obj => obj[_field] === _needle) : _haystack.some(obj => obj === _needle))({expected!s}, ...args)))("1", "hello"))'
) )
@ -1133,11 +1135,11 @@ def test_string_operations():
) )
assert ( assert (
str(basic_string.contains("World")) str(basic_string.contains("World"))
== '(((...args) => (((_haystack, _needle, _field = "") => isTrue(_field) ? _haystack.some(obj => obj[_field] === _needle) : _haystack.some(obj => obj === _needle))("Hello, World!", ...args)))("World"))' == '(((...args) => (((_haystack, _needle) => _haystack.includes(_needle))("Hello, World!", ...args)))("World"))'
) )
assert ( assert (
str(basic_string.split(" ").join(",")) str(basic_string.split(" ").join(","))
== '(((...args) => (((_array, _sep = "") => _array.join(_sep))((((...args) => (((_string, _sep = "") => isTrue(_sep) ? _string.split(_sep) : [..._string])("Hello, World!", ...args)))(" ")), ...args)))(","))' == '(((...args) => (((_array, _sep = "") => Array.prototype.join.apply(_array,[_sep]))((((...args) => (((_string, _sep = "") => isTrue(_sep) ? _string.split(_sep) : [..._string])("Hello, World!", ...args)))(" ")), ...args)))(","))'
) )
@ -1157,7 +1159,7 @@ def test_all_number_operations():
assert ( assert (
str(even_more_complicated_number) str(even_more_complicated_number)
== "(((_value) => !(_value))((isTrue((((_a, _b) => (_a || _b))((Math.abs((Math.floor((((_lhs, _rhs) => (_lhs ** _rhs))((((_lhs, _rhs) => (_lhs % _rhs))((((_lhs, _rhs) => Math.floor(_lhs / _rhs))((((_lhs, _rhs) => (_lhs / _rhs))((((_lhs, _rhs) => (_lhs * _rhs))((((_value) => -(_value))((((_lhs, _rhs) => (_lhs + _rhs))(-5.4, 1)))), 2)), 3)), 2)), 3)), 2)))))), (((_a, _b) => (_a && _b))(2, (((_value) => Math.round(_value))((((_lhs, _rhs) => (_lhs ** _rhs))((((_lhs, _rhs) => (_lhs % _rhs))((((_lhs, _rhs) => Math.floor(_lhs / _rhs))((((_lhs, _rhs) => (_lhs / _rhs))((((_lhs, _rhs) => (_lhs * _rhs))((((_value) => -(_value))((((_lhs, _rhs) => (_lhs + _rhs))(-5.4, 1)))), 2)), 3)), 2)), 3)), 2))))))))))))" == "(((_value) => !(_value))((isTrue((((_a, _b) => (_a() || _b()))((() => (Math.abs((Math.floor((((_lhs, _rhs) => (_lhs ** _rhs))((((_lhs, _rhs) => (_lhs % _rhs))((((_lhs, _rhs) => Math.floor(_lhs / _rhs))((((_lhs, _rhs) => (_lhs / _rhs))((((_lhs, _rhs) => (_lhs * _rhs))((((_value) => -(_value))((((_lhs, _rhs) => (_lhs + _rhs))(-5.4, 1)))), 2)), 3)), 2)), 3)), 2))))))), (() => (((_a, _b) => (_a() && _b()))((() => 2), (() => (((_value) => Math.round(_value))((((_lhs, _rhs) => (_lhs ** _rhs))((((_lhs, _rhs) => (_lhs % _rhs))((((_lhs, _rhs) => Math.floor(_lhs / _rhs))((((_lhs, _rhs) => (_lhs / _rhs))((((_lhs, _rhs) => (_lhs * _rhs))((((_value) => -(_value))((((_lhs, _rhs) => (_lhs + _rhs))(-5.4, 1)))), 2)), 3)), 2)), 3)), 2))))))))))))))"
) )
assert ( assert (
@ -1250,19 +1252,19 @@ def test_array_operations():
) )
assert ( assert (
str(ArrayVar.range(10)) str(ArrayVar.range(10))
== "(((_e1, _e2 = null, _step = 1) => range(_e1, _e2, _step))(10))" == "(((_e1, _e2 = null, _step = 1) => [...range(_e1, _e2, _step)])(10))"
) )
assert ( assert (
str(ArrayVar.range(1, 10)) str(ArrayVar.range(1, 10))
== "(((_e1, _e2 = null, _step = 1) => range(_e1, _e2, _step))(1, 10))" == "(((_e1, _e2 = null, _step = 1) => [...range(_e1, _e2, _step)])(1, 10))"
) )
assert ( assert (
str(ArrayVar.range(1, 10, 2)) str(ArrayVar.range(1, 10, 2))
== "(((_e1, _e2 = null, _step = 1) => range(_e1, _e2, _step))(1, 10, 2))" == "(((_e1, _e2 = null, _step = 1) => [...range(_e1, _e2, _step)])(1, 10, 2))"
) )
assert ( assert (
str(ArrayVar.range(1, 10, -1)) str(ArrayVar.range(1, 10, -1))
== "(((_e1, _e2 = null, _step = 1) => range(_e1, _e2, _step))(1, 10, -1))" == "(((_e1, _e2 = null, _step = 1) => [...range(_e1, _e2, _step)])(1, 10, -1))"
) )