reflex/tests/components/core/test_cond.py
Khaleel Al-Adhami a5c73ad8e5
Use old serializer system in LiteralVar (#3875)
* use serializer system

* add checks for unsupported operands

* and and or are now supported

* format

* remove unnecessary call to JSON

* put base before rest

* fix failing testcase

* add hinting to get static analysis to complain

* damn

* big changes

* get typeguard from extensions

* please darglint

* dangit darglint

* remove one from vars

* add without data and use it in plotly

* DARGLINT

* change format for special props

* add pyi

* delete instances of Var.create

* modify client state to work

* fixed so much

* remove every Var.create

* delete all basevar stuff

* checkpoint

* fix pyi

* get older python to work

* dangit darglint

* add simple fix to last failing testcase

* remove var name unwrapped and put client state on immutable var

* fix older python

* fox event issues

* change forms pyi

* make test less strict

* use rx state directly

* add typeignore to page_id

* implement foreach

* delete .web states folder silly

* update reflex chakra

* fix issue when on mount or on unmount is not set

* nuke Var

* run pyi

* import immutablevar in critical location

* delete unwrap vars

* bring back array ref

* fix style props in app

* /health endpoint for K8 Liveness and Readiness probes (#3855)

* Added API Endpoint

* Added API Endpoint

* Added Unit Tests

* Added Unit Tests

* main

* Apply suggestions from Code Review

* Fix Ruff Formatting

* Update Socket Events

* Async Functions

* Update find_replace (#3886)

* [REF-3592]Promote `rx.progress` from radix themes (#3878)

* Promote `rx.progress` from radix themes

* fix pyi

* add warning when accessing `rx._x.progress`

* Use correct flexgen backend URL (#3891)

* Remove demo template (#3888)

* gitignore .web (#3885)

* update overflowY in AUTO_HEIGHT_JS from hidden to scroll (#3882)

* Retain mutability inside `async with self` block (#3884)

When emitting a state update, restore `_self_mutable` to the value it had
previously so that `yield` in the middle of `async with self` does not result
in an immutable StateProxy.

Fix #3869

* Include child imports in markdown component_map (#3883)

If a component in the markdown component_map contains children components, use
`_get_all_imports` to recursively enumerate them.

Fix #3880

* [REF-3570] Remove deprecated REDIS_URL syntax (#3892)

* mixin computed vars should only be applied to highest level state (#3833)

* improve state hierarchy validation, drop old testing special case (#3894)

* fix var dependency dicts (#3842)

* Adding array to array pluck operation. (#3868)

* fix initial state without cv fallback (#3670)

* add fragment to foreach (#3877)

* Update docker-example (#3324)

* /health endpoint for K8 Liveness and Readiness probes (#3855)

* Added API Endpoint

* Added API Endpoint

* Added Unit Tests

* Added Unit Tests

* main

* Apply suggestions from Code Review

* Fix Ruff Formatting

* Update Socket Events

* Async Functions

* /health endpoint for K8 Liveness and Readiness probes (#3855)

* Added API Endpoint

* Added API Endpoint

* Added Unit Tests

* Added Unit Tests

* main

* Apply suggestions from Code Review

* Fix Ruff Formatting

* Update Socket Events

* Async Functions

* Merge branch 'main' into use-old-serializer-in-literalvar

* [REF-3570] Remove deprecated REDIS_URL syntax (#3892)

* /health endpoint for K8 Liveness and Readiness probes (#3855)

* Added API Endpoint

* Added API Endpoint

* Added Unit Tests

* Added Unit Tests

* main

* Apply suggestions from Code Review

* Fix Ruff Formatting

* Update Socket Events

* Async Functions

* [REF-3570] Remove deprecated REDIS_URL syntax (#3892)

* remove extra var

Co-authored-by: Masen Furer <m_github@0x26.net>

* resolve typo

* write better doc for var.create

* return var value when we know it's literal var

* fix unit test

* less bloat for ToOperations

* simplify ImmutableComputedVar.__get__ (#3902)

* simplify ImmutableComputedVar.__get__

* ruff it

---------

Co-authored-by: Samarth Bhadane <samarthbhadane119@gmail.com>
Co-authored-by: Elijah Ahianyo <elijahahianyo@gmail.com>
Co-authored-by: Masen Furer <m_github@0x26.net>
Co-authored-by: benedikt-bartscher <31854409+benedikt-bartscher@users.noreply.github.com>
Co-authored-by: Vishnu Deva <vishnu.deva12@gmail.com>
Co-authored-by: abulvenz <a.eismann@senbax.de>
2024-09-10 11:43:37 -07:00

147 lines
4.2 KiB
Python

import json
from typing import Any, Union
import pytest
from reflex.components.base.fragment import Fragment
from reflex.components.core.cond import Cond, cond
from reflex.components.radix.themes.typography.text import Text
from reflex.ivars.base import ImmutableVar, LiteralVar, immutable_computed_var
from reflex.state import BaseState, State
from reflex.utils.format import format_state_name
@pytest.fixture
def cond_state(request):
class CondState(BaseState):
value: request.param["value_type"] = request.param["value"] # noqa
return CondState
def test_f_string_cond_interpolation():
# make sure backticks inside interpolation don't get escaped
var = LiteralVar.create(f"x {cond(True, 'a', 'b')}")
assert str(var) == '("x "+(true ? "a" : "b"))'
@pytest.mark.parametrize(
"cond_state",
[
pytest.param({"value_type": bool, "value": True}),
pytest.param({"value_type": int, "value": 0}),
pytest.param({"value_type": str, "value": "true"}),
],
indirect=True,
)
def test_validate_cond(cond_state: BaseState):
"""Test if cond can be a rx.Var with any values.
Args:
cond_state: A fixture.
"""
cond_component = cond(
cond_state.value,
Text.create("cond is True"),
Text.create("cond is False"),
)
cond_dict = cond_component.render() if type(cond_component) == Fragment else {}
assert cond_dict["name"] == "Fragment"
[condition] = cond_dict["children"]
assert condition["cond_state"] == f"isTrue({cond_state.get_full_name()}.value)"
# true value
true_value = condition["true_value"]
assert true_value["name"] == "Fragment"
[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(
"c1, c2",
[
(True, False),
(32, 0),
("hello", ""),
(2.3, 0.0),
(LiteralVar.create("a"), LiteralVar.create("b")),
],
)
def test_prop_cond(c1: Any, c2: Any):
"""Test if cond can be a prop.
Args:
c1: truth condition value
c2: false condition value
"""
prop_cond = cond(
True,
c1,
c2,
)
assert isinstance(prop_cond, ImmutableVar)
if not isinstance(c1, ImmutableVar):
c1 = json.dumps(c1)
if not isinstance(c2, ImmutableVar):
c2 = json.dumps(c2)
assert str(prop_cond) == f"(true ? {str(c1)} : {str(c2)})"
def test_cond_no_mix():
"""Test if cond can't mix components and props."""
with pytest.raises(ValueError):
cond(True, LiteralVar.create("hello"), Text.create("world"))
def test_cond_no_else():
"""Test if cond can be used without else."""
# Components should support the use of cond without else
comp = cond(True, Text.create("hello"))
assert isinstance(comp, Fragment)
comp = comp.children[0]
assert isinstance(comp, Cond)
assert comp.cond._decode() is True # type: ignore
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
with pytest.raises(ValueError):
cond(True, "hello") # type: ignore
def test_cond_computed_var():
"""Test if cond works with computed vars."""
class CondStateComputed(State):
@immutable_computed_var
def computed_int(self) -> int:
return 0
@immutable_computed_var
def computed_str(self) -> str:
return "a string"
comp = cond(True, CondStateComputed.computed_int, CondStateComputed.computed_str)
# TODO: shouln't this be a ComputedVar?
assert isinstance(comp, ImmutableVar)
state_name = format_state_name(CondStateComputed.get_full_name())
assert (
str(comp) == f"(true ? {state_name}.computed_int : {state_name}.computed_str)"
)
assert comp._var_type == Union[int, str]