I can bind elements
This commit is contained in:
96
tests/core/test_bindings.py
Normal file
96
tests/core/test_bindings.py
Normal file
@@ -0,0 +1,96 @@
|
||||
from dataclasses import dataclass
|
||||
|
||||
import pytest
|
||||
from fasthtml.components import Label, Input
|
||||
from myutils.observable import collect_return_values
|
||||
|
||||
from myfasthtml.core.bindings import BindingsManager, Binding
|
||||
|
||||
|
||||
@dataclass
|
||||
class Data:
|
||||
value: str = "Hello World"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def reset_binding_manager():
|
||||
BindingsManager.reset()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def data():
|
||||
return Data()
|
||||
|
||||
|
||||
def test_i_can_register_a_binding(data):
|
||||
binding = Binding(data, "value")
|
||||
|
||||
assert binding.id is not None
|
||||
assert binding.data is data
|
||||
assert binding.data_attr == 'value'
|
||||
|
||||
|
||||
def test_i_can_register_a_binding_with_default_attr(data):
|
||||
binding = Binding(data)
|
||||
|
||||
assert binding.id is not None
|
||||
assert binding.data is data
|
||||
assert binding.data_attr == 'value'
|
||||
|
||||
|
||||
def test_i_can_retrieve_a_registered_binding(data):
|
||||
binding = Binding(data)
|
||||
assert BindingsManager.get_binding(binding.id) is binding
|
||||
|
||||
|
||||
def test_i_can_reset_bindings(data):
|
||||
Binding(data)
|
||||
assert len(BindingsManager.bindings) != 0
|
||||
|
||||
BindingsManager.reset()
|
||||
assert len(BindingsManager.bindings) == 0
|
||||
|
||||
|
||||
def test_i_can_bind_an_element_to_a_binding(data):
|
||||
elt = Label("hello", id="label_id")
|
||||
Binding(data, ft=elt)
|
||||
|
||||
data.value = "new value"
|
||||
|
||||
assert elt.children[0] == "new value"
|
||||
assert elt.attrs["hx-swap-oob"] == "true"
|
||||
assert elt.attrs["id"] == "label_id"
|
||||
|
||||
|
||||
def test_i_can_bind_an_element_attr_to_a_binding(data):
|
||||
elt = Input(value="somme value", id="input_id")
|
||||
|
||||
Binding(data, ft=elt, ft_attr="value")
|
||||
|
||||
data.value = "new value"
|
||||
|
||||
assert elt.attrs["value"] == "new value"
|
||||
assert elt.attrs["hx-swap-oob"] == "true"
|
||||
assert elt.attrs["id"] == "input_id"
|
||||
|
||||
|
||||
def test_bound_element_has_an_id():
|
||||
elt = Label("hello")
|
||||
assert elt.attrs.get("id", None) is None
|
||||
|
||||
Binding(Data(), ft=elt)
|
||||
assert elt.attrs.get("id", None) is not None
|
||||
|
||||
|
||||
def test_i_can_collect_updates_values(data):
|
||||
elt = Label("hello")
|
||||
Binding(data, ft=elt)
|
||||
|
||||
data.value = "new value"
|
||||
collected = collect_return_values(data)
|
||||
assert collected == [elt]
|
||||
|
||||
# a second time to ensure no side effect
|
||||
data.value = "another value"
|
||||
collected = collect_return_values(data)
|
||||
assert collected == [elt]
|
||||
Reference in New Issue
Block a user