cpython/Lib/unittest
Miss Islington (bot) a6063f8756
[3.15] gh-153888: Resolve lazy imports before using them as a mock spec (GH-157768) (GH-158396)
Resolve lazy imports before using them as a mock spec

unittest.mock.patch() reads the attribute it replaces out of
target.__dict__, which for an unresolved lazy import holds a
types.LazyImportType placeholder. spec=True, spec_set=True and
autospec=True then specced the placeholder, so patching a function
produced a NonCallableMagicMock.

Reimplementation of python/cpython#153977:

- Resolve in _patch.__enter__(), and only when the spec is taken from
  the original, rather than unconditionally in get_original().
  Resolving on every patch() breaks patch("mod.dep", new=...) for a
  lazy import of a module that is not installed.
- Test spec and spec_set as well as autospec, as asked for in review.
- Build the lazy binding in the test instead of importing json lazily
  at module level: "lazy from" binds eagerly when the module is already
  imported, so that test passed without the fix too.
(cherry picked from commit cac016736e)

Co-authored-by: Brittany Reynoso <breynoso@meta.com>
2026-10-10 14:01:54 +03:00
..
__init__.py
__main__.py
_log.py
async_case.py
case.py gh-143231: Do not swallow not matched warnings in assertWarns*() (GH-149229) 2026-05-03 10:24:57 +00:00
loader.py [3.15] gh-120665: make unittest loaders avoid loading test cases that are abstract base classes (GH-120666) (#151601) 2026-06-17 11:47:27 -04:00
main.py gh-142389: Add backticks to stdlib argparse help to display in colour (#149384) 2026-05-04 22:23:18 +00:00
mock.py [3.15] gh-153888: Resolve lazy imports before using them as a mock spec (GH-157768) (GH-158396) 2026-10-10 14:01:54 +03:00
result.py
runner.py gh-144384: Lazily import _colorize (#149318) 2026-05-06 16:07:43 +00:00
signals.py
suite.py
util.py gh-145546: unittest.util: fix sorted_list_difference tail deduplication (GH-145547) 2026-03-11 13:21:22 +01:00