Last active
August 29, 2015 14:01
-
-
Save wonderb0lt/e0e463d50be8cc679ab7 to your computer and use it in GitHub Desktop.
Mock requests without responses. Useful, for example, if you want to simulate non-status-code side effects like timeouts. It's a hack, but it works
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
class AmazonResponseMocker(): | |
def __init__(self, response=None, timeout=False): | |
import requests | |
self.response = response | |
self.timeout = timeout | |
self.get = requests.get | |
def __enter__(self): | |
def timeout(*args, **kwargs): | |
from requests.exceptions import Timeout | |
raise Timeout() | |
def response(*args, **kwargs): | |
from collections import namedtuple | |
httpresponse = namedtuple('FakedResponse', ['status_code', 'text']) | |
return httpresponse(status_code=200, text=self.response) | |
if self.timeout: | |
module.to.mocks.get.import = MagicMock().side_effect = timeout | |
else: | |
module.to.mocks.get.import = response | |
def __exit__(self, exc_type, exc_val, exc_tb): | |
module.to.mocks.get.import = self.get |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment