eolas/zk/Pytest_Magic_Mock.md

1.3 KiB

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

    • 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:

def get_user_data(api_client):
    response = api_client.get_user(id=123)
    return response

As follows:

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:

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")