Skip to content

Instantly share code, notes, and snippets.

@elnygren
Created August 8, 2021 12:15
Show Gist options
  • Save elnygren/7d4eb69ea1f2c6ba1a4865535f00ed2c to your computer and use it in GitHub Desktop.
Save elnygren/7d4eb69ea1f2c6ba1a4865535f00ed2c to your computer and use it in GitHub Desktop.
Patching in Python with pytest using monkeypatch and requests_mock
import requests
API_URL = "https://example.com" # often imported from settings
#
# Code
#
def get_user_with_org(id: str):
"""Gets a User object with the User's Organisation"""
# fetch the data (side effect)
user = requests.get(f'{API_URL}/user/{id}').json()
org_id = user['org_id']
organisation = requests.get(f'{API_URL}/organisation/{org_id}').json()
return {'user': user, 'organisation': organisation}
#
# Tests: pytest monkeypatch
#
from unittest.mock import MagicMock
def test_get_user_with_org(monkeypatch):
"""Test getting a user + organisation by mocking the side effect"""
monkeypatch.setattr(requests, "get", lambda _: MagicMock())
result = get_user_with_org("test-id")
assert 'organisation' in result
assert 'user' in result
assert result['user']['org_id'].__str__.called
#
# Tests: pytest + requests_mock
#
import requests_mock
def test_get_user_with_org2(requests_mock):
"""Test getting a user + organisation by mocking with requests_mock library"""
requests_mock.get(
f'{API_URL}/user/user-1',
json={'id': 'user-1', 'name': 'Test User', 'org_id': 'org-1'}
)
requests_mock.get(
f'{API_URL}/organisation/org-1',
json={'id': 'org-1', 'name': 'Test Org'}
)
result = get_user_with_org('user-1')
assert 'organisation' in result
assert 'user' in result
assert result['user']['name'] == 'Test User'
assert result['organisation']['name'] == 'Test Org'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment