2015-01-27 16:53:17 +00:00
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
|
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
|
2015-01-29 11:20:17 +00:00
|
|
|
import pytest
|
2015-01-27 16:53:17 +00:00
|
|
|
|
|
|
|
import attr
|
|
|
|
|
2015-01-29 15:24:49 +00:00
|
|
|
from attr._compat import TYPE
|
2015-01-27 16:53:17 +00:00
|
|
|
from attr._make import Attribute, NOTHING
|
|
|
|
|
|
|
|
|
|
|
|
@attr.s
|
|
|
|
class C1(object):
|
2015-01-29 11:20:17 +00:00
|
|
|
x = attr.ib(validator=attr.validators.instance_of(int))
|
2015-01-27 22:03:42 +00:00
|
|
|
y = attr.ib()
|
2015-01-27 16:53:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
foo = None
|
|
|
|
|
|
|
|
|
|
|
|
@attr.s()
|
|
|
|
class C2(object):
|
2015-01-27 22:03:42 +00:00
|
|
|
x = attr.ib(default_value=foo)
|
|
|
|
y = attr.ib(default_factory=list)
|
2015-01-27 16:53:17 +00:00
|
|
|
|
|
|
|
|
|
|
|
class TestDarkMagic(object):
|
|
|
|
"""
|
|
|
|
Integration tests.
|
|
|
|
"""
|
|
|
|
def test_ls(self):
|
|
|
|
"""
|
|
|
|
`attr.ls` works.
|
|
|
|
"""
|
|
|
|
assert [
|
2015-01-29 15:24:49 +00:00
|
|
|
Attribute(name="x", default_value=foo, default_factory=NOTHING,
|
2015-01-28 14:54:41 +00:00
|
|
|
validator=None),
|
|
|
|
Attribute(name="y", default_value=NOTHING, default_factory=list,
|
|
|
|
validator=None),
|
2015-01-27 16:53:17 +00:00
|
|
|
] == attr.ls(C2)
|
|
|
|
|
2015-01-29 20:50:07 +00:00
|
|
|
def test_asdict(self):
|
2015-01-27 16:53:17 +00:00
|
|
|
"""
|
2015-01-29 20:50:07 +00:00
|
|
|
`attr.asdict` works.
|
2015-01-27 16:53:17 +00:00
|
|
|
"""
|
|
|
|
assert {
|
|
|
|
"x": 1,
|
|
|
|
"y": 2,
|
2015-01-29 20:50:07 +00:00
|
|
|
} == attr.asdict(C1(x=1, y=2))
|
2015-01-29 11:20:17 +00:00
|
|
|
|
|
|
|
def test_validator(self):
|
|
|
|
"""
|
|
|
|
`instance_of` raises `TypeError` on type mismatch.
|
|
|
|
"""
|
|
|
|
with pytest.raises(TypeError) as e:
|
|
|
|
C1("1", 2)
|
|
|
|
assert (
|
|
|
|
"'x' must be <{type} 'int'> (got '1' that is a <{type} "
|
|
|
|
"'str'>).".format(type=TYPE),
|
|
|
|
C1.x, int, "1",
|
|
|
|
) == e.value.args
|
2015-01-29 12:05:04 +00:00
|
|
|
|
|
|
|
def test_renaming(self):
|
|
|
|
"""
|
|
|
|
Private members are renamed but only in `__init__`.
|
|
|
|
"""
|
|
|
|
@attr.s
|
|
|
|
class C3(object):
|
|
|
|
_x = attr.ib()
|
|
|
|
|
|
|
|
assert "C3(_x=1)" == repr(C3(x=1))
|