attrs/tests/test_filters.py

128 lines
2.8 KiB
Python
Raw Normal View History

2021-12-27 08:29:09 +00:00
# SPDX-License-Identifier: MIT
2015-02-20 15:34:21 +00:00
"""
Tests for `attr.filters`.
"""
import pytest
import attr
from attr import fields
from attr.filters import _split_what, exclude, include
2015-02-20 15:34:21 +00:00
@attr.s
class C:
a = attr.ib()
b = attr.ib()
2015-02-20 15:34:21 +00:00
class TestSplitWhat:
2015-02-20 15:34:21 +00:00
"""
Tests for `_split_what`.
"""
2018-06-10 17:40:07 +00:00
2015-02-20 15:34:21 +00:00
def test_splits(self):
"""
Splits correctly.
"""
assert (
frozenset((int, str)),
frozenset(("abcd", "123")),
frozenset((fields(C).a,)),
) == _split_what((str, "123", fields(C).a, int, "abcd"))
2015-02-20 15:34:21 +00:00
class TestInclude:
2015-02-20 15:34:21 +00:00
"""
Tests for `include`.
"""
2018-06-10 17:40:07 +00:00
@pytest.mark.parametrize(
"incl,value",
[
((int,), 42),
((str,), "hello"),
((str, fields(C).a), 42),
((str, fields(C).b), "hello"),
(("a",), 42),
(("a",), "hello"),
(("a", str), 42),
(("a", fields(C).b), "hello"),
2018-06-10 17:40:07 +00:00
],
)
2015-02-20 15:34:21 +00:00
def test_allow(self, incl, value):
"""
Return True if a class or attribute is included.
2015-02-20 15:34:21 +00:00
"""
i = include(*incl)
assert i(fields(C).a, value) is True
2015-02-20 15:34:21 +00:00
2018-06-10 17:40:07 +00:00
@pytest.mark.parametrize(
"incl,value",
[
((str,), 42),
((int,), "hello"),
((str, fields(C).b), 42),
((int, fields(C).b), "hello"),
(("b",), 42),
(("b",), "hello"),
(("b", str), 42),
(("b", fields(C).b), "hello"),
2018-06-10 17:40:07 +00:00
],
)
2015-02-20 15:34:21 +00:00
def test_drop_class(self, incl, value):
"""
Return False on non-included classes and attributes.
2015-02-20 15:34:21 +00:00
"""
i = include(*incl)
assert i(fields(C).a, value) is False
2015-02-20 15:34:21 +00:00
class TestExclude:
2015-02-20 15:34:21 +00:00
"""
Tests for `exclude`.
"""
2018-06-10 17:40:07 +00:00
@pytest.mark.parametrize(
"excl,value",
[
((str,), 42),
((int,), "hello"),
((str, fields(C).b), 42),
((int, fields(C).b), "hello"),
(("b",), 42),
(("b",), "hello"),
(("b", str), 42),
(("b", fields(C).b), "hello"),
2018-06-10 17:40:07 +00:00
],
)
2015-02-20 15:34:21 +00:00
def test_allow(self, excl, value):
"""
Return True if class or attribute is not excluded.
2015-02-20 15:34:21 +00:00
"""
e = exclude(*excl)
assert e(fields(C).a, value) is True
2015-02-20 15:34:21 +00:00
2018-06-10 17:40:07 +00:00
@pytest.mark.parametrize(
"excl,value",
[
((int,), 42),
((str,), "hello"),
((str, fields(C).a), 42),
((str, fields(C).b), "hello"),
(("a",), 42),
(("a",), "hello"),
(("a", str), 42),
(("a", fields(C).b), "hello"),
2018-06-10 17:40:07 +00:00
],
)
2015-02-20 15:34:21 +00:00
def test_drop_class(self, excl, value):
"""
Return True on non-excluded classes and attributes.
2015-02-20 15:34:21 +00:00
"""
e = exclude(*excl)
assert e(fields(C).a, value) is False