0
0
PytestHow-ToBeginner ยท 4 min read

How to Mock API Call in pytest: Simple Guide with Examples

To mock an API call in pytest, use the unittest.mock library to replace the network call with a mock object that returns a controlled response. This lets you test your code without making real HTTP requests by patching the function or method that performs the API call.
๐Ÿ“

Syntax

Use unittest.mock.patch as a decorator or context manager to replace the API call function with a mock. Inside the test, configure the mock to return the desired response.

  • @patch('module.function'): Replaces function in module with a mock.
  • mock_function.return_value: Sets what the mock returns when called.
  • mock_function.side_effect: Defines behavior like raising exceptions.
python
from unittest.mock import patch
import requests

@patch('requests.get')
def test_api_call(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {'key': 'value'}
    response = requests.get('http://fakeapi.com/data')
    assert response.status_code == 200
    assert response.json() == {'key': 'value'}
๐Ÿ’ป

Example

This example shows how to mock an API call using requests.get in a function. The test replaces the real HTTP call with a mock that returns a fake JSON response and status code.

python
import requests
from unittest.mock import patch

def fetch_data():
    response = requests.get('https://api.example.com/data')
    if response.status_code == 200:
        return response.json()
    return None

@patch('requests.get')
def test_fetch_data(mock_get):
    mock_get.return_value.status_code = 200
    mock_get.return_value.json.return_value = {'name': 'Test', 'value': 123}

    result = fetch_data()

    assert result == {'name': 'Test', 'value': 123}
    mock_get.assert_called_once_with('https://api.example.com/data')
Output
PASSED
โš ๏ธ

Common Pitfalls

  • Not patching the correct import path of the API call function causes the mock to be ignored.
  • Forgetting to set mock.return_value.json.return_value leads to errors when calling response.json().
  • Using real API calls in tests makes tests slow and flaky.

Always patch where the function is used, not where it is defined.

python
from unittest.mock import patch

# Wrong patch path - will not mock correctly
@patch('requests.get')  # If fetch_data imports requests differently, this fails

def test_wrong_patch(mock_get):
    pass

# Correct patch path example
@patch('your_module.requests.get')
def test_correct_patch(mock_get):
    pass
๐Ÿ“Š

Quick Reference

Remember these key points when mocking API calls in pytest:

  • Use unittest.mock.patch to replace network calls.
  • Set mock.return_value.status_code and mock.return_value.json.return_value for HTTP mocks.
  • Patch the function where it is used, not where it is defined.
  • Use mock.assert_called_once_with() to verify calls.
โœ…

Key Takeaways

Use unittest.mock.patch to replace API calls with mocks in pytest tests.
Always patch the API call at the location where your code imports it.
Configure mock return values to simulate API responses accurately.
Avoid real network calls in tests to keep them fast and reliable.
Verify your mocks were called with expected arguments using assertions.