Mocking External Dependencies: Achieving Reliable Test Results

Mocking External Dependencies: Achieving Reliable Test Results

Testing code that relies on external services, like a database, can be difficult since the behaviors of these services can change.

A mock object can control the behavior of a real object in a testing environment by simulating responses from external services.

Here are two common use cases with examples:

Mocking Time-Dependent Functions

When testing functions that depend on the current time or date, you can mock the time to ensure consistent results.

Example: Testing a function that returns data for the last week

Open In Colab
from datetime import datetime, timedelta


def get_data_for_last_week():
    end_date = datetime.now().date()
    start_date = end_date - timedelta(days=7)
    return {
        "start_date": start_date.strftime("%Y-%m-%d"),
        "end_date": end_date.strftime("%Y-%m-%d"),
    }

Now, let’s create a test for this function using mock:

from datetime import datetime
from unittest.mock import patch
from main import get_data_for_last_week


@patch("main.datetime")
def test_get_data_for_last_week(mock_datetime):
    # Set a fixed date for the test
    mock_datetime.now.return_value = datetime(2024, 8, 5)

    # Call the function
    result = get_data_for_last_week()

    # Assert the results
    assert result["start_date"] == "2024-07-29"
    assert result["end_date"] == "2024-08-05"

    # Verify that datetime.now() was called
    mock_datetime.now.assert_called_once()

This test mocks the datetime.now() method to return a fixed date, allowing for predictable and consistent test results.

Mocking API calls

When testing code that makes external API calls, mocking helps avoid actual network requests during testing.

Example: Testing a function that makes an API call

import requests
from requests.exceptions import ConnectionError


def get_data():
    """Make an API call to Postgres"""
    try:
        response = requests.get("http://localhost:5432")
        return response.json()
    except ConnectionError:
        return None
from unittest.mock import patch
from requests.exceptions import ConnectionError
from main import get_data


@patch("main.requests.get")
def test_get_data_fails(mock_get):
    """Test the get_data function when the API call fails"""
    # Define what happens when the function is called
    mock_get.side_effect = ConnectionError
    assert get_data() is None


@patch("main.requests.get")
def test_get_data_succeeds(mock_get):
    """Test the get_data function when the API call succeeds"""
    # Define the return value of the function
    mock_get.return_value.json.return_value = {"data": "test"}
    assert get_data() == {"data": "test"}

These tests mock the requests.get() function to simulate both successful and failed API calls, allowing us to test our function’s behavior in different scenarios without making actual network requests.

By using mocks in these ways, we can create more reliable and controlled unit tests for our data projects, ensuring that our code behaves correctly under various conditions.

Scroll to Top

Work with Khuyen Tran

Work with Khuyen Tran