← Back to index

exceptions_context_managers.py

True Positive
False Positive
False Negative
Optional (detected)
Warning or Info
TP: 0
FP: 2
FN: 0
Optional: 0 / 0
1"""
2Tests the handling of __exit__ return types for context managers.
3"""
4
5# Specification: https://typing.readthedocs.io/en/latest/spec/exceptions.html
6
7
8from typing import Any, Literal, assert_type
9
11class CMBase:
12 def __enter__(self) -> None:
13 pass
16class Suppress1(CMBase):
17 def __exit__(self, exc_type, exc_value, traceback) -> bool:
18 return True
21class Suppress2(CMBase):
22 def __exit__(self, exc_type, exc_value, traceback) -> Literal[True]:
23 return True
26class NoSuppress1(CMBase):
27 def __exit__(self, exc_type, exc_value, traceback) -> None:
28 return None
31class NoSuppress2(CMBase):
32 def __exit__(self, exc_type, exc_value, traceback) -> Literal[False]:
33 return False
36class NoSuppress3(CMBase):
37 def __exit__(self, exc_type, exc_value, traceback) -> Any:
38 return False
41class NoSuppress4(CMBase):
42 def __exit__(self, exc_type, exc_value, traceback) -> None | bool:
43 return None
46def suppress1(x: int | str) -> None:
47 if isinstance(x, int):
48 with Suppress1():
49 raise ValueError
50 assert_type(x, int | str)
Unexpected error [type-assertion-failure] Type `int | str` does not match asserted type `str`
53def suppress2(x: int | str) -> None:
54 if isinstance(x, int):
55 with Suppress2():
56 raise ValueError
57 assert_type(x, int | str)
Unexpected error [type-assertion-failure] Type `int | str` does not match asserted type `str`
60def no_suppress1(x: int | str) -> None:
61 if isinstance(x, int):
62 with NoSuppress1():
63 raise ValueError
64 assert_type(x, str)
67def no_suppress2(x: int | str) -> None:
68 if isinstance(x, int):
69 with NoSuppress2():
70 raise ValueError
71 assert_type(x, str)
74def no_suppress3(x: int | str) -> None:
75 if isinstance(x, int):
76 with NoSuppress3():
77 raise ValueError
78 assert_type(x, str)
81def no_suppress4(x: int | str) -> None:
82 if isinstance(x, int):
83 with NoSuppress4():
84 raise ValueError
85 assert_type(x, str)