-
-
Notifications
You must be signed in to change notification settings - Fork 386
/
Copy pathtest_custom_fields.py
77 lines (52 loc) · 1.71 KB
/
test_custom_fields.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
"""Tests for the custom attributes functionality."""
from __future__ import annotations
from functools import partial
from typing import Generic, TypeVar
from attrs import Attribute, AttrsInstance, define
from attrs.custom_fields import custom_fields
T = TypeVar("T")
@define
class CustomAttribute(Generic[T]):
"""A custom attribute, for tests."""
cl: type[AttrsInstance]
name: str
attribute_type: T
@classmethod
def _from_attrs_attribute(
cls, attrs_cls: type[AttrsInstance], attribute: Attribute[T]
):
return cls(attrs_cls, attribute.name, attribute.type)
cust_fields = partial(custom_fields, attribute_model=CustomAttribute)
cust_resolved_fields = partial(
custom_fields, attribute_model=CustomAttribute, resolve_types=True
)
def test_simple_custom_fields():
"""Simple custom attribute overriding works."""
@define
class Test:
a: int
b: float
for _ in range(2):
# Do it twice to test caching.
f = cust_fields(Test)
assert isinstance(f.a, CustomAttribute)
assert isinstance(f.b, CustomAttribute)
assert not hasattr(f, "c")
assert f.a.name == "a"
assert f.a.cl is Test
assert f.a.attribute_type == "int"
def test_resolved_custom_fields():
"""Resolved custom attributes work."""
@define
class Test:
a: int
b: float
for _ in range(2):
# Do it twice to test caching.
f = cust_resolved_fields(Test)
assert isinstance(f.a, CustomAttribute)
assert isinstance(f.b, CustomAttribute)
assert not hasattr(f, "c")
assert f.a.name == "a"
assert f.a.cl is Test
assert f.a.attribute_type is int