Speaker
Lisa Roach
Material
Note
- Patch: temporarily replace your target with
MagicMock() - Target:
'package.module.ClassName' - When should you mock?
- When you don't want to actually call an object
- e.g., database, system call
- When you don't want to actually call an object
- What makes it so confusing?
- Identifying the target
- Multiple ways to call
Patch
- Target must be importable
- Patch where the object is used
# module.py
from db import db_write
# test_module.py
@patch("module.db_write")
- How to call Patch
- Context Manager
- Function / Class Decorators
- Manual start/stop
Spec
- The
specarguments:spec,autospec,spec_set - Mock Problems that
speccan solve- Misspelled asserts look like attributes
- Mocked objects called incorrectly pass silently
- A MagicMock
dir()assert_any_callassert_calledassert_called_onceassert_called_once_withassert_called_with- ...
return_valueside_effect
- A Specced MagicMock
spec=True- The attribute of patched object is now in MagicMock.
- We can now only get attribute that exists.
- It does not know the attribute of your attribute →
autospec=True- However,
autospeccan be dangerous. It will run the code that will be triggered when introspected.
- However,
- It doesn't know dynamically created attribute (including the ones in
__init__) → manually create it
spec_set=Trueprevent you from setting attribute that does not exist
Other arguments
new_callable- Common Use case: Mocking property object
newcreatekwargsreturn_value- set attribute
Readmore
patch.objectpatch.dictpatch.multiple