Featured image of post A Detailed Guide to pytest-mock

A Detailed Guide to pytest-mock

How to Use pytest-mock


Advanced Unit Testing and Mocking in Python with pytest-mock

1. The Significance of Unit Testing and Mocking

In software development, unit testing is used to verify the correctness of code logic. In real-world projects, however, code often depends on external services (such as databases, APIs, and file systems). Testing these dependencies directly leads to:

  1. Slower test execution
  2. Uncontrollable test results
  3. Side effects (such as actually sending emails)

Mocking replaces real dependencies with virtual objects, allowing tests to focus on the logic of the unit under test.


2. Environment Setup

Use the pytest and pytest-mock plugins:

1
pip install pytest pytest-mock

3. Basic Usage Example

Scenario: Email Sending Service

Suppose we have an email-sending class, EmailSender:

1
2
3
4
5
# email_sender.py
class EmailSender:
    def send(self, to, subject, body):
        # Logic for actually sending the email
        return True

When testing, we should not actually send emails. Use pytest-mock to mock the send method:

1
2
3
4
5
6
7
8
9
# test_email_sender.py
def test_send_email(mocker):
    mock_send = mocker.patch("email_sender.EmailSender.send")
    sender = EmailSender()
    
    result = sender.send("user@example.com", "Hello", "Test email")
    
    mock_send.assert_called_once_with("user@example.com", "Hello", "Test email")
    assert result is True

Code walkthrough:

  • mocker.patch replaces the EmailSender.send method
  • Verify that the method was called with the correct arguments
  • Assert that the return value is True

4. Advanced Mocking Techniques

1. Mocking Return Values

1
2
3
4
def test_mock_return_value(mocker):
    mocker.patch("module.Class.method", return_value="mocked_response")
    instance = Class()
    assert instance.method() == "mocked_response"

2. Mocking Exceptions

1
2
3
4
5
def test_mock_exception(mocker):
    mocker.patch("module.Class.method", side_effect=Exception("DB Error"))
    instance = Class()
    with pytest.raises(Exception, match="DB Error"):
        instance.method()

3. Mocking Consecutive Calls

1
2
3
4
5
6
7
def test_multiple_returns(mocker):
    mock_method = mocker.patch("module.Class.method")
    mock_method.side_effect = [10, 20, 30]
    
    assert Class().method() == 10
    assert Class().method() == 20
    assert Class().method() == 30

4. Mocking Attributes and Method Chains

1
2
3
4
5
6
def test_chained_methods(mocker):
    mock_instance = mocker.MagicMock()
    mock_instance.method1().method2().method3.return_value = "final"
    
    assert mock_instance.method1().method2().method3() == "final"
    mock_instance.method1.assert_called_once()

5. Mocking Complex Scenarios

Scenario: API Client Testing

1
2
3
4
5
6
7
# api_client.py
import requests

class APIClient:
    def get_user_data(self, user_id):
        response = requests.get(f"https://api.example.com/users/{user_id}")
        return response.json()

When testing, mock requests.get:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def test_api_client(mocker):
    mock_response = mocker.MagicMock()
    mock_response.json.return_value = {"id": 1, "name": "John"}
    
    mock_get = mocker.patch("requests.get", return_value=mock_response)
    
    client = APIClient()
    data = client.get_user_data(1)
    
    mock_get.assert_called_once_with("https://api.example.com/users/1")
    assert data == {"id": 1, "name": "John"}

6. Best Practices and Considerations

  1. Precise assertions: not only verify that a call was made, but also check its arguments

    1
    
    mock_method.assert_called_with(arg1, arg2=expected_value)
    
  2. Use autospec: keep the mock’s interface consistent with the original object

    1
    
    mocker.patch("module.Class", autospec=True)
    
  3. Avoid over-mocking: use real objects for core business logic whenever possible

  4. Clean up mocks: the mocker fixture handles automatic cleanup and prevents test pollution


7. Summary

With pytest-mock we can:

  • ✅ Isolate the test environment
  • ✅ Simulate a wide range of boundary conditions
  • ✅ Verify object interaction behavior
  • ✅ Speed up test execution

Mastering mocking techniques can significantly improve test coverage and code quality. It is recommended to consult the official documentation to explore more advanced use cases in depth.


Built with Hugo
Theme Stack designed by Jimmy