Skip to content

Commit

Permalink
feat: computed should be glitch free
Browse files Browse the repository at this point in the history
This is only a failing test for now to demonstrate what can go wrong.
1) without an error, the system can see an invalid state
2) an invalid state can also trigger an exception

See https://dev.to/this-is-learning/derivations-in-reactivity-4fo1
for the loose definition of glitch-free
  • Loading branch information
maartenbreddels committed Apr 12, 2024
1 parent a573f95 commit a6fe198
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions tests/unit/toestand_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1233,3 +1233,59 @@ class Person(BaseModel):
assert person.get().height == 2.0
assert Ref(person.fields.name).get() == "Maria"
assert Ref(person.fields.height).get() == 2.0
@dataclasses.dataclass(frozen=True)
class Profile:
name: str
surname: str


def test_computed_glitch_invalid_state_without_error():
from solara.toestand import Computed

profile = Reactive(Profile(name="John", surname="Doe"))

name = Computed(lambda: profile.value.name)
surname = Computed(lambda: profile.value.surname)

computed_initials = []

def compute_initials():
initials = name.value[0] + surname.value[0]
computed_initials.append(initials)
return initials

initials = Computed(compute_initials)

assert name.value == "John"
assert surname.value == "Doe"
assert initials.value == "JD"
assert computed_initials == ["JD"]

profile.value = Profile(name="Rosa", surname="Breddels")

assert name.value == "Rosa"
assert surname.value == "Breddels"
assert initials.value == "RB"
assert computed_initials == ["JD", "RB"]


@dataclasses.dataclass(frozen=True)
class CountrySelection:
countries: List[str]
selected: str


def test_computed_glitch_invalid_state_with_error():
from solara.toestand import Computed

country_selection = Reactive(CountrySelection(countries=["Netherlands", "Belgium", "Germany"], selected="Germany"))

countries = Computed(lambda: country_selection.value.countries)
selected = Computed(lambda: country_selection.value.selected)
selected_index = Computed(lambda: countries.value.index(selected.value))

assert selected_index.value == 2

country_selection.value = CountrySelection(countries=["China", "Japan"], selected="Japan")

assert selected_index.value == 1

0 comments on commit a6fe198

Please sign in to comment.