diff options
author | Matthew Suozzo <msuozzo@google.com> | 2022-02-03 08:41:19 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-02-03 08:41:19 (GMT) |
commit | 6394e981adaca2c0daa36c8701611e250d74024c (patch) | |
tree | e045af3b3a17ab2bfa72e44aa711ad046c8ba4bb /Lib/unittest/mock.py | |
parent | 8726067ace98a27557e9fdf1a8e1c509c37cfcfc (diff) | |
download | cpython-6394e981adaca2c0daa36c8701611e250d74024c.zip cpython-6394e981adaca2c0daa36c8701611e250d74024c.tar.gz cpython-6394e981adaca2c0daa36c8701611e250d74024c.tar.bz2 |
Restrict use of Mock objects as specs (GH-31090)
Follow-on to https://github.com/python/cpython/pull/25326
This covers cases where mock objects are passed directly to spec.
Diffstat (limited to 'Lib/unittest/mock.py')
-rw-r--r-- | Lib/unittest/mock.py | 10 |
1 files changed, 9 insertions, 1 deletions
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 9137501..2719f74 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -489,6 +489,9 @@ class NonCallableMock(Base): def _mock_add_spec(self, spec, spec_set, _spec_as_instance=False, _eat_self=False): + if _is_instance_mock(spec): + raise InvalidSpecError(f'Cannot spec a Mock object. [object={spec!r}]') + _spec_class = None _spec_signature = None _spec_asyncs = [] @@ -2789,6 +2792,7 @@ FunctionTypes = ( file_spec = None +open_spec = None def _to_stream(read_data): @@ -2845,8 +2849,12 @@ def mock_open(mock=None, read_data=''): import _io file_spec = list(set(dir(_io.TextIOWrapper)).union(set(dir(_io.BytesIO)))) + global open_spec + if open_spec is None: + import _io + open_spec = list(set(dir(_io.open))) if mock is None: - mock = MagicMock(name='open', spec=open) + mock = MagicMock(name='open', spec=open_spec) handle = MagicMock(spec=file_spec) handle.__enter__.return_value = handle |