]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/testsuite/gdb.dap/type_check.py
Update copyright year range in header of all files managed by GDB
[thirdparty/binutils-gdb.git] / gdb / testsuite / gdb.dap / type_check.py
1 # Copyright 2023-2024 Free Software Foundation, Inc.
2
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15
16 # Test the type checker.
17
18 import typing
19 from gdb.dap.typecheck import type_check
20
21
22 # A wrapper to call a function that should cause a type-checking
23 # failure. Returns if the exception was seen. Throws an exception if
24 # a TypeError was not seen.
25 def should_fail(func, **args):
26 try:
27 func(**args)
28 except TypeError:
29 return
30 raise RuntimeError("function failed to throw TypeError")
31
32
33 # Also specify a return type to make sure return types do not confuse
34 # the checker.
35 @type_check
36 def simple_types(*, b: bool, s: str, i: int = 23) -> int:
37 return i
38
39
40 def check_simple():
41 simple_types(b=True, s="DEI", i=97)
42 # Check the absence of a defaulted argument.
43 simple_types(b=True, s="DEI")
44 simple_types(b=False, s="DEI", i=97)
45 should_fail(simple_types, b=97, s="DEI", i=97)
46 should_fail(simple_types, b=True, s=None, i=97)
47 should_fail(simple_types, b=True, s="DEI", i={})
48
49
50 @type_check
51 def sequence_type(*, s: typing.Sequence[str]):
52 pass
53
54
55 def check_sequence():
56 sequence_type(s=("hi", "out", "there"))
57 sequence_type(s=["hi", "out", "there"])
58 sequence_type(s=())
59 sequence_type(s=[])
60 should_fail(sequence_type, s=23)
61 should_fail(sequence_type, s=["hi", 97])
62
63
64 @type_check
65 def map_type(*, m: typing.Mapping[str, int]):
66 pass
67
68
69 def check_map():
70 map_type(m={})
71 map_type(m={"dei": 23})
72 should_fail(map_type, m=[1, 2, 3])
73 should_fail(map_type, m=None)
74 should_fail(map_type, m={"dei": "string"})
75
76
77 @type_check
78 def opt_type(*, u: typing.Optional[int]):
79 pass
80
81
82 def check_opt():
83 opt_type(u=23)
84 opt_type(u=None)
85 should_fail(opt_type, u="string")
86
87
88 def check_everything():
89 # Older versions of Python can't really implement this.
90 if hasattr(typing, "get_origin"):
91 # Just let any exception propagate and end up in the log.
92 check_simple()
93 check_sequence()
94 check_map()
95 check_opt()
96 print("OK")
97 else:
98 print("UNSUPPORTED")