123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128 |
- import json
- import typing
- from typing import Dict, List, Set, Tuple
- import pytest
- from pandas import DataFrame
- from reflex.base import Base
- from reflex.state import BaseState
- from reflex.vars import (
- BaseVar,
- ComputedVar,
- Var,
- )
- test_vars = [
- BaseVar(_var_name="prop1", _var_type=int),
- BaseVar(_var_name="key", _var_type=str),
- BaseVar(_var_name="value", _var_type=str)._var_set_state("state"),
- BaseVar(_var_name="local", _var_type=str, _var_is_local=True)._var_set_state(
- "state"
- ),
- BaseVar(_var_name="local2", _var_type=str, _var_is_local=True),
- ]
- @pytest.fixture
- def TestObj():
- class TestObj(Base):
- foo: int
- bar: str
- return TestObj
- @pytest.fixture
- def ParentState(TestObj):
- class ParentState(BaseState):
- foo: int
- bar: int
- @ComputedVar
- def var_without_annotation(self):
- return TestObj
- return ParentState
- @pytest.fixture
- def ChildState(ParentState, TestObj):
- class ChildState(ParentState):
- @ComputedVar
- def var_without_annotation(self):
- return TestObj
- return ChildState
- @pytest.fixture
- def GrandChildState(ChildState, TestObj):
- class GrandChildState(ChildState):
- @ComputedVar
- def var_without_annotation(self):
- return TestObj
- return GrandChildState
- @pytest.fixture
- def StateWithAnyVar(TestObj):
- class StateWithAnyVar(BaseState):
- @ComputedVar
- def var_without_annotation(self) -> typing.Any:
- return TestObj
- return StateWithAnyVar
- @pytest.fixture
- def StateWithCorrectVarAnnotation():
- class StateWithCorrectVarAnnotation(BaseState):
- @ComputedVar
- def var_with_annotation(self) -> str:
- return "Correct annotation"
- return StateWithCorrectVarAnnotation
- @pytest.fixture
- def StateWithWrongVarAnnotation(TestObj):
- class StateWithWrongVarAnnotation(BaseState):
- @ComputedVar
- def var_with_annotation(self) -> str:
- return TestObj
- return StateWithWrongVarAnnotation
- @pytest.mark.parametrize(
- "prop,expected",
- zip(
- test_vars,
- [
- "prop1",
- "key",
- "state.value",
- "state.local",
- "local2",
- ],
- ),
- )
- def test_full_name(prop, expected):
- """Test that the full name of a var is correct.
- Args:
- prop: The var to test.
- expected: The expected full name.
- """
- assert prop._var_full_name == expected
- @pytest.mark.parametrize(
- "prop,expected",
- zip(
- test_vars,
- ["{prop1}", "{key}", "{state.value}", "state.local", "local2"],
- ),
- )
- def test_str(prop, expected):
- """Test that the string representation of a var is correct.
- Args:
- prop: The var to test.
- expected: The expected string representation.
- """
- assert str(prop) == expected
- @pytest.mark.parametrize(
- "prop,expected",
- [
- (BaseVar(_var_name="p", _var_type=int), 0),
- (BaseVar(_var_name="p", _var_type=float), 0.0),
- (BaseVar(_var_name="p", _var_type=str), ""),
- (BaseVar(_var_name="p", _var_type=bool), False),
- (BaseVar(_var_name="p", _var_type=list), []),
- (BaseVar(_var_name="p", _var_type=dict), {}),
- (BaseVar(_var_name="p", _var_type=tuple), ()),
- (BaseVar(_var_name="p", _var_type=set), set()),
- ],
- )
- def test_default_value(prop, expected):
- """Test that the default value of a var is correct.
- Args:
- prop: The var to test.
- expected: The expected default value.
- """
- assert prop.get_default_value() == expected
- @pytest.mark.parametrize(
- "prop,expected",
- zip(
- test_vars,
- [
- "set_prop1",
- "set_key",
- "state.set_value",
- "state.set_local",
- "set_local2",
- ],
- ),
- )
- def test_get_setter(prop, expected):
- """Test that the name of the setter function of a var is correct.
- Args:
- prop: The var to test.
- expected: The expected name of the setter function.
- """
- assert prop.get_setter_name() == expected
- @pytest.mark.parametrize(
- "value,expected",
- [
- (None, None),
- (1, BaseVar(_var_name="1", _var_type=int, _var_is_local=True)),
- ("key", BaseVar(_var_name="key", _var_type=str, _var_is_local=True)),
- (3.14, BaseVar(_var_name="3.14", _var_type=float, _var_is_local=True)),
- ([1, 2, 3], BaseVar(_var_name="[1, 2, 3]", _var_type=list, _var_is_local=True)),
- (
- {"a": 1, "b": 2},
- BaseVar(_var_name='{"a": 1, "b": 2}', _var_type=dict, _var_is_local=True),
- ),
- ],
- )
- def test_create(value, expected):
- """Test the var create function.
- Args:
- value: The value to create a var from.
- expected: The expected name of the setter function.
- """
- prop = Var.create(value)
- if value is None:
- assert prop == expected
- else:
- assert prop.equals(expected) # type: ignore
- def test_create_type_error():
- """Test the var create function when inputs type error."""
- class ErrorType:
- pass
- value = ErrorType()
- with pytest.raises(TypeError):
- Var.create(value)
- def v(value) -> Var:
- val = (
- Var.create(json.dumps(value), _var_is_string=True, _var_is_local=False)
- if isinstance(value, str)
- else Var.create(value, _var_is_local=False)
- )
- assert val is not None
- return val
- def test_basic_operations(TestObj):
- """Test the var operations.
- Args:
- TestObj: The test object.
- """
- assert str(v(1) == v(2)) == "{(1 === 2)}"
- assert str(v(1) != v(2)) == "{(1 !== 2)}"
- assert str(v(1) < v(2)) == "{(1 < 2)}"
- assert str(v(1) <= v(2)) == "{(1 <= 2)}"
- assert str(v(1) > v(2)) == "{(1 > 2)}"
- assert str(v(1) >= v(2)) == "{(1 >= 2)}"
- assert str(v(1) + v(2)) == "{(1 + 2)}"
- assert str(v(1) - v(2)) == "{(1 - 2)}"
- assert str(v(1) * v(2)) == "{(1 * 2)}"
- assert str(v(1) / v(2)) == "{(1 / 2)}"
- assert str(v(1) // v(2)) == "{Math.floor(1 / 2)}"
- assert str(v(1) % v(2)) == "{(1 % 2)}"
- assert str(v(1) ** v(2)) == "{Math.pow(1 , 2)}"
- assert str(v(1) & v(2)) == "{(1 && 2)}"
- assert str(v(1) | v(2)) == "{(1 || 2)}"
- assert str(v([1, 2, 3])[v(0)]) == "{[1, 2, 3].at(0)}"
- assert str(v({"a": 1, "b": 2})["a"]) == '{{"a": 1, "b": 2}["a"]}'
- assert (
- str(BaseVar(_var_name="foo", _var_type=TestObj)._var_set_state("state").bar)
- == "{state.foo.bar}"
- )
- assert str(abs(v(1))) == "{Math.abs(1)}"
- assert str(v([1, 2, 3]).length()) == "{[1, 2, 3].length}"
- assert str(v([1, 2]) + v([3, 4])) == "{spreadArraysOrObjects([1, 2] , [3, 4])}"
- # Tests for reverse operation
- assert str(v([1, 2, 3]).reverse()) == "{[...[1, 2, 3]].reverse()}"
- assert str(v(["1", "2", "3"]).reverse()) == '{[...["1", "2", "3"]].reverse()}'
- assert (
- str(BaseVar(_var_name="foo", _var_type=list)._var_set_state("state").reverse())
- == "{[...state.foo].reverse()}"
- )
- assert (
- str(BaseVar(_var_name="foo", _var_type=list).reverse())
- == "{[...foo].reverse()}"
- )
- @pytest.mark.parametrize(
- "var, expected",
- [
- (v([1, 2, 3]), "[1, 2, 3]"),
- (v(["1", "2", "3"]), '["1", "2", "3"]'),
- (BaseVar(_var_name="foo", _var_type=list)._var_set_state("state"), "state.foo"),
- (BaseVar(_var_name="foo", _var_type=list), "foo"),
- (v((1, 2, 3)), "[1, 2, 3]"),
- (v(("1", "2", "3")), '["1", "2", "3"]'),
- (
- BaseVar(_var_name="foo", _var_type=tuple)._var_set_state("state"),
- "state.foo",
- ),
- (BaseVar(_var_name="foo", _var_type=tuple), "foo"),
- ],
- )
- def test_list_tuple_contains(var, expected):
- assert str(var.contains(1)) == f"{{{expected}.includes(1)}}"
- assert str(var.contains("1")) == f'{{{expected}.includes("1")}}'
- assert str(var.contains(v(1))) == f"{{{expected}.includes(1)}}"
- assert str(var.contains(v("1"))) == f'{{{expected}.includes("1")}}'
- other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
- other_var = BaseVar(_var_name="other", _var_type=str)
- assert str(var.contains(other_state_var)) == f"{{{expected}.includes(state.other)}}"
- assert str(var.contains(other_var)) == f"{{{expected}.includes(other)}}"
- @pytest.mark.parametrize(
- "var, expected",
- [
- (v("123"), json.dumps("123")),
- (BaseVar(_var_name="foo", _var_type=str)._var_set_state("state"), "state.foo"),
- (BaseVar(_var_name="foo", _var_type=str), "foo"),
- ],
- )
- def test_str_contains(var, expected):
- assert str(var.contains("1")) == f'{{{expected}.includes("1")}}'
- assert str(var.contains(v("1"))) == f'{{{expected}.includes("1")}}'
- other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
- other_var = BaseVar(_var_name="other", _var_type=str)
- assert str(var.contains(other_state_var)) == f"{{{expected}.includes(state.other)}}"
- assert str(var.contains(other_var)) == f"{{{expected}.includes(other)}}"
- @pytest.mark.parametrize(
- "var, expected",
- [
- (v({"a": 1, "b": 2}), '{"a": 1, "b": 2}'),
- (BaseVar(_var_name="foo", _var_type=dict)._var_set_state("state"), "state.foo"),
- (BaseVar(_var_name="foo", _var_type=dict), "foo"),
- ],
- )
- def test_dict_contains(var, expected):
- assert str(var.contains(1)) == f"{{{expected}.hasOwnProperty(1)}}"
- assert str(var.contains("1")) == f'{{{expected}.hasOwnProperty("1")}}'
- assert str(var.contains(v(1))) == f"{{{expected}.hasOwnProperty(1)}}"
- assert str(var.contains(v("1"))) == f'{{{expected}.hasOwnProperty("1")}}'
- other_state_var = BaseVar(_var_name="other", _var_type=str)._var_set_state("state")
- other_var = BaseVar(_var_name="other", _var_type=str)
- assert (
- str(var.contains(other_state_var))
- == f"{{{expected}.hasOwnProperty(state.other)}}"
- )
- assert str(var.contains(other_var)) == f"{{{expected}.hasOwnProperty(other)}}"
- @pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="list", _var_type=List[int]),
- BaseVar(_var_name="tuple", _var_type=Tuple[int, int]),
- BaseVar(_var_name="str", _var_type=str),
- ],
- )
- def test_var_indexing_lists(var):
- """Test that we can index into str, list or tuple vars.
- Args:
- var : The str, list or tuple base var.
- """
- # Test basic indexing.
- assert str(var[0]) == f"{{{var._var_name}.at(0)}}"
- assert str(var[1]) == f"{{{var._var_name}.at(1)}}"
- # Test negative indexing.
- assert str(var[-1]) == f"{{{var._var_name}.at(-1)}}"
- @pytest.mark.parametrize(
- "var, index",
- [
- (BaseVar(_var_name="lst", _var_type=List[int]), [1, 2]),
- (BaseVar(_var_name="lst", _var_type=List[int]), {"name": "dict"}),
- (BaseVar(_var_name="lst", _var_type=List[int]), {"set"}),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- (
- 1,
- 2,
- ),
- ),
- (BaseVar(_var_name="lst", _var_type=List[int]), 1.5),
- (BaseVar(_var_name="lst", _var_type=List[int]), "str"),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="string_var", _var_type=str),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="float_var", _var_type=float),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="list_var", _var_type=List[int]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="set_var", _var_type=Set[str]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
- ),
- (BaseVar(_var_name="str", _var_type=str), [1, 2]),
- (BaseVar(_var_name="lst", _var_type=str), {"name": "dict"}),
- (BaseVar(_var_name="lst", _var_type=str), {"set"}),
- (
- BaseVar(_var_name="lst", _var_type=str),
- BaseVar(_var_name="string_var", _var_type=str),
- ),
- (
- BaseVar(_var_name="lst", _var_type=str),
- BaseVar(_var_name="float_var", _var_type=float),
- ),
- (BaseVar(_var_name="str", _var_type=Tuple[str]), [1, 2]),
- (BaseVar(_var_name="lst", _var_type=Tuple[str]), {"name": "dict"}),
- (BaseVar(_var_name="lst", _var_type=Tuple[str]), {"set"}),
- (
- BaseVar(_var_name="lst", _var_type=Tuple[str]),
- BaseVar(_var_name="string_var", _var_type=str),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Tuple[str]),
- BaseVar(_var_name="float_var", _var_type=float),
- ),
- ],
- )
- def test_var_unsupported_indexing_lists(var, index):
- """Test unsupported indexing throws a type error.
- Args:
- var: The base var.
- index: The base var index.
- """
- with pytest.raises(TypeError):
- var[index]
- @pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="lst", _var_type=List[int]),
- BaseVar(_var_name="tuple", _var_type=Tuple[int, int]),
- BaseVar(_var_name="str", _var_type=str),
- ],
- )
- def test_var_list_slicing(var):
- """Test that we can slice into str, list or tuple vars.
- Args:
- var : The str, list or tuple base var.
- """
- assert str(var[:1]) == f"{{{var._var_name}.slice(0, 1)}}"
- assert str(var[:1]) == f"{{{var._var_name}.slice(0, 1)}}"
- assert str(var[:]) == f"{{{var._var_name}.slice(0, undefined)}}"
- def test_dict_indexing():
- """Test that we can index into dict vars."""
- dct = BaseVar(_var_name="dct", _var_type=Dict[str, int])
- # Check correct indexing.
- assert str(dct["a"]) == '{dct["a"]}'
- assert str(dct["asdf"]) == '{dct["asdf"]}'
- @pytest.mark.parametrize(
- "var, index",
- [
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- [1, 2],
- ),
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- {"name": "dict"},
- ),
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- {"set"},
- ),
- (
- BaseVar(_var_name="dict", _var_type=Dict[str, str]),
- (
- 1,
- 2,
- ),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Dict[str, str]),
- BaseVar(_var_name="list_var", _var_type=List[int]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Dict[str, str]),
- BaseVar(_var_name="set_var", _var_type=Set[str]),
- ),
- (
- BaseVar(_var_name="lst", _var_type=Dict[str, str]),
- BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- [1, 2],
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- {"name": "dict"},
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- {"set"},
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- (
- 1,
- 2,
- ),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- BaseVar(_var_name="list_var", _var_type=List[int]),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- BaseVar(_var_name="set_var", _var_type=Set[str]),
- ),
- (
- BaseVar(_var_name="df", _var_type=DataFrame),
- BaseVar(_var_name="dict_var", _var_type=Dict[str, str]),
- ),
- ],
- )
- def test_var_unsupported_indexing_dicts(var, index):
- """Test unsupported indexing throws a type error.
- Args:
- var: The base var.
- index: The base var index.
- """
- with pytest.raises(TypeError):
- var[index]
- @pytest.mark.parametrize(
- "fixture,full_name",
- [
- ("ParentState", "parent_state.var_without_annotation"),
- ("ChildState", "parent_state__child_state.var_without_annotation"),
- (
- "GrandChildState",
- "parent_state__child_state__grand_child_state.var_without_annotation",
- ),
- ("StateWithAnyVar", "state_with_any_var.var_without_annotation"),
- ],
- )
- def test_computed_var_without_annotation_error(request, fixture, full_name):
- """Test that a type error is thrown when an attribute of a computed var is
- accessed without annotating the computed var.
- Args:
- request: Fixture Request.
- fixture: The state fixture.
- full_name: The full name of the state var.
- """
- with pytest.raises(TypeError) as err:
- state = request.getfixturevalue(fixture)
- state.var_without_annotation.foo
- assert (
- err.value.args[0]
- == f"You must provide an annotation for the state var `{full_name}`. Annotation cannot be `typing.Any`"
- )
- @pytest.mark.parametrize(
- "fixture,full_name",
- [
- (
- "StateWithCorrectVarAnnotation",
- "state_with_correct_var_annotation.var_with_annotation",
- ),
- (
- "StateWithWrongVarAnnotation",
- "state_with_wrong_var_annotation.var_with_annotation",
- ),
- ],
- )
- def test_computed_var_with_annotation_error(request, fixture, full_name):
- """Test that an Attribute error is thrown when a non-existent attribute of an annotated computed var is
- accessed or when the wrong annotation is provided to a computed var.
- Args:
- request: Fixture Request.
- fixture: The state fixture.
- full_name: The full name of the state var.
- """
- with pytest.raises(AttributeError) as err:
- state = request.getfixturevalue(fixture)
- state.var_with_annotation.foo
- assert (
- err.value.args[0]
- == f"The State var `{full_name}` has no attribute 'foo' or may have been annotated wrongly."
- )
- @pytest.mark.parametrize(
- "out, expected",
- [
- (f"{BaseVar(_var_name='var', _var_type=str)}", "${var}"),
- (
- f"testing f-string with {BaseVar(_var_name='myvar', _var_type=int)._var_set_state('state')}",
- 'testing f-string with $<reflex.Var>{"state": "state", "imports": {"/utils/context": [{"tag": "StateContexts", "is_default": false, "alias": null, "install": true, "render": true}], "react": [{"tag": "useContext", "is_default": false, "alias": null, "install": true, "render": true}]}, "hooks": ["const state = useContext(StateContexts.state)"]}</reflex.Var>{state.myvar}',
- ),
- (
- f"testing local f-string {BaseVar(_var_name='x', _var_is_local=True, _var_type=str)}",
- "testing local f-string x",
- ),
- ],
- )
- def test_fstrings(out, expected):
- assert out == expected
- @pytest.mark.parametrize(
- ("value", "expect_state"),
- [
- ([1], ""),
- ({"a": 1}, ""),
- ([Var.create_safe(1)._var_set_state("foo")], "foo"),
- ({"a": Var.create_safe(1)._var_set_state("foo")}, "foo"),
- ],
- )
- def test_extract_state_from_container(value, expect_state):
- """Test that _var_state is extracted from containers containing BaseVar.
- Args:
- value: The value to create a var from.
- expect_state: The expected state.
- """
- assert Var.create_safe(value)._var_state == expect_state
- def test_fstring_roundtrip():
- """Test that f-string roundtrip carries state."""
- var = BaseVar.create_safe("var")._var_set_state("state")
- rt_var = Var.create_safe(f"{var}")
- assert var._var_state == rt_var._var_state
- assert var._var_full_name_needs_state_prefix
- assert not rt_var._var_full_name_needs_state_prefix
- assert rt_var._var_name == var._var_full_name
- @pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="var", _var_type=int),
- BaseVar(_var_name="var", _var_type=float),
- BaseVar(_var_name="var", _var_type=str),
- BaseVar(_var_name="var", _var_type=bool),
- BaseVar(_var_name="var", _var_type=dict),
- BaseVar(_var_name="var", _var_type=tuple),
- BaseVar(_var_name="var", _var_type=set),
- BaseVar(_var_name="var", _var_type=None),
- ],
- )
- def test_unsupported_types_for_reverse(var):
- """Test that unsupported types for reverse throw a type error.
- Args:
- var: The base var.
- """
- with pytest.raises(TypeError) as err:
- var.reverse()
- assert err.value.args[0] == f"Cannot reverse non-list var var."
- @pytest.mark.parametrize(
- "var",
- [
- BaseVar(_var_name="var", _var_type=int),
- BaseVar(_var_name="var", _var_type=float),
- BaseVar(_var_name="var", _var_type=bool),
- BaseVar(_var_name="var", _var_type=set),
- BaseVar(_var_name="var", _var_type=None),
- ],
- )
- def test_unsupported_types_for_contains(var):
- """Test that unsupported types for contains throw a type error.
- Args:
- var: The base var.
- """
- with pytest.raises(TypeError) as err:
- assert var.contains(1)
- assert (
- err.value.args[0]
- == f"Var var of type {var._var_type} does not support contains check."
- )
- @pytest.mark.parametrize(
- "other",
- [
- BaseVar(_var_name="other", _var_type=int),
- BaseVar(_var_name="other", _var_type=float),
- BaseVar(_var_name="other", _var_type=bool),
- BaseVar(_var_name="other", _var_type=list),
- BaseVar(_var_name="other", _var_type=dict),
- BaseVar(_var_name="other", _var_type=tuple),
- BaseVar(_var_name="other", _var_type=set),
- ],
- )
- def test_unsupported_types_for_string_contains(other):
- with pytest.raises(TypeError) as err:
- assert BaseVar(_var_name="var", _var_type=str).contains(other)
- assert (
- err.value.args[0]
- == f"'in <string>' requires string as left operand, not {other._var_type}"
- )
- def test_unsupported_default_contains():
- with pytest.raises(TypeError) as err:
- assert 1 in BaseVar(_var_name="var", _var_type=str)
- assert (
- err.value.args[0]
- == "'in' operator not supported for Var types, use Var.contains() instead."
- )
- @pytest.mark.parametrize(
- "operand1_var,operand2_var,operators",
- [
- (
- Var.create(10),
- Var.create(5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5),
- ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
- ),
- (
- Var.create(5),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5.5),
- ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
- ),
- (
- Var.create(10.5),
- Var.create(True),
- ["+", "-", "/", "//", "*", "%", "**", ">", "<", "<=", ">="],
- ),
- (Var.create("10"), Var.create("5"), ["+", ">", "<", "<=", ">="]),
- (Var.create([10, 20]), Var.create([5, 6]), ["+", ">", "<", "<=", ">="]),
- (Var.create([10, 20]), Var.create(5), ["*"]),
- (Var.create([10, 20]), Var.create(True), ["*"]),
- (
- Var.create(True),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "&",
- ],
- ),
- ],
- )
- def test_valid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
- """Test that operations do not raise a TypeError.
- Args:
- operand1_var: left operand.
- operand2_var: right operand.
- operators: list of supported operators.
- """
- for operator in operators:
- operand1_var.operation(op=operator, other=operand2_var)
- operand1_var.operation(op=operator, other=operand2_var, flip=True)
- @pytest.mark.parametrize(
- "operand1_var,operand2_var,operators",
- [
- (
- Var.create(10),
- Var.create(5),
- [
- "^",
- "<<",
- ">>",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5),
- [
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(True),
- [
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create(10.5),
- Var.create(5.5),
- [
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create("10"),
- Var.create("5"),
- [
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create([5, 6]),
- [
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create(5),
- [
- "+",
- "-",
- "/",
- "//",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create("5"),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create({"key": "value"}),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create([10, 20]),
- Var.create(5.5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create({"another_key": "another_value"}),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create(5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create(True),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create(5.5),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- (
- Var.create({"key": "value"}),
- Var.create("5"),
- [
- "+",
- "-",
- "/",
- "//",
- "*",
- "%",
- "**",
- ">",
- "<",
- "<=",
- ">=",
- "|",
- "^",
- "<<",
- ">>",
- "&",
- ],
- ),
- ],
- )
- def test_invalid_var_operations(operand1_var: Var, operand2_var, operators: List[str]):
- for operator in operators:
- with pytest.raises(TypeError):
- operand1_var.operation(op=operator, other=operand2_var)
- with pytest.raises(TypeError):
- operand1_var.operation(op=operator, other=operand2_var, flip=True)
|