From 7fc0829cc98f4aeaef40743e809a4456e7beecaf Mon Sep 17 00:00:00 2001 From: thomasabishop Date: Mon, 12 Jan 2026 07:57:44 +0000 Subject: [PATCH] notes on magic mock py --- zk/Pytest_Magic_Mock.md | 58 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 zk/Pytest_Magic_Mock.md diff --git a/zk/Pytest_Magic_Mock.md b/zk/Pytest_Magic_Mock.md new file mode 100644 index 0000000..a4dc0af --- /dev/null +++ b/zk/Pytest_Magic_Mock.md @@ -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") +```