Skip to content

Commit

Permalink
Merge pull request pnuckowski#189 from wblxyxolbkhv/relative_urls_red…
Browse files Browse the repository at this point in the history
…irect

Add relative urls support to redirect feature
  • Loading branch information
pnuckowski authored Jan 17, 2022
2 parents 9303268 + f082ba4 commit 4d9259e
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
35 changes: 35 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,41 @@ for convenience use *payload* argument to mock out json response. Example below.
assert resp.status == 200
**allows to make redirects responses**

.. code:: python
import asyncio
import aiohttp
from aioresponses import aioresponses
@aioresponses()
def test_redirect_example(m):
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession()
# absolute urls are supported
m.get(
'http://example.com/',
headers={'Location': 'http://another.com/'},
status=307
)
resp = loop.run_until_complete(
session.get('http://example.com/', allow_redirects=True)
)
assert resp.url == 'http://another.com/'
# and also relative
m.get(
'http://example.com/',
headers={'Location': '/test'},
status=307
)
resp = loop.run_until_complete(
session.get('http://example.com/', allow_redirects=True)
)
assert resp.url == 'http://example.com/test'
**allows to passthrough to a specified list of servers**

Expand Down
6 changes: 5 additions & 1 deletion aioresponses/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,7 +353,11 @@ async def match(
if hdrs.LOCATION not in response_or_exc.headers:
break
history.append(response_or_exc)
url = URL(response_or_exc.headers[hdrs.LOCATION])
redirect_url = URL(response_or_exc.headers[hdrs.LOCATION])
if redirect_url.is_absolute():
url = redirect_url
else:
url = url.join(redirect_url)
method = 'get'
continue
else:
Expand Down
18 changes: 18 additions & 0 deletions tests/test_aioresponses.py
Original file line number Diff line number Diff line change
Expand Up @@ -655,3 +655,21 @@ async def test_request_info_with_original_request_headers(self, rsps):
request_info = response.request_info
assert str(request_info.url) == self.url
assert request_info.headers == headers

@aioresponses()
async def test_relative_url_redirect_followed(self, rsps):
base_url = "https://httpbin.org"
url = f"{base_url}/foo/bar"
rsps.get(
url,
status=307,
headers={"Location": "../baz"},
)
rsps.get(f"{base_url}/baz")

response = await self.session.get(url, allow_redirects=True)

self.assertEqual(response.status, 200)
self.assertEqual(str(response.url), f"{base_url}/baz")
self.assertEqual(len(response.history), 1)
self.assertEqual(str(response.history[0].url), url)

0 comments on commit 4d9259e

Please sign in to comment.