Skip to content

Instantly share code, notes, and snippets.

@va3093
Last active June 26, 2017 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save va3093/e7ae3eeb76f3e317214e2aa80b576bd6 to your computer and use it in GitHub Desktop.
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.
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