Skip to content

Commit

Permalink
Let the callback result set the URL of a response
Browse files Browse the repository at this point in the history
  • Loading branch information
betatim committed Apr 30, 2019
1 parent 566461a commit e18aa95
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ for convenience use *payload* argument to mock out json response. Example below.
# will throw an exception.
**aioresponses allows to use callbacks to provide dynamic responses**
**aioresponses allows you to use callbacks to provide dynamic responses**

.. code:: python
Expand Down
6 changes: 5 additions & 1 deletion aioresponses/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ def __init__(self, method: str = hdrs.METH_GET,
payload: Dict = None,
headers: Dict = None,
response_class: 'ClientResponse' = None,
reason: Optional[str] = None):
reason: Optional[str] = None,
url: Optional[URL] = None):
self.method = method
self.status = status
self.body = body
Expand All @@ -45,6 +46,7 @@ def __init__(self, method: str = hdrs.METH_GET,
self.headers = headers
self.response_class = response_class
self.reason = reason
self.url = url


class RequestMatch(object):
Expand Down Expand Up @@ -166,6 +168,8 @@ async def build_response(
return self.exception
if callable(self.callback):
result = self.callback(url, **kwargs)
if result.url is not None:
url = result.url
else:
result = None
result = self if result is None else result
Expand Down
15 changes: 15 additions & 0 deletions tests/test_aioresponses.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,3 +328,18 @@ def callback(url, **kwargs):
response = self.run_async(self.request(self.url))
data = self.run_async(response.read())
assert data == body

@aioresponses()
def test_callback_setting_url(self, m):
body = b'New body'

def callback(url, **kwargs):
self.assertEqual(str(url), self.url)
self.assertEqual(kwargs, {'allow_redirects': True})
return CallbackResult(body=body, url=url.with_query(foo='bar'))

m.get(self.url, callback=callback)
response = self.run_async(self.request(self.url))
data = self.run_async(response.read())
assert response.url == URL(self.url).with_query(foo='bar')
assert data == body

0 comments on commit e18aa95

Please sign in to comment.