Skip to content

Commit 45e1bf7

Browse files
authored
Typeshed cherry-pick: Fix @patch when new is missing (#10459) (#15673)
For release-1.5
1 parent 7a94183 commit 45e1bf7

File tree

1 file changed

+21
-6
lines changed

1 file changed

+21
-6
lines changed

mypy/typeshed/stdlib/unittest/mock.pyi

+21-6
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,8 @@ class _patch(Generic[_T]):
234234
def copy(self) -> _patch[_T]: ...
235235
@overload
236236
def __call__(self, func: _TT) -> _TT: ...
237+
# If new==DEFAULT, this should add a MagicMock parameter to the function
238+
# arguments. See the _patch_default_new class below for this functionality.
237239
@overload
238240
def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ...
239241
if sys.version_info >= (3, 8):
@@ -257,6 +259,22 @@ class _patch(Generic[_T]):
257259
def start(self) -> _T: ...
258260
def stop(self) -> None: ...
259261

262+
if sys.version_info >= (3, 8):
263+
_Mock: TypeAlias = MagicMock | AsyncMock
264+
else:
265+
_Mock: TypeAlias = MagicMock
266+
267+
# This class does not exist at runtime, it's a hack to make this work:
268+
# @patch("foo")
269+
# def bar(..., mock: MagicMock) -> None: ...
270+
class _patch_default_new(_patch[_Mock]):
271+
@overload
272+
def __call__(self, func: _TT) -> _TT: ...
273+
# Can't use the following as ParamSpec is only allowed as last parameter:
274+
# def __call__(self, func: Callable[_P, _R]) -> Callable[Concatenate[_P, MagicMock], _R]: ...
275+
@overload
276+
def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ...
277+
260278
class _patch_dict:
261279
in_dict: Any
262280
values: Any
@@ -273,11 +291,8 @@ class _patch_dict:
273291
start: Any
274292
stop: Any
275293

276-
if sys.version_info >= (3, 8):
277-
_Mock: TypeAlias = MagicMock | AsyncMock
278-
else:
279-
_Mock: TypeAlias = MagicMock
280-
294+
# This class does not exist at runtime, it's a hack to add methods to the
295+
# patch() function.
281296
class _patcher:
282297
TEST_PREFIX: str
283298
dict: type[_patch_dict]
@@ -307,7 +322,7 @@ class _patcher:
307322
autospec: Any | None = ...,
308323
new_callable: Any | None = ...,
309324
**kwargs: Any,
310-
) -> _patch[_Mock]: ...
325+
) -> _patch_default_new: ...
311326
@overload
312327
@staticmethod
313328
def object( # type: ignore[misc]

0 commit comments

Comments
 (0)