77from fractions import Fraction
88from typing import TypedDict
99from typing_extensions import assert_type
10- from unittest .mock import MagicMock , Mock , patch
10+ from unittest .mock import MagicMock , Mock , patch , AsyncMock
1111
1212case = unittest .TestCase ()
1313
@@ -153,12 +153,16 @@ def f_default_new(i: int, mock: MagicMock) -> str:
153153def f_explicit_new (i : int ) -> str :
154154 return "asdf"
155155
156+ @patch ("sys.exit" , new_callable = lambda : 42 )
157+ def f_explicit_new_callable (i : int , new_callable_ret : int ) -> str :
158+ return "asdf"
156159
157160assert_type (f_default_new (1 ), str )
158161f_default_new ("a" ) # Not an error due to ParamSpec limitations
159162assert_type (f_explicit_new (1 ), str )
160163f_explicit_new ("a" ) # type: ignore[arg-type]
161-
164+ assert_type (f_explicit_new_callable (1 ), str )
165+ f_explicit_new_callable ("a" ) # Same as default new
162166
163167@patch ("sys.exit" , new = Mock ())
164168class TestXYZ (unittest .TestCase ):
@@ -171,3 +175,49 @@ def method() -> int:
171175
172176assert_type (TestXYZ .attr , int )
173177assert_type (TestXYZ .method (), int )
178+
179+
180+ with patch ("sys.exit" ) as default_new_enter :
181+ assert_type (default_new_enter , MagicMock | AsyncMock )
182+
183+ with patch ("sys.exit" , new = 42 ) as explicit_new_enter :
184+ assert_type (explicit_new_enter , int )
185+
186+ with patch ("sys.exit" , new_callable = lambda : 42 ) as explicit_new_callable_enter :
187+ assert_type (explicit_new_callable_enter , int )
188+
189+
190+ ###
191+ # Tests for mock.patch.object
192+ ###
193+
194+ @patch .object (Decimal , "exp" )
195+ def obj_f_default_new (i : int , mock : MagicMock ) -> str :
196+ return "asdf"
197+
198+
199+ @patch .object (Decimal , "exp" , new = 42 )
200+ def obj_f_explicit_new (i : int ) -> str :
201+ return "asdf"
202+
203+ @patch .object (Decimal , "exp" , new_callable = lambda : 42 )
204+ def obj_f_explicit_new_callable (i : int , new_callable_ret : int ) -> str :
205+ return "asdf"
206+
207+ assert_type (obj_f_default_new (1 ), str )
208+ obj_f_default_new ("a" ) # Not an error due to ParamSpec limitations
209+ assert_type (obj_f_explicit_new (1 ), str )
210+ obj_f_explicit_new ("a" ) # type: ignore[arg-type]
211+ assert_type (obj_f_explicit_new_callable (1 ), str )
212+ obj_f_explicit_new_callable ("a" ) # Same as default new
213+
214+
215+
216+ with patch .object (Decimal , "exp" ) as obj_default_new_enter :
217+ assert_type (obj_default_new_enter , MagicMock | AsyncMock )
218+
219+ with patch .object (Decimal , "exp" , new = 42 ) as obj_explicit_new_enter :
220+ assert_type (obj_explicit_new_enter , int )
221+
222+ with patch .object (Decimal , "exp" , new_callable = lambda : 42 ) as obj_explicit_new_callable_enter :
223+ assert_type (obj_explicit_new_callable_enter , int )
0 commit comments