1+ import sys
12import unittest
23from datetime import datetime , timedelta
34from typing import Optional
@@ -33,7 +34,7 @@ def test_strict_struct_initialization(self):
3334
3435 class MyStrictStruct (csp .Struct , allow_unset = False ):
3536 req_int : int
36- opt_str : str | None = None
37+ opt_str : Optional [ str ] = None
3738 def_int : int = 123
3839 opt_str_2 : Optional [str ] = None
3940
@@ -49,6 +50,24 @@ class MyStrictStruct(csp.Struct, allow_unset=False):
4950 ):
5051 MyStrictStruct ()
5152
53+ # test 3.10+ | operator
54+ if sys .version_info >= (3 , 10 ):
55+
56+ class MyStrictStruct (csp .Struct , allow_unset = False ):
57+ req_int : int
58+ opt_str : str | None = None
59+
60+ s1 = MyStrictStruct (req_int = 42 , opt_str = "hola" )
61+ self .assertEqual (s1 .req_int , 42 )
62+ self .assertEqual (s1 .opt_str , "hola" )
63+ with self .assertRaisesRegex (
64+ ValueError , r"Struct MyStrictStruct is not valid; required fields \[req_int\] were not set on init"
65+ ):
66+ MyStrictStruct (opt_str = "bonjour" )
67+ s2 = MyStrictStruct (req_int = 43 )
68+ self .assertEqual (s2 .req_int , 43 )
69+ self .assertIsNone (s2 .opt_str )
70+
5271 def test_strict_struct_hasattr_delattr (self ):
5372 """test hasattr and delattr behavior for strict structs"""
5473
@@ -326,7 +345,7 @@ def test_strict_struct_wiring_access_2(self):
326345 class Test (csp .Struct , allow_unset = False ):
327346 name : str
328347 age : int
329- is_active : bool | None = None
348+ is_active : Optional [ bool ] = None
330349
331350 def greet (self ):
332351 return f"Hello, my name is { self .name } and I am { self .age } years old."
0 commit comments