Skip to content
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
25 changes: 25 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,31 @@ for convenience use *payload* argument to mock out json response. Example below.
assert resp.status == 418


**aioresponses allows to get the mocked requests**

.. code:: python

import asyncio
import aiohttp
from aioresponses import aioresponses

@aioresponses()
def test_requests(m):
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession()

matcher = m.post('http://example.com', status=500)
m.post('http://example.com', status=200)

loop.run_until_complete(session.post('http://example.com', json={"a": 1}))
loop.run_until_complete(session.post('http://example.com', json={"a": 2}))

requests = aioresponses.matched_requests(matcher)
assert requests[0].kwargs["json"] == {"a": 1}
assert requests[1].kwargs["json"] == {"a": 2}



**aioresponses can be used in a pytest fixture**

.. code:: python
Expand Down
72 changes: 55 additions & 17 deletions aioresponses/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,26 +249,30 @@ def stop(self) -> None:
self.patcher.stop()
self.clear()

def head(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_HEAD, **kwargs)
def head(self, url: 'Union[URL, str, Pattern]', **kwargs) -> RequestMatch:
return self.add(url, method=hdrs.METH_HEAD, **kwargs)

def get(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_GET, **kwargs)
def get(self, url: 'Union[URL, str, Pattern]', **kwargs) -> RequestMatch:
return self.add(url, method=hdrs.METH_GET, **kwargs)

def post(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_POST, **kwargs)
def post(self, url: 'Union[URL, str, Pattern]', **kwargs) -> RequestMatch:
return self.add(url, method=hdrs.METH_POST, **kwargs)

def put(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_PUT, **kwargs)
def put(self, url: 'Union[URL, str, Pattern]', **kwargs) -> RequestMatch:
return self.add(url, method=hdrs.METH_PUT, **kwargs)

def patch(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_PATCH, **kwargs)
def patch(self, url: 'Union[URL, str, Pattern]', **kwargs) -> RequestMatch:
return self.add(url, method=hdrs.METH_PATCH, **kwargs)

def delete(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_DELETE, **kwargs)
def delete(
self, url: 'Union[URL, str, Pattern]', **kwargs
) -> RequestMatch:
return self.add(url, method=hdrs.METH_DELETE, **kwargs)

def options(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_OPTIONS, **kwargs)
def options(
self, url: 'Union[URL, str, Pattern]', **kwargs
) -> RequestMatch:
return self.add(url, method=hdrs.METH_OPTIONS, **kwargs)

def add(self, url: 'Union[URL, str, Pattern]', method: str = hdrs.METH_GET,
status: int = 200,
Expand All @@ -281,8 +285,8 @@ def add(self, url: 'Union[URL, str, Pattern]', method: str = hdrs.METH_GET,
repeat: bool = False,
timeout: bool = False,
reason: Optional[str] = None,
callback: Optional[Callable] = None) -> None:
self._matches.append(RequestMatch(
callback: Optional[Callable] = None) -> RequestMatch:
match = RequestMatch(
url,
method=method,
status=status,
Expand All @@ -296,7 +300,9 @@ def add(self, url: 'Union[URL, str, Pattern]', method: str = hdrs.METH_GET,
timeout=timeout,
reason=reason,
callback=callback,
))
)
self._matches.append(match)
return match

async def match(
self, method: str, url: URL, **kwargs: Dict
Expand All @@ -314,6 +320,38 @@ async def match(
raise response
return response

def matched_requests(self, matcher: RequestMatch) -> List[RequestCall]:
"""
Given a RequestMatch, return all mocked requests that
matched this matcher.

Example:

loop = asyncio.get_event_loop()
session = aiohttp.ClientSession()

matcher = m.post('http://example.com', status=500)
m.post('http://example.com', status=200)

loop.run_until_complete(
session.post('http://example.com', json={"a": 1})
)
loop.run_until_complete(
session.post('http://example.com', json={"a": 2})
)

requests = aioresponses.matched_requests(matcher)
assert requests[0].kwargs["json"] == {"a": 1}
assert requests[1].kwargs["json"] == {"a": 2}
"""
matched = []

for key, requests in self.requests.items():
if matcher.match(*key):
matched.extend(requests)

return matched

async def _request_mock(self, orig_self: ClientSession,
method: str, url: 'Union[URL, str]',
*args: Tuple,
Expand Down
42 changes: 41 additions & 1 deletion tests/test_aioresponses.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@
)
from aiohttp.http_exceptions import HttpProcessingError

from aioresponses.compat import AIOHTTP_VERSION, URL
from aioresponses import CallbackResult, aioresponses
from aioresponses.compat import AIOHTTP_VERSION, URL
from aioresponses.core import RequestCall


@ddt
Expand Down Expand Up @@ -363,6 +364,45 @@ def callback(url, **kwargs):
data = self.run_async(response.read())
assert data == body

@aioresponses()
@asyncio.coroutine
def test_matched_requests(self, mocked):
matcher_1 = mocked.get(
re.compile(r'^http://example\.com/api\?foo=.*$'),
status=200
)

matcher_2 = mocked.get(
re.compile(r'^http://example\.com/api\?foo=.*$'),
status=200
)

matcher_3 = mocked.get('http://example.com/other_api?foo=c', status=200)

url_1 = 'http://example.com/api'
url_3 = 'http://example.com/other_api'

yield from self.session.get(url_1, params={"foo": "a"})
yield from self.session.get(url_1, params={"foo": "b"})
yield from self.session.get(url_3, params={"foo": "c"})

# matcher 1 and 2 match the same requests,
# since they have the same regex as key
matched_1 = mocked.matched_requests(matcher_1)
matched_2 = mocked.matched_requests(matcher_2)
expected = [
RequestCall(tuple(), {"allow_redirects": True, "params": {"foo": "a"}}),
RequestCall(tuple(), {"allow_redirects": True, "params": {"foo": "b"}}),
]
assert matched_1 == expected
assert matched_2 == expected

# matcher 3 matches another set of requests
matched_3 = mocked.matched_requests(matcher_3)
assert matched_3 == [
RequestCall(tuple(), {"allow_redirects": True, "params": {"foo": "c"}}),
]


class AIOResponsesRaiseForStatusSessionTestCase(TestCase):
"""Test case for sessions with raise_for_status=True.
Expand Down