2017-09-17 14:22:49 +00:00
|
|
|
"""
|
|
|
|
Tests for PEP-526 type annotations.
|
|
|
|
"""
|
|
|
|
|
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
|
|
|
|
import pytest
|
|
|
|
|
2017-10-02 17:32:10 +00:00
|
|
|
import attr
|
2017-09-17 14:22:49 +00:00
|
|
|
|
|
|
|
import typing
|
|
|
|
|
|
|
|
|
|
|
|
class TestAnnotations(object):
|
|
|
|
"""
|
|
|
|
Tests for types derived from variable annotations (PEP-526).
|
|
|
|
"""
|
|
|
|
|
|
|
|
def test_basic_annotations(self):
|
|
|
|
"""
|
|
|
|
Sets the `Attribute.type` attr from basic type annotations.
|
|
|
|
"""
|
2017-10-02 17:32:10 +00:00
|
|
|
@attr.s
|
2017-09-17 14:22:49 +00:00
|
|
|
class C(object):
|
2017-10-02 17:32:10 +00:00
|
|
|
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
|
2017-09-17 14:22:49 +00:00
|
|
|
|
|
|
|
def test_catches_basic_type_conflict(self):
|
|
|
|
"""
|
|
|
|
Raises ValueError type is specified both ways.
|
|
|
|
"""
|
|
|
|
with pytest.raises(ValueError) as e:
|
2017-10-02 17:32:10 +00:00
|
|
|
@attr.s
|
2017-09-17 14:22:49 +00:00
|
|
|
class C:
|
2017-10-02 17:32:10 +00:00
|
|
|
x: int = attr.ib(type=int)
|
|
|
|
|
2017-09-17 14:22:49 +00:00
|
|
|
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.
|
|
|
|
"""
|
2017-10-02 17:32:10 +00:00
|
|
|
@attr.s
|
2017-09-17 14:22:49 +00:00
|
|
|
class C(object):
|
2017-10-02 17:32:10 +00:00
|
|
|
x: typing.List[int] = attr.ib()
|
|
|
|
y = attr.ib(type=typing.Optional[str])
|
2017-09-17 14:22:49 +00:00
|
|
|
|
2017-10-02 17:32:10 +00:00
|
|
|
assert typing.List[int] is attr.fields(C).x.type
|
|
|
|
assert typing.Optional[str] is attr.fields(C).y.type
|