Commit cac0167
authored
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 #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.
1 parent 1407bb9 commit cac0167
3 files changed
Lines changed: 42 additions & 1 deletion
File tree
- Lib
- test/test_unittest/testmock
- unittest
- Misc/NEWS.d/next/Library
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
5 | 5 | | |
6 | 6 | | |
7 | 7 | | |
| 8 | + | |
8 | 9 | | |
9 | 10 | | |
10 | 11 | | |
| |||
2101 | 2102 | | |
2102 | 2103 | | |
2103 | 2104 | | |
| 2105 | + | |
| 2106 | + | |
| 2107 | + | |
| 2108 | + | |
| 2109 | + | |
| 2110 | + | |
| 2111 | + | |
| 2112 | + | |
| 2113 | + | |
| 2114 | + | |
| 2115 | + | |
| 2116 | + | |
| 2117 | + | |
| 2118 | + | |
| 2119 | + | |
| 2120 | + | |
| 2121 | + | |
| 2122 | + | |
| 2123 | + | |
| 2124 | + | |
| 2125 | + | |
| 2126 | + | |
| 2127 | + | |
| 2128 | + | |
| 2129 | + | |
| 2130 | + | |
| 2131 | + | |
| 2132 | + | |
| 2133 | + | |
| 2134 | + | |
| 2135 | + | |
| 2136 | + | |
| 2137 | + | |
| 2138 | + | |
2104 | 2139 | | |
2105 | 2140 | | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
35 | 35 | | |
36 | 36 | | |
37 | 37 | | |
38 | | - | |
| 38 | + | |
39 | 39 | | |
40 | 40 | | |
41 | 41 | | |
| |||
1507 | 1507 | | |
1508 | 1508 | | |
1509 | 1509 | | |
| 1510 | + | |
| 1511 | + | |
| 1512 | + | |
| 1513 | + | |
1510 | 1514 | | |
1511 | 1515 | | |
1512 | 1516 | | |
| |||
Lines changed: 2 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
0 commit comments