Last active
June 26, 2017 08:58
-
-
Save va3093/e7ae3eeb76f3e317214e2aa80b576bd6 to your computer and use it in GitHub Desktop.
Convenient way to mock http requests in your tests by wrapping the functionality of httppretty.
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 httpretty | |
import requests | |
def stub_http_request(method='GET', url=None, status=200, json={}): | |
def wrap(func): | |
@httpretty.activate | |
def wrapped_func(*args, **kwargs): | |
httpretty.register_uri(method, url, | |
body=f"{json}".replace("'", '"'), | |
status=status, | |
content_type="application/json") | |
return func(*args, **kwargs) | |
return wrapped_func | |
return wrap | |
# test_something.py | |
@stub_http_request(url='http://www.google.com', status=400, json={'t': 't'}) | |
def test_mock(): | |
res = requests.get('http://www.google.com') | |
assert res.json() == {'t': 't'} | |
assert res.status_code == 400 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment