notes on magic mock py
This commit is contained in:
parent
abb92d9f2b
commit
7fc0829cc9
1 changed files with 58 additions and 0 deletions
58
zk/Pytest_Magic_Mock.md
Normal file
58
zk/Pytest_Magic_Mock.md
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
---
|
||||
tags: [python]
|
||||
---
|
||||
|
||||
An instance of the general Python `Mock` that is pre-configured with "magic"
|
||||
methods that the standard `Mock` lacks.
|
||||
|
||||
These methods mean that it can automaticaly behave like the following objects
|
||||
without special configuration:
|
||||
|
||||
- a [context manager](./Using_a_context_manager_in_Python.md)
|
||||
- supports `__enter__`, `__exit__` and `with` statement
|
||||
|
||||
- a list or other container
|
||||
- supports `__iter__`, `__getitem`, `__len__`
|
||||
|
||||
- calls to a methods
|
||||
|
||||
## Example: mocking return from API call
|
||||
|
||||
Mock:
|
||||
|
||||
```py
|
||||
def get_user_data(api_client):
|
||||
response = api_client.get_user(id=123)
|
||||
return response
|
||||
|
||||
```
|
||||
|
||||
As follows:
|
||||
|
||||
```py
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
def test_get_user_data():
|
||||
mock_api = MagicMock()
|
||||
mock_api.get_user.return_value = {"name": "Alice", "role": "Admin"}
|
||||
result = get_user_data(mock_api)
|
||||
|
||||
assert result["name"] == "Alice"
|
||||
mock_api.get_user.assert_called_once_with(id=123)
|
||||
```
|
||||
|
||||
## Example: testing behaviour of code that relies on context managers:
|
||||
|
||||
```py
|
||||
def log_to_file(file_system):
|
||||
with file_system.open("log.txt") as f:
|
||||
f.write("Hello World")
|
||||
|
||||
def test_log_to_file():
|
||||
mock_fs = MagicMock()
|
||||
|
||||
log_to_file(mock_fs)
|
||||
|
||||
mock_fs.open.assert_called_with("log.txt")
|
||||
mock_fs.open().__enter__().write.assert_called_with("Hello World")
|
||||
```
|
||||
Loading…
Add table
Reference in a new issue