55from datetime import datetime , timedelta
66from decimal import Decimal
77from fractions import Fraction
8- from typing import TypedDict
8+ from typing import TypedDict , Union
99from typing_extensions import assert_type
10- from unittest .mock import MagicMock , Mock , patch
10+ from unittest .mock import AsyncMock , MagicMock , Mock , patch
1111
1212case = unittest .TestCase ()
1313
@@ -154,10 +154,17 @@ def f_explicit_new(i: int) -> str:
154154 return "asdf"
155155
156156
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+
157162assert_type (f_default_new (1 ), str )
158163f_default_new ("a" ) # Not an error due to ParamSpec limitations
159164assert_type (f_explicit_new (1 ), str )
160165f_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
161168
162169
163170@patch ("sys.exit" , new = Mock ())
@@ -171,3 +178,51 @@ def method() -> int:
171178
172179assert_type (TestXYZ .attr , int )
173180assert_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