5
5
from datetime import datetime , timedelta
6
6
from decimal import Decimal
7
7
from fractions import Fraction
8
- from typing import TypedDict
8
+ from typing import TypedDict , Union
9
9
from typing_extensions import assert_type
10
- from unittest .mock import MagicMock , Mock , patch
10
+ from unittest .mock import AsyncMock , MagicMock , Mock , patch
11
11
12
12
case = unittest .TestCase ()
13
13
@@ -154,10 +154,17 @@ def f_explicit_new(i: int) -> str:
154
154
return "asdf"
155
155
156
156
157
+ @patch ("sys.exit" , new_callable = lambda : 42 )
158
+ def f_explicit_new_callable (i : int , new_callable_ret : int ) -> str :
159
+ return "asdf"
160
+
161
+
157
162
assert_type (f_default_new (1 ), str )
158
163
f_default_new ("a" ) # Not an error due to ParamSpec limitations
159
164
assert_type (f_explicit_new (1 ), str )
160
165
f_explicit_new ("a" ) # type: ignore[arg-type]
166
+ assert_type (f_explicit_new_callable (1 ), str )
167
+ f_explicit_new_callable ("a" ) # Same as default new
161
168
162
169
163
170
@patch ("sys.exit" , new = Mock ())
@@ -171,3 +178,51 @@ def method() -> int:
171
178
172
179
assert_type (TestXYZ .attr , int )
173
180
assert_type (TestXYZ .method (), int )
181
+
182
+
183
+ with patch ("sys.exit" ) as default_new_enter :
184
+ assert_type (default_new_enter , Union [MagicMock , AsyncMock ])
185
+
186
+ with patch ("sys.exit" , new = 42 ) as explicit_new_enter :
187
+ assert_type (explicit_new_enter , int )
188
+
189
+ with patch ("sys.exit" , new_callable = lambda : 42 ) as explicit_new_callable_enter :
190
+ assert_type (explicit_new_callable_enter , int )
191
+
192
+
193
+ ###
194
+ # Tests for mock.patch.object
195
+ ###
196
+
197
+
198
+ @patch .object (Decimal , "exp" )
199
+ def obj_f_default_new (i : int , mock : MagicMock ) -> str :
200
+ return "asdf"
201
+
202
+
203
+ @patch .object (Decimal , "exp" , new = 42 )
204
+ def obj_f_explicit_new (i : int ) -> str :
205
+ return "asdf"
206
+
207
+
208
+ @patch .object (Decimal , "exp" , new_callable = lambda : 42 )
209
+ def obj_f_explicit_new_callable (i : int , new_callable_ret : int ) -> str :
210
+ return "asdf"
211
+
212
+
213
+ assert_type (obj_f_default_new (1 ), str )
214
+ obj_f_default_new ("a" ) # Not an error due to ParamSpec limitations
215
+ assert_type (obj_f_explicit_new (1 ), str )
216
+ obj_f_explicit_new ("a" ) # type: ignore[arg-type]
217
+ assert_type (obj_f_explicit_new_callable (1 ), str )
218
+ obj_f_explicit_new_callable ("a" ) # Same as default new
219
+
220
+
221
+ with patch .object (Decimal , "exp" ) as obj_default_new_enter :
222
+ assert_type (obj_default_new_enter , Union [MagicMock , AsyncMock ])
223
+
224
+ with patch .object (Decimal , "exp" , new = 42 ) as obj_explicit_new_enter :
225
+ assert_type (obj_explicit_new_enter , int )
226
+
227
+ with patch .object (Decimal , "exp" , new_callable = lambda : 42 ) as obj_explicit_new_callable_enter :
228
+ assert_type (obj_explicit_new_callable_enter , int )
0 commit comments