def test_from_attr_value(self): a = Attr.from_attr_value("attr", "value", compare=False) assert a.name == "attr" assert a.default == "value" assert a.compare is False a = Attr.from_attr_value("attr", a) assert a.name == "attr" assert a.default == "value" assert a.compare is False f = dataclasses.field( default="value", init=False, repr=False, compare=False, hash=False, metadata={"foo": "bar"}, ) a = Attr.from_attr_value("attr", f) assert a.name == "attr" for attr in { "default", "default_factory", "init", "repr", "compare", "hash", "metadata", }: a_value = getattr(a, attr) f_value = getattr(f, attr) assert (a_value == f_value or a_value is MISSING and f_value is dataclasses.MISSING)
class Spec: attr: str = Attr(default="Hello World") unmanaged_attr = "Hi" invalidated_attr: str = Attr( default="Invalidated", repr=False, invalidated_by=["attr", "unmanaged_attr"], ) @spec_property(cache=True, invalidated_by=["unmanaged_attr"]) def invalidated_property(self): return self.unmanaged_attr
def test_constructor(self): with pytest.raises( ValueError, match=re.escape( "Only one of `default` and `default_factory` can be specified." ), ): Attr(default="Hi", default_factory=lambda: "Hi")
class MyClass: attr: List[str] = Attr() @attr.preparer def _(self, attr): return list(attr) @attr.item_preparer def _(self, attr_item): return str(attr_item)
def test_default_helpers(self): assert Attr(default="Hi").has_default assert Attr(default_factory=lambda: "Hi").has_default assert not Attr().has_default assert Attr(default="Hi").default_value == "Hi" assert Attr(default_factory=lambda: "Hi").default_value == "Hi" assert Attr().default_value is MISSING
def attr_spec2(self): return Attr.from_attr_value("attr", "value", type=List[Spec])
def attr_spec(self): return Attr.from_attr_value("attr", "value", type=List[str], prepare_item=lambda self, x: str(x))
def attr_spec2(self): return Attr.from_attr_value("attr", "value", type=KeyedSet[Spec, str])
class MyClass: attr1: MySpec = Attr() attr2: List[MySpec] = Attr(default_factory=[])
class MyClass: a: int = Attr(default=Attr())
def attr_spec2(self): return Attr.from_attr_value("attr", "value", type=Dict[str, Spec])
class SubSpec(Spec): sub_invalidated_attr: str = Attr( default="Also Invalidated", repr=False, invalidated_by=["invalidated_attr"], )
class Spec: attr: str = Attr(default="Hello World") hidden_attr: str = Attr( default="Hidden", init=False, repr=False, compare=False )