File: apptest_patma.py

package info (click to toggle)
pypy3 7.3.19%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 212,236 kB
  • sloc: python: 2,098,316; ansic: 540,565; sh: 21,462; asm: 14,419; cpp: 4,451; makefile: 4,209; objc: 761; xml: 530; exp: 499; javascript: 314; pascal: 244; lisp: 45; csh: 12; awk: 4
file content (357 lines) | stat: -rw-r--r-- 8,609 bytes parent folder | download | duplicates (2)
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
import pytest

def test_match_sequence_string_bug():
    x = "x"
    match x:
        case ['x']:
            y = 2
        case 'x':
            y = 5
    assert y == 5

def test_sequence_missing_not_used():
    class defaultdict(dict):
        def __missing__(self, key):
            return 0
    x = defaultdict()
    x[1] = 1
    match x:
        case {0: 0}:
            y = 0
        case {**z}:
            y = 1
    assert x == {1: 1} # no keys added
    assert y == 1 # second case applies
    assert z == {1: 1} # the extracted inner dict is like the outer one

def test_error_name_bindings_duplicate():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case [a, a]:
        pass
""")

def test_error_name_bindings_duplicate_or():
    with pytest.raises(SyntaxError) as info:
        exec("""
def f(x):
    match x:
            case [1 as a,
                ((2 as a) | (3 as a))]: return 17
""")
    assert info.value.msg == "multiple assignments to name 'a' in pattern, previous one was on line 4"
    assert info.value.lineno == 5


def test_error_name_bindings_or():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case "a" | a:
        pass
""")

def test_error_allow_always_passing_or():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case a | "a":
        pass
""")
    assert info.value.msg == "name capture 'a' makes remaining patterns unreachable"

def test_error_forbidden_name():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case 1 as True:
        pass
""")

def test_match_list():
    def match_list(x):
        match x:
            case [True]: return "[True]"
            case [1,2,3]: return "list[1,2,3]"
            case [1]: return "list[1]"
            case []: return "emptylist"
            case [_]: return "list"
    assert match_list(['']) == "list"
    assert match_list([1]) == "list[1]"
    assert match_list([1,2,3]) == "list[1,2,3]"
    assert match_list([1,2,4]) is None
    assert match_list([2,3,4]) is None
    assert match_list([1, 2]) is None
    assert match_list([]) == "emptylist"

def test_match_with_if_bug():
    def match_truthy(x):
        match x:
            case a if a: return a
    assert match_truthy(1) == 1
    assert match_truthy(True) is True
    assert match_truthy([]) is None
    assert match_truthy('') is None


def test_or():
    x = 2
    match x:
        case 1 | 2:
            a = 2
        case _:
            a = 3
    assert a == 2

def test_dont_use_is():
    match [1.0]:
        case [1]: pass
        case _: assert False

def test_only_bind_at_end():
    a = 5
    match [1, 2, 3]:
        case [a, 1, b]:
            pass
    assert a == 5

def test_or_reorder():
    def or_orders(x):
        match x:
            case [a, b, 1] | [b, a, 2]:
                return a, b
        return 12
    assert or_orders([1, 2, 1]) == (1, 2)
    assert or_orders([1, 2, 2]) == (2, 1)
    assert or_orders([1, 3, 4]) == 12

def test_bug_repeated_names_not_reset_between_cases():
    def as_bug(x):
        match x:
            case 1 as y: return y
            case 2 as y: return y
    assert as_bug(1) == 1
    assert as_bug(2) == 2
    assert as_bug(3) is None

def test_bug_match_sequence_star():
    def sequence_star_bug(x):
        match x:
            case [1, a, *rest, x, 3]:
                return a, rest, x
    assert sequence_star_bug([1, 2, 3, 4, 5, 6, 3]) == (2, [3, 4, 5], 6)
    # rest must not end up in globals!
    assert "rest" not in globals()

def test_bug_match_class_builtin():
    def match_class_bool(x):
        match x:
            case bool(b) if b: return "True"
            case bool(): return "False"
    assert match_class_bool(True) == "True"
    assert match_class_bool(False) == "False"

def test_error_repeated_class_keyword():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case A(a=_, a=_):
        pass
""")

def test_error_duplicate_key():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case {"a": 1, "a": 2}:
        pass
""")
    assert info.value.msg == "mapping pattern checks duplicate key ('a')"
    assert info.value.lineno == 3

def test_error_key_wrong_kind():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case {f"{a}": 1}:
        pass
""")
    assert info.value.msg == "mapping pattern keys may only match literals and attribute lookups"
    assert info.value.lineno == 3

def test_error_key_wrong_kind():
    with pytest.raises(SyntaxError) as info:
        exec("""
match x:
    case [a, *b, c, *d]:
        pass
""")
    assert info.value.msg == "multiple starred names in sequence pattern"
    assert info.value.lineno == 3

def test_match_args_tuple():
    class C:
        __match_args__ = ["a", "b"]
        a = 0
        b = 1
    x = C()
    w = y = z = None
    with pytest.raises(TypeError):
        match x:
            case C(y, z):
                w = 12
    assert w is y is z is None

def test_match_keys_duplicate_runtime():
    class K:
        k = "a"
    w = y = z = None
    with pytest.raises(ValueError):
        match {"a": 1, "b": 2}:
            case {K.k: y, "a": z}: w = 12
    assert w is y is z is None

def test_optimize_unpack_sequence_star_no_capture():
    class Sequence:
        def __getitem__(self, index):
            return index
        def __len__(self):
            return 42
        def __iter__(self):
            return self
        def __next__(self):
            return 1
    a = 0
    b = 0
    match Sequence():
        case [0, *_, b, 41]:
            a = 1
    assert a == 1
    assert b == 40

def test_unpack_sequence_bug():
    def f(w):
        match w:
            case (p, q) as x:
                locals()
                return p, q, x
    assert f((1, 2)) == (1, 2, (1, 2))
    assert "p" not in globals()
    assert "q" not in globals()

def test_or_reordering_bug():
    def annoying_or(x):
        match x:
            case ((a, b, c, d, e, 7) |
                 (a, b, d, e, c, 8)):
                        pass
        out = locals()
        del out["x"]
        return out

    res = annoying_or(range(3, 9))
    exp = dict(a=3, b=4, d=5, e=6, c=7)
    assert res == exp

def test_bytearray_does_not_match_sequence():
    def sequence_match(x):
        match x:
            case [120]:
                return 1
            case 120:
                return 2
        return 3
    assert sequence_match(bytearray(b"x")) == 3


def test_error_fstring():
    with pytest.raises(SyntaxError) as info:
        exec("""
def fstringbug():
    match x:
        case f"{x}":
            pass
""")
    assert info.value.msg == "patterns may only match literals and attribute lookups"


def test_collections_abcs():
    import collections.abc
    class Seq(collections.abc.Sequence):
        __getitem__ = None

        def __init__(self, l):
            self.l = l

        def __len__(self):
            return self.l
    match Seq(0):
        case []:
            y = 0
    assert y == 0

    match Seq(34):
        case [*_]:
            y = 10
    assert y == 10

def test_sequence_doesnt_need_length():
    class A:
        def __getitem__(self, x):
            return 1
    match A():
        case [*_]:
            y = 10
    assert y == 10

def test_collections_abc_mapping():
    import collections.abc
    class A:
        pass
    collections.abc.Mapping.register(A)
    match A():
        case [*_]: assert 0, "unreachable"
        case {}: x = 11121
    assert x == 11121

    class B(A): # made after registering
        pass

    match B():
        case [*_]: assert 0, "unreachable"
        case {}: x = 111213434
    assert x == 111213434

def test_abstract_isinstance_check():
    class ABC(type):

        def __instancecheck__(cls, inst):
            """Implement isinstance(inst, cls)."""
            return any(cls.__subclasscheck__(c)
                       for c in set([type(inst), inst.__class__]))

        def __subclasscheck__(cls, sub):
            """Implement issubclass(sub, cls)."""
            candidates = cls.__dict__.get("__subclass__", set()) | set([cls])
            return any(c in candidates for c in sub.mro())

    class Integer(metaclass=ABC):
        __subclass__ = set([int])

    assert isinstance(12, Integer)

    match 12:
        case Integer(): pass
        case _: assert 0 # unreachable


def test_dict_pattern_none_value_bug():
    d = {"a": None}
    res = 0
    match d:
        case {"a": None}:
            res = 1
        case _:
            res = 2
    assert res == 1