Created
July 11, 2018 12:49
-
-
Save ripiuk/1e9eff95f718ce3506bbaf37ff152e4d to your computer and use it in GitHub Desktop.
Pytest mock requests.get() using monkeypatch
This file contains hidden or 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 requests | |
def get_scan_id(url: str) -> int: | |
""" | |
Response example: | |
>>>requests.get('http://.../sequence/v1/generateid?sequenceName=assignments') | |
{"counter":{"_id":"assignments","seq":401865077},"message":"ok"} | |
""" | |
try: | |
response = requests.get(url).json() | |
except requests.RequestException: | |
raise SomeException("ScanApi request failed. URL: {url}".format(url=url)) | |
if response.get('message') != 'ok': | |
raise SomeException("Failed to get valid scan id from ScanApi: {message}".format( | |
message=response.get('message'))) | |
return response.get('counter', dict()).get('seq') | |
class SomeException(Exception): | |
pass |
This file contains hidden or 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
from functools import partial | |
import pytest | |
import scanapi_client | |
def mocked_requests_get(json_resp=None, *args, **kwargs): | |
class MockResponse: | |
def __init__(self, json_data, status_code): | |
self.json_data = json_data | |
self.status_code = status_code | |
def json(self): | |
return self.json_data | |
return MockResponse(json_resp, 200) | |
@pytest.mark.parametrize("json_response,expected_value,exception", [ | |
({"counter": {"_id": "assignments", "seq": 401865077}, "message": "ok"}, 401865077, None), | |
({"counter": {"_id": "test", "seq": 432}, "message": "ok"}, 432, None), | |
({"counter": {"_id": "not_exists", "seq": 0}, "message": "sequence not_exists was not found!"}, | |
None, scanapi_client.SomeException) | |
]) | |
def test_get_scan_id(json_response, expected_value, exception, monkeypatch): | |
monkeypatch.setattr(scanapi_client.requests, 'get', partial(mocked_requests_get, json_response)) | |
if exception: | |
with pytest.raises(exception): | |
scanapi_client.get_scan_id('') | |
else: | |
assert scanapi_client.get_scan_id('') == expected_value |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment