Created
May 15, 2018 13:48
-
-
Save bsweger/18202511b1d32910afb2b8732b2e7ab5 to your computer and use it in GitHub Desktop.
Pytest Snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
import requests | |
@pytest.fixture | |
def mock_request_json(): | |
"""Return fake API data.""" | |
return {'spring': [ | |
{ | |
'name': 'birds', | |
'status': 'chirpin', | |
'start': 1522360809573, | |
'extra_column': 'ignore this', | |
}, | |
{ | |
'name': 'daffodils', | |
'status': 'out', | |
'another_extra': 'ignore this too', | |
}, | |
{ | |
'name': 'tastytop', | |
'status': 'open', | |
'start': 1507927655003, | |
}, | |
{ | |
'name': 'peepers', | |
'status': 'peepin', | |
'start': 1507927655003, | |
}, | |
]} | |
@pytest.fixture | |
def patched_requests(monkeypatch): | |
"""Monkeypatch requests.get.""" | |
def mocked_get(uri, *args, **kwargs): | |
"""A method to replace Requests.get.""" | |
mock = type('MockedReq', (), {})() | |
# create some mock request response data, making | |
# sure to include any status fields checked by | |
# your application code | |
mock.ok = True | |
mock.json = mock_request_json | |
return mock | |
monkeypatch.setattr(requests, 'get', mocked_get) | |
def test_the_thing(patched_requests): | |
"""A test that uses the patched version of requests.get.""" | |
endpoint = 'fake/endpoint' | |
# Call some application code that invokes request.get. | |
# Because we're using the patched_requests fixture, the | |
# application code will use the mocked_get method created | |
# above instead of the regular requests.get | |
data = get_api_data(endpoint) | |
# data is now equal to the json returned by the | |
# mock_request_json function above |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment