Created
October 23, 2017 17:37
-
-
Save edersonbadeca/92b27d7a81164408f4445f949131ba83 to your computer and use it in GitHub Desktop.
Python Utility for asynchronous mocking
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 asyncio | |
from unittest import mock | |
class AsyncMock(mock.MagicMock): | |
@asyncio.coroutine | |
def __call__(self, *args, **kwargs): | |
return super(AsyncMock, self).__call__(*args, **kwargs) | |
# Alternative using Tornado... | |
class AsyncMock(mock.MagicMock): | |
async def __call__(self, *args, **kwargs): | |
return super().__call__(*args, **kwargs) | |
def empty_http_request(url="localhost", headers={}): | |
return HTTPRequest(url=url, headers=HTTPHeaders(**headers)) | |
def empty_http_response(body="", code=200, error=None): | |
return HTTPResponse( | |
request=empty_http_request(), | |
headers=HTTPHeaders(), | |
code=code, | |
buffer=BytesIO(body.encode()), | |
error=error | |
) | |
def response_to_future(response): | |
f = Future() | |
f.set_result(response) | |
return f | |
class StaleClientTests(testing.AsyncTestCase): | |
def setUp(self): | |
super(StaleClientTests, self).setUp() | |
@mock.patch("bf_stale_client.client.api_gateway") | |
@testing.gen_test | |
async def test_api_gateway_call(self, mock_api_gateway): | |
response = empty_http_response(body="body") | |
request = empty_http_request(headers={"x-auth-token": "foo"}) | |
http_client = mock.MagicMock() | |
http_client.fetch.return_value = response_to_future(empty_http_response("body")) | |
# TODO: change arg to response | |
mock_api_gateway.get = AsyncMock(return_value=empty_http_response("body")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment