-
-
Notifications
You must be signed in to change notification settings - Fork 448
Expand file tree
/
Copy pathtest_pattern_matching.py
More file actions
100 lines (76 loc) · 2.19 KB
/
Copy pathtest_pattern_matching.py
File metadata and controls
100 lines (76 loc) · 2.19 KB
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
# SPDX-License-Identifier: MIT
import pytest
import attr
class TestPatternMatching:
"""
Pattern matching syntax test cases.
"""
@pytest.mark.parametrize("dec", [attr.s, attr.define, attr.frozen])
def test_simple_match_case(self, dec):
"""
Simple match case statement works as expected with all class
decorators.
"""
@dec
class C:
a = attr.ib()
assert ("a",) == C.__match_args__
matched = False
c = C(a=1)
match c:
case C(a):
matched = True
assert matched
assert 1 == a
def test_explicit_match_args(self):
"""
Does not overwrite a manually set empty __match_args__.
"""
ma = ()
@attr.define
class C:
a = attr.field()
__match_args__ = ma
c = C(a=1)
msg = r"C\(\) accepts 0 positional sub-patterns \(1 given\)"
with pytest.raises(TypeError, match=msg):
match c:
case C(_):
pass
def test_match_args_kw_only(self):
"""
kw_only classes don't generate __match_args__.
kw_only fields are not included in __match_args__.
"""
@attr.define
class C:
a = attr.field(kw_only=True)
b = attr.field()
assert ("b",) == C.__match_args__
c = C(a=1, b=1)
msg = r"C\(\) accepts 1 positional sub-pattern \(2 given\)"
with pytest.raises(TypeError, match=msg):
match c:
case C(a, b):
pass
found = False
match c:
case C(b, a=a):
found = True
assert found
@attr.define(kw_only=True)
class C:
a = attr.field()
b = attr.field()
c = C(a=1, b=1)
msg = r"C\(\) accepts 0 positional sub-patterns \(2 given\)"
with pytest.raises(TypeError, match=msg):
match c:
case C(a, b):
pass
found = False
match c:
case C(a=a, b=b):
found = True
assert found
assert (1, 1) == (a, b)