File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ from dataclasses import dataclass
2
+
3
+ import pytest
4
+ import sys
5
+ from typing import Optional
6
+
7
+ import betterproto
8
+
9
+
10
+ @pytest .mark .skipif (
11
+ sys .version_info < (3 , 10 ),
12
+ reason = "pattern matching is only supported in python3.10+" ,
13
+ )
14
+ def test_oneof_pattern_matching ():
15
+ @dataclass
16
+ class Sub (betterproto .Message ):
17
+ val : int = betterproto .int32_field (1 )
18
+
19
+ @dataclass
20
+ class Foo (betterproto .Message ):
21
+ bar : Optional [int ] = betterproto .int32_field (1 , group = "group1" )
22
+ baz : Optional [str ] = betterproto .string_field (2 , group = "group1" )
23
+ sub : Optional [Sub ] = betterproto .message_field (3 , group = "group2" )
24
+ abc : Optional [str ] = betterproto .string_field (4 , group = "group2" )
25
+
26
+ foo = Foo (baz = "test1" , abc = "test2" )
27
+
28
+ match foo :
29
+ case Foo (bar = int (_)):
30
+ pytest .fail ("Matched 'bar' instead of 'baz'" )
31
+ case Foo (baz = v ):
32
+ assert v == "test1"
33
+ case _:
34
+ pytest .fail ("Matched neither 'bar' nor 'baz'" )
35
+
36
+ match foo :
37
+ case Foo (sub = Sub (_)):
38
+ pytest .fail ("Matched 'sub' instead of 'abc'" )
39
+ case Foo (abc = v ):
40
+ assert v == "test2"
41
+ case _:
7288
42
+ pytest .fail ("Matched neither 'sub' nor 'abc'" )
43
+
44
+ foo .sub = Sub (val = 1 )
45
+
46
+ match foo :
47
+ case Foo (sub = Sub (val = v )):
48
+ assert v == 1
49
+ case Foo (abc = str (v )):
50
+ pytest .fail ("Matched 'abc' instead of 'sub'" )
51
+ case _:
52
+ pytest .fail ("Matched neither 'sub' nor 'abc'" )
You can’t perform that action at this time.
0 commit comments