Skip to content

Instantly share code, notes, and snippets.

@hectorcanto
Last active February 8, 2019 15:12
Show Gist options
  • Save hectorcanto/0793f0aeab67e922d382fa54975c9566 to your computer and use it in GitHub Desktop.
Save hectorcanto/0793f0aeab67e922d382fa54975c9566 to your computer and use it in GitHub Desktop.
Two samples using a spy, including possible assertions.
"""
In this example we will spy on one method without obstructing it.
When we place
"""
import requests
from unittest.mock import call
URL1 = "https://www.python.org/"
URL2 = "https://www.python.org/dev/peps/pep-0008/"
def test_spy_request(mocker):
session = requests.Session() # Use session if you are going to hit the same server several times
spy = mocker.patch.object(session, "get", wraps=session.get)
response1 = session.get(URL1)
response2 = session.get(URL2)
assert response1.status_code == 200
assert response2.status_code == 200
assert spy.call_count == 2
spy.assert_any_call(URL2)
spy.assert_has_calls([call(URL1), call(URL2)])
spy.assert_has_calls([call(URL2), call(URL1)], any_order=True)
def test_another_spy_request(mocker): # Same test but different call to spy
session = requests.Session() # Use session if you are going to hit the same server several times
spy = mocker.spy(session, "get")
response1 = session.get(URL1)
response2 = session.get(URL2)
assert response1.status_code == 200
assert response2.status_code == 200
assert spy.call_count == 2
spy.assert_any_call(URL2)
spy.assert_has_calls([call(URL1), call(URL2)])
spy.assert_has_calls([call(URL2), call(URL1)], any_order=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment