mirror of https://github.com/python/cpython.git
Add example to the documentation for calling unittest.mock.patch with create=True (GH-11056)
This commit is contained in:
parent
ee65594367
commit
d6acf17c05
|
@ -1119,13 +1119,13 @@ patch
|
||||||
Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
|
Instead of ``autospec=True`` you can pass ``autospec=some_object`` to use an
|
||||||
arbitrary object as the spec instead of the one being replaced.
|
arbitrary object as the spec instead of the one being replaced.
|
||||||
|
|
||||||
By default :func:`patch` will fail to replace attributes that don't exist. If
|
By default :func:`patch` will fail to replace attributes that don't exist.
|
||||||
you pass in ``create=True``, and the attribute doesn't exist, patch will
|
If you pass in ``create=True``, and the attribute doesn't exist, patch will
|
||||||
create the attribute for you when the patched function is called, and
|
create the attribute for you when the patched function is called, and delete
|
||||||
delete it again afterwards. This is useful for writing tests against
|
it again after the patched function has exited. This is useful for writing
|
||||||
attributes that your production code creates at runtime. It is off by
|
tests against attributes that your production code creates at runtime. It is
|
||||||
default because it can be dangerous. With it switched on you can write
|
off by default because it can be dangerous. With it switched on you can
|
||||||
passing tests against APIs that don't actually exist!
|
write passing tests against APIs that don't actually exist!
|
||||||
|
|
||||||
.. note::
|
.. note::
|
||||||
|
|
||||||
|
@ -1247,6 +1247,27 @@ into a :func:`patch` call using ``**``::
|
||||||
...
|
...
|
||||||
KeyError
|
KeyError
|
||||||
|
|
||||||
|
By default, attempting to patch a function in a module (or a method or an
|
||||||
|
attribute in a class) that does not exist will fail with :exc:`AttributeError`::
|
||||||
|
|
||||||
|
>>> @patch('sys.non_existing_attribute', 42)
|
||||||
|
... def test():
|
||||||
|
... assert sys.non_existing_attribute == 42
|
||||||
|
...
|
||||||
|
>>> test()
|
||||||
|
Traceback (most recent call last):
|
||||||
|
...
|
||||||
|
AttributeError: <module 'sys' (built-in)> does not have the attribute 'non_existing'
|
||||||
|
|
||||||
|
but adding ``create=True`` in the call to :func:`patch` will make the previous example
|
||||||
|
work as expected::
|
||||||
|
|
||||||
|
>>> @patch('sys.non_existing_attribute', 42, create=True)
|
||||||
|
... def test(mock_stdout):
|
||||||
|
... assert sys.non_existing_attribute == 42
|
||||||
|
...
|
||||||
|
>>> test()
|
||||||
|
|
||||||
|
|
||||||
patch.object
|
patch.object
|
||||||
~~~~~~~~~~~~
|
~~~~~~~~~~~~
|
||||||
|
|
Loading…
Reference in New Issue