Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Let the callback result set the URL of a response #120

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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