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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
|
"""
Tests for PEP-526 type annotations.
Python 3.6+ only.
"""
import types
import typing
import pytest
import attr
from attr._make import _classvar_prefixes
from attr.exceptions import UnannotatedAttributeError
class TestAnnotations:
"""
Tests for types derived from variable annotations (PEP-526).
"""
def test_basic_annotations(self):
"""
Sets the `Attribute.type` attr from basic type annotations.
"""
@attr.s
class C:
x: int = attr.ib()
y = attr.ib(type=str)
z = attr.ib()
assert int is attr.fields(C).x.type
assert str is attr.fields(C).y.type
assert None is attr.fields(C).z.type
assert C.__init__.__annotations__ == {
"x": int,
"y": str,
"return": None,
}
def test_catches_basic_type_conflict(self):
"""
Raises ValueError if type is specified both ways.
"""
with pytest.raises(ValueError) as e:
@attr.s
class C:
x: int = attr.ib(type=int)
assert (
"Type annotation and type argument cannot both be present",
) == e.value.args
def test_typing_annotations(self):
"""
Sets the `Attribute.type` attr from typing annotations.
"""
@attr.s
class C:
x: typing.List[int] = attr.ib()
y = attr.ib(type=typing.Optional[str])
assert typing.List[int] is attr.fields(C).x.type
assert typing.Optional[str] is attr.fields(C).y.type
assert C.__init__.__annotations__ == {
"x": typing.List[int],
"y": typing.Optional[str],
"return": None,
}
def test_only_attrs_annotations_collected(self):
"""
Annotations that aren't set to an attr.ib are ignored.
"""
@attr.s
class C:
x: typing.List[int] = attr.ib()
y: int
assert 1 == len(attr.fields(C))
assert C.__init__.__annotations__ == {
"x": typing.List[int],
"return": None,
}
@pytest.mark.parametrize("slots", [True, False])
def test_auto_attribs(self, slots):
"""
If *auto_attribs* is True, bare annotations are collected too.
Defaults work and class variables are ignored.
"""
@attr.s(auto_attribs=True, slots=slots)
class C:
cls_var: typing.ClassVar[int] = 23
a: int
x: typing.List[int] = attr.Factory(list)
y: int = 2
z: int = attr.ib(default=3)
foo: typing.Any = None
i = C(42)
assert "C(a=42, x=[], y=2, z=3, foo=None)" == repr(i)
attr_names = set(a.name for a in C.__attrs_attrs__)
assert "a" in attr_names # just double check that the set works
assert "cls_var" not in attr_names
assert int == attr.fields(C).a.type
assert attr.Factory(list) == attr.fields(C).x.default
assert typing.List[int] == attr.fields(C).x.type
assert int == attr.fields(C).y.type
assert 2 == attr.fields(C).y.default
assert int == attr.fields(C).z.type
assert typing.Any == attr.fields(C).foo.type
# Class body is clean.
if slots is False:
with pytest.raises(AttributeError):
C.y
assert 2 == i.y
else:
assert isinstance(C.y, types.MemberDescriptorType)
i.y = 23
assert 23 == i.y
assert C.__init__.__annotations__ == {
"a": int,
"x": typing.List[int],
"y": int,
"z": int,
"foo": typing.Any,
"return": None,
}
@pytest.mark.parametrize("slots", [True, False])
def test_auto_attribs_unannotated(self, slots):
"""
Unannotated `attr.ib`s raise an error.
"""
with pytest.raises(UnannotatedAttributeError) as e:
@attr.s(slots=slots, auto_attribs=True)
class C:
v = attr.ib()
x: int
y = attr.ib()
z: str
assert (
"The following `attr.ib`s lack a type annotation: v, y.",
) == e.value.args
@pytest.mark.parametrize("slots", [True, False])
def test_auto_attribs_subclassing(self, slots):
"""
Attributes from base classes are inherited, it doesn't matter if the
subclass has annotations or not.
Ref #291
"""
@attr.s(slots=slots, auto_attribs=True)
class A:
a: int = 1
@attr.s(slots=slots, auto_attribs=True)
class B(A):
b: int = 2
@attr.s(slots=slots, auto_attribs=True)
class C(A):
pass
assert "B(a=1, b=2)" == repr(B())
assert "C(a=1)" == repr(C())
assert A.__init__.__annotations__ == {"a": int, "return": None}
assert B.__init__.__annotations__ == {
"a": int,
"b": int,
"return": None,
}
assert C.__init__.__annotations__ == {"a": int, "return": None}
def test_converter_annotations(self):
"""
Attributes with converters don't have annotations.
"""
@attr.s(auto_attribs=True)
class A:
a: int = attr.ib(converter=int)
assert A.__init__.__annotations__ == {"return": None}
@pytest.mark.parametrize("slots", [True, False])
@pytest.mark.parametrize("classvar", _classvar_prefixes)
def test_annotations_strings(self, slots, classvar):
"""
String annotations are passed into __init__ as is.
"""
@attr.s(auto_attribs=True, slots=slots)
class C:
cls_var: classvar + "[int]" = 23
a: "int"
x: "typing.List[int]" = attr.Factory(list)
y: "int" = 2
z: "int" = attr.ib(default=3)
foo: "typing.Any" = None
assert C.__init__.__annotations__ == {
"a": "int",
"x": "typing.List[int]",
"y": "int",
"z": "int",
"foo": "typing.Any",
"return": None,
}
def test_keyword_only_auto_attribs(self):
"""
`kw_only` propagates to attributes defined via `auto_attribs`.
"""
@attr.s(auto_attribs=True, kw_only=True)
class C:
x: int
y: int
with pytest.raises(TypeError):
C(0, 1)
with pytest.raises(TypeError):
C(x=0)
c = C(x=0, y=1)
assert c.x == 0
assert c.y == 1
def test_base_class_variable(self):
"""
Base class' class variables can be overridden with an attribute
without resorting to using an explicit `attr.ib()`.
"""
class Base:
x: int = 42
@attr.s(auto_attribs=True)
class C(Base):
x: int
assert 1 == C(1).x
|