Contributors
------------
None yet. Why not be the first?
aioresponses-0.7.3/CONTRIBUTING.rst 0000664 0000000 0000000 00000006313 14167132246 0016705 0 ustar 00root root 0000000 0000000 .. highlight:: shell
============
Contributing
============
Contributions are welcome, and they are greatly appreciated! Every
little bit helps, and credit will always be given.
You can contribute in many ways:
Types of Contributions
----------------------
Report Bugs
~~~~~~~~~~~
Report bugs at https://github.com/pnuckowski/aioresponses/issues.
If you are reporting a bug, please include:
* Your operating system name and version.
* Any details about your local setup that might be helpful in troubleshooting.
* Detailed steps to reproduce the bug.
Fix Bugs
~~~~~~~~
Look through the GitHub issues for bugs. Anything tagged with "bug"
and "help wanted" is open to whoever wants to implement it.
Implement Features
~~~~~~~~~~~~~~~~~~
Look through the GitHub issues for features. Anything tagged with "enhancement"
and "help wanted" is open to whoever wants to implement it.
Write Documentation
~~~~~~~~~~~~~~~~~~~
aioresponses could always use more documentation, whether as part of the
official aioresponses docs, in docstrings, or even on the web in blog posts,
articles, and such.
Submit Feedback
~~~~~~~~~~~~~~~
The best way to send feedback is to file an issue at https://github.com/pnuckowski/aioresponses/issues.
If you are proposing a feature:
* Explain in detail how it would work.
* Keep the scope as narrow as possible, to make it easier to implement.
* Remember that this is a volunteer-driven project, and that contributions
are welcome :)
Get Started!
------------
Ready to contribute? Here's how to set up `aioresponses` for local development.
1. Fork the `aioresponses` repo on GitHub.
2. Clone your fork locally::
$ git clone git@github.com:your_name_here/aioresponses.git
3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development::
$ mkvirtualenv aioresponses
$ cd aioresponses/
$ python setup.py develop
4. Create a branch for local development::
$ git checkout -b name-of-your-bugfix-or-feature
Now you can make your changes locally.
5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox::
$ flake8 aioresponses tests
$ python setup.py test
$ tox
To get flake8 and tox, just pip install them into your virtualenv.
6. Commit your changes and push your branch to GitHub::
$ git add .
$ git commit -m "Your detailed description of your changes."
$ git push origin name-of-your-bugfix-or-feature
7. Submit a pull request through the GitHub website.
Pull Request Guidelines
-----------------------
Before you submit a pull request, check that it meets these guidelines:
1. The pull request should include tests.
2. If the pull request adds functionality, the docs should be updated. Put
your new functionality into a function with a docstring, and add the
feature to the list in README.rst.
3. The pull request should work for Python 3.5, 3.6, 3.7 and for PyPy. Check
https://travis-ci.org/pnuckowski/aioresponses/pull_requests
and make sure that the tests pass for all supported Python versions.
Tips
----
To run a subset of tests::
$ python -m unittest tests.test_aioresponses
aioresponses-0.7.3/HISTORY.rst 0000664 0000000 0000000 00000000121 14167132246 0016126 0 ustar 00root root 0000000 0000000 =======
History
=======
0.1.0 (2016-10-17)
------------------
* initial commit
aioresponses-0.7.3/LICENSE 0000664 0000000 0000000 00000002053 14167132246 0015246 0 ustar 00root root 0000000 0000000 MIT License
Copyright (c) 2016 pnuckowski
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
aioresponses-0.7.3/MANIFEST.in 0000664 0000000 0000000 00000000410 14167132246 0015772 0 ustar 00root root 0000000 0000000
include AUTHORS.rst
include CONTRIBUTING.rst
include HISTORY.rst
include LICENSE
include README.rst
recursive-include tests *
recursive-exclude * __pycache__
recursive-exclude * *.py[co]
recursive-include docs *.rst conf.py Makefile make.bat *.jpg *.png *.gif
aioresponses-0.7.3/Makefile 0000664 0000000 0000000 00000004437 14167132246 0015711 0 ustar 00root root 0000000 0000000 .PHONY: clean clean-test clean-pyc clean-build docs help
.DEFAULT_GOAL := help
define BROWSER_PYSCRIPT
import os, webbrowser, sys
try:
from urllib import pathname2url
except:
from urllib.request import pathname2url
webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
endef
export BROWSER_PYSCRIPT
define PRINT_HELP_PYSCRIPT
import re, sys
for line in sys.stdin:
match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
if match:
target, help = match.groups()
print("%-20s %s" % (target, help))
endef
export PRINT_HELP_PYSCRIPT
BROWSER := python -c "$$BROWSER_PYSCRIPT"
help:
@python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
clean: clean-build clean-pyc clean-test ## remove all build, test, coverage and Python artifacts
clean-build: ## remove build artifacts
rm -fr build/
rm -fr dist/
rm -fr .eggs/
find . -name '*.egg-info' -exec rm -fr {} +
find . -name '*.egg' -exec rm -f {} +
clean-pyc: ## remove Python file artifacts
find . -name '*.pyc' -exec rm -f {} +
find . -name '*.pyo' -exec rm -f {} +
find . -name '*~' -exec rm -f {} +
find . -name '__pycache__' -exec rm -fr {} +
clean-test: ## remove test and coverage artifacts
rm -fr .tox/
rm -fr .pytest_cache/
rm -f .coverage
rm -fr htmlcov/
lint: ## check style with flake8
flake8 aioresponses tests
test: ## run tests quickly with the default Python
python setup.py test
test-all: ## run tests on every Python version with tox
tox
coverage: ## check code coverage quickly with the default Python
coverage run --source aioresponses setup.py test
coverage report -m
coverage html
$(BROWSER) htmlcov/index.html
docs: ## generate Sphinx HTML documentation, including API docs
rm -f docs/aioresponses.rst
rm -f docs/modules.rst
sphinx-apidoc -o docs/ aioresponses
$(MAKE) -C docs clean
$(MAKE) -C docs html
$(BROWSER) docs/_build/html/index.html
servedocs: docs ## compile the docs watching for changes
watchmedo shell-command -p '*.rst' -c '$(MAKE) -C docs html' -R -D .
release: clean ## package and upload a release
python setup.py sdist upload
python setup.py bdist_wheel upload
dist: clean ## builds source and wheel package
python setup.py sdist
python setup.py bdist_wheel
ls -l dist
install: clean ## install the package to the active Python's site-packages
python setup.py install
aioresponses-0.7.3/README.rst 0000664 0000000 0000000 00000015443 14167132246 0015737 0 ustar 00root root 0000000 0000000 ===============================
aioresponses
===============================
.. image:: https://travis-ci.org/pnuckowski/aioresponses.svg?branch=master
:target: https://travis-ci.org/pnuckowski/aioresponses
.. image:: https://coveralls.io/repos/github/pnuckowski/aioresponses/badge.svg?branch=master
:target: https://coveralls.io/github/pnuckowski/aioresponses?branch=master
.. image:: https://landscape.io/github/pnuckowski/aioresponses/master/landscape.svg?style=flat
:target: https://landscape.io/github/pnuckowski/aioresponses/master
:alt: Code Health
.. image:: https://pyup.io/repos/github/pnuckowski/aioresponses/shield.svg
:target: https://pyup.io/repos/github/pnuckowski/aioresponses/
:alt: Updates
.. image:: https://img.shields.io/pypi/v/aioresponses.svg
:target: https://pypi.python.org/pypi/aioresponses
.. image:: https://readthedocs.org/projects/aioresponses/badge/?version=latest
:target: https://aioresponses.readthedocs.io/en/latest/?badge=latest
:alt: Documentation Status
Aioresponses is a helper to mock/fake web requests in python aiohttp package.
For *requests* module there are a lot of packages that help us with testing (eg. *httpretty*, *responses*, *requests-mock*).
When it comes to testing asynchronous HTTP requests it is a bit harder (at least at the beginning).
The purpose of this package is to provide an easy way to test asynchronous HTTP requests.
Installing
----------
.. code:: bash
$ pip install aioresponses
Supported versions
------------------
- Python 3.5.3+
- aiohttp>=2.0.0,<4.0.0
Usage
--------
To mock out HTTP request use *aioresponses* as a method decorator or as a context manager.
Response *status* code, *body*, *payload* (for json response) and *headers* can be mocked.
Supported HTTP methods: **GET**, **POST**, **PUT**, **PATCH**, **DELETE** and **OPTIONS**.
.. code:: python
import aiohttp
import asyncio
from aioresponses import aioresponses
@aioresponses()
def test_request(mocked):
loop = asyncio.get_event_loop()
mocked.get('http://example.com', status=200, body='test')
session = aiohttp.ClientSession()
resp = loop.run_until_complete(session.get('http://example.com'))
assert resp.status == 200
for convenience use *payload* argument to mock out json response. Example below.
**as a context manager**
.. code:: python
import asyncio
import aiohttp
from aioresponses import aioresponses
def test_ctx():
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession()
with aioresponses() as m:
m.get('http://test.example.com', payload=dict(foo='bar'))
resp = loop.run_until_complete(session.get('http://test.example.com'))
data = loop.run_until_complete(resp.json())
assert dict(foo='bar') == data
**aioresponses allows to mock out any HTTP headers**
.. code:: python
import asyncio
import aiohttp
from aioresponses import aioresponses
@aioresponses()
def test_http_headers(m):
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession()
m.post(
'http://example.com',
payload=dict(),
headers=dict(connection='keep-alive'),
)
resp = loop.run_until_complete(session.post('http://example.com'))
# note that we pass 'connection' but get 'Connection' (capitalized)
# under the neath `multidict` is used to work with HTTP headers
assert resp.headers['Connection'] == 'keep-alive'
**allows to register different responses for the same url**
.. code:: python
import asyncio
import aiohttp
from aioresponses import aioresponses
@aioresponses()
def test_multiple_responses(m):
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession()
m.get('http://example.com', status=500)
m.get('http://example.com', status=200)
resp1 = loop.run_until_complete(session.get('http://example.com'))
resp2 = loop.run_until_complete(session.get('http://example.com'))
assert resp1.status == 500
assert resp2.status == 200
**match URLs with regular expressions**
.. code:: python
import asyncio
import aiohttp
import re
from aioresponses import aioresponses
@aioresponses()
def test_regexp_example(m):
loop = asyncio.get_event_loop()
session = aiohttp.ClientSession()
pattern = re.compile(r'^http://example\.com/api\?foo=.*$')
m.get(pattern, status=200)
resp = loop.run_until_complete(session.get('http://example.com/api?foo=bar'))
assert resp.status == 200
**allows to passthrough to a specified list of servers**
.. code:: python
import asyncio
import aiohttp
from aioresponses import aioresponses
@aioresponses(passthrough=['http://backend'])
def test_passthrough(m, test_client):
session = aiohttp.ClientSession()
# this will actually perform a request
resp = loop.run_until_complete(session.get('http://backend/api'))
**aioresponses allows to throw an exception**
.. code:: python
import asyncio
from aiohttp import ClientSession
from aiohttp.http_exceptions import HttpProcessingError
from aioresponses import aioresponses
@aioresponses()
def test_how_to_throw_an_exception(m, test_client):
loop = asyncio.get_event_loop()
session = ClientSession()
m.get('http://example.com/api', exception=HttpProcessingError('test'))
# calling
# loop.run_until_complete(session.get('http://example.com/api'))
# will throw an exception.
**aioresponses allows to use callbacks to provide dynamic responses**
.. code:: python
import asyncio
import aiohttp
from aioresponses import CallbackResult, aioresponses
def callback(url, **kwargs):
return CallbackResult(status=418)
@aioresponses()
def test_callback(m, test_client):
loop = asyncio.get_event_loop()
session = ClientSession()
m.get('http://example.com', callback=callback)
resp = loop.run_until_complete(session.get('http://example.com'))
assert resp.status == 418
**aioresponses can be used in a pytest fixture**
.. code:: python
import pytest
from aioresponses import aioresponses
@pytest.fixture
def mock_aioresponse():
with aioresponses() as m:
yield m
Features
--------
* Easy to mock out HTTP requests made by *aiohttp.ClientSession*
License
-------
* Free software: MIT license
Credits
-------
This package was created with Cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template.
.. _Cookiecutter: https://github.com/audreyr/cookiecutter
.. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage
aioresponses-0.7.3/aioresponses/ 0000775 0000000 0000000 00000000000 14167132246 0016753 5 ustar 00root root 0000000 0000000 aioresponses-0.7.3/aioresponses/__init__.py 0000664 0000000 0000000 00000000227 14167132246 0021065 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
from .core import CallbackResult, aioresponses
__version__ = '0.7.2'
__all__ = [
'CallbackResult',
'aioresponses',
]
aioresponses-0.7.3/aioresponses/compat.py 0000664 0000000 0000000 00000003537 14167132246 0020620 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
import asyncio # noqa: F401
import sys
from typing import Dict, Optional, Tuple, Union # noqa
from urllib.parse import parse_qsl, urlencode
from aiohttp import __version__ as aiohttp_version, StreamReader
from multidict import MultiDict
from pkg_resources import parse_version
from yarl import URL
if sys.version_info < (3, 7):
from re import _pattern_type as Pattern
else:
from re import Pattern
AIOHTTP_VERSION = parse_version(aiohttp_version)
if AIOHTTP_VERSION >= parse_version('3.0.0'):
from aiohttp.client_proto import ResponseHandler
def stream_reader_factory( # noqa
loop: 'Optional[asyncio.AbstractEventLoop]' = None
):
protocol = ResponseHandler(loop=loop)
return StreamReader(protocol, limit=2 ** 16, loop=loop)
else:
def stream_reader_factory(loop=None):
return StreamReader()
def merge_params(url: 'Union[URL, str]', params: 'Dict' = None) -> 'URL':
url = URL(url)
if params:
query_params = MultiDict(url.query)
query_params.extend(url.with_query(params).query)
return url.with_query(query_params)
return url
def normalize_url(url: 'Union[URL, str]') -> 'URL':
"""Normalize url to make comparisons."""
url = URL(url)
return url.with_query(urlencode(sorted(parse_qsl(url.query_string))))
try:
from aiohttp import RequestInfo
except ImportError:
class RequestInfo(object):
__slots__ = ('url', 'method', 'headers', 'real_url')
def __init__(
self, url: URL, method: str, headers: Dict, real_url: str
):
self.url = url
self.method = method
self.headers = headers
self.real_url = real_url
__all__ = [
'URL',
'Pattern',
'RequestInfo',
'AIOHTTP_VERSION',
'merge_params',
'stream_reader_factory',
'normalize_url',
]
aioresponses-0.7.3/aioresponses/core.py 0000664 0000000 0000000 00000033755 14167132246 0020272 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
import asyncio
import copy
import inspect
import json
from collections import namedtuple
from functools import wraps
from typing import Callable, Dict, Tuple, Union, Optional, List # noqa
from unittest.mock import Mock, patch
from uuid import uuid4
from aiohttp import (
ClientConnectionError,
ClientResponse,
ClientSession,
hdrs,
http
)
from aiohttp.helpers import TimerNoop
from multidict import CIMultiDict, CIMultiDictProxy
from pkg_resources import parse_version
from .compat import (
AIOHTTP_VERSION,
URL,
Pattern,
stream_reader_factory,
merge_params,
normalize_url,
RequestInfo,
)
class CallbackResult:
def __init__(self, method: str = hdrs.METH_GET,
status: int = 200,
body: Union[str, bytes] = '',
content_type: str = 'application/json',
payload: Dict = None,
headers: Dict = None,
response_class: 'ClientResponse' = None,
reason: Optional[str] = None):
self.method = method
self.status = status
self.body = body
self.content_type = content_type
self.payload = payload
self.headers = headers
self.response_class = response_class
self.reason = reason
class RequestMatch(object):
url_or_pattern = None # type: Union[URL, Pattern]
def __init__(self, url: Union[URL, str, Pattern],
method: str = hdrs.METH_GET,
status: int = 200,
body: Union[str, bytes] = '',
payload: Dict = None,
exception: 'Exception' = None,
headers: Dict = None,
content_type: str = 'application/json',
response_class: 'ClientResponse' = None,
timeout: bool = False,
repeat: bool = False,
reason: Optional[str] = None,
callback: Optional[Callable] = None):
if isinstance(url, Pattern):
self.url_or_pattern = url
self.match_func = self.match_regexp
else:
self.url_or_pattern = normalize_url(url)
self.match_func = self.match_str
self.method = method.lower()
self.status = status
self.body = body
self.payload = payload
self.exception = exception
if timeout:
self.exception = asyncio.TimeoutError('Connection timeout test')
self.headers = headers
self.content_type = content_type
self.response_class = response_class
self.repeat = repeat
self.reason = reason
if self.reason is None:
try:
self.reason = http.RESPONSES[self.status][0]
except (IndexError, KeyError):
self.reason = ''
self.callback = callback
def match_str(self, url: URL) -> bool:
return self.url_or_pattern == url
def match_regexp(self, url: URL) -> bool:
return bool(self.url_or_pattern.match(str(url)))
def match(self, method: str, url: URL) -> bool:
if self.method != method.lower():
return False
return self.match_func(url)
def _build_raw_headers(self, headers: Dict) -> Tuple:
"""
Convert a dict of headers to a tuple of tuples
Mimics the format of ClientResponse.
"""
raw_headers = []
for k, v in headers.items():
raw_headers.append((k.encode('utf8'), v.encode('utf8')))
return tuple(raw_headers)
def _build_response(self, url: 'Union[URL, str]',
method: str = hdrs.METH_GET,
request_headers: Dict = None,
status: int = 200,
body: Union[str, bytes] = '',
content_type: str = 'application/json',
payload: Dict = None,
headers: Dict = None,
response_class: 'ClientResponse' = None,
reason: Optional[str] = None) -> ClientResponse:
if response_class is None:
response_class = ClientResponse
if payload is not None:
body = json.dumps(payload)
if not isinstance(body, bytes):
body = str.encode(body)
if request_headers is None:
request_headers = {}
kwargs = {}
if AIOHTTP_VERSION >= parse_version('3.1.0'):
loop = Mock()
loop.get_debug = Mock()
loop.get_debug.return_value = True
kwargs['request_info'] = RequestInfo(
url=url,
method=method,
headers=CIMultiDictProxy(CIMultiDict(**request_headers)),
)
kwargs['writer'] = Mock()
kwargs['continue100'] = None
kwargs['timer'] = TimerNoop()
if AIOHTTP_VERSION < parse_version('3.3.0'):
kwargs['auto_decompress'] = True
kwargs['traces'] = []
kwargs['loop'] = loop
kwargs['session'] = None
else:
loop = None
# We need to initialize headers manually
_headers = CIMultiDict({hdrs.CONTENT_TYPE: content_type})
if headers:
_headers.update(headers)
raw_headers = self._build_raw_headers(_headers)
resp = response_class(method, url, **kwargs)
for hdr in _headers.getall(hdrs.SET_COOKIE, ()):
resp.cookies.load(hdr)
if AIOHTTP_VERSION >= parse_version('3.3.0'):
# Reified attributes
resp._headers = _headers
resp._raw_headers = raw_headers
else:
resp.headers = _headers
resp.raw_headers = raw_headers
resp.status = status
resp.reason = reason
resp.content = stream_reader_factory(loop)
resp.content.feed_data(body)
resp.content.feed_eof()
return resp
async def build_response(
self, url: URL, **kwargs
) -> 'Union[ClientResponse, Exception]':
if callable(self.callback):
if asyncio.iscoroutinefunction(self.callback):
result = await self.callback(url, **kwargs)
else:
result = self.callback(url, **kwargs)
else:
result = None
if self.exception is not None:
return self.exception
result = self if result is None else result
resp = self._build_response(
url=url,
method=result.method,
request_headers=kwargs.get("headers"),
status=result.status,
body=result.body,
content_type=result.content_type,
payload=result.payload,
headers=result.headers,
response_class=result.response_class,
reason=result.reason)
return resp
RequestCall = namedtuple('RequestCall', ['args', 'kwargs'])
class aioresponses(object):
"""Mock aiohttp requests made by ClientSession."""
_matches = None # type: Dict[str, RequestMatch]
_responses = None # type: List[ClientResponse]
requests = None # type: Dict
def __init__(self, **kwargs):
self._param = kwargs.pop('param', None)
self._passthrough = kwargs.pop('passthrough', [])
self.patcher = patch('aiohttp.client.ClientSession._request',
side_effect=self._request_mock,
autospec=True)
self.requests = {}
def __enter__(self) -> 'aioresponses':
self.start()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
def __call__(self, f):
def _pack_arguments(ctx, *args, **kwargs) -> Tuple[Tuple, Dict]:
if self._param:
kwargs[self._param] = ctx
else:
args += (ctx,)
return args, kwargs
if asyncio.iscoroutinefunction(f):
@wraps(f)
async def wrapped(*args, **kwargs):
with self as ctx:
args, kwargs = _pack_arguments(ctx, *args, **kwargs)
return await f(*args, **kwargs)
else:
@wraps(f)
def wrapped(*args, **kwargs):
with self as ctx:
args, kwargs = _pack_arguments(ctx, *args, **kwargs)
return f(*args, **kwargs)
return wrapped
def clear(self):
self._responses.clear()
self._matches.clear()
def start(self):
self._responses = []
self._matches = {}
self.patcher.start()
self.patcher.return_value = self._request_mock
def stop(self) -> None:
for response in self._responses:
response.close()
self.patcher.stop()
self.clear()
def head(self, url: 'Union[URL, str, Pattern]', **kwargs):
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 post(self, url: 'Union[URL, str, Pattern]', **kwargs):
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 patch(self, url: 'Union[URL, str, Pattern]', **kwargs):
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 options(self, url: 'Union[URL, str, Pattern]', **kwargs):
self.add(url, method=hdrs.METH_OPTIONS, **kwargs)
def add(self, url: 'Union[URL, str, Pattern]', method: str = hdrs.METH_GET,
status: int = 200,
body: Union[str, bytes] = '',
exception: 'Exception' = None,
content_type: str = 'application/json',
payload: Dict = None,
headers: Dict = None,
response_class: 'ClientResponse' = None,
repeat: bool = False,
timeout: bool = False,
reason: Optional[str] = None,
callback: Optional[Callable] = None) -> None:
self._matches[str(uuid4())] = (RequestMatch(
url,
method=method,
status=status,
content_type=content_type,
body=body,
exception=exception,
payload=payload,
headers=headers,
response_class=response_class,
repeat=repeat,
timeout=timeout,
reason=reason,
callback=callback,
))
@staticmethod
def is_exception(resp_or_exc: Union[ClientResponse, Exception]) -> bool:
if inspect.isclass(resp_or_exc):
parent_classes = set(inspect.getmro(resp_or_exc))
if {Exception, BaseException} & parent_classes:
return True
else:
if isinstance(resp_or_exc, (Exception, BaseException)):
return True
return False
async def match(
self, method: str, url: URL,
allow_redirects: bool = True, **kwargs: Dict
) -> Optional['ClientResponse']:
history = []
while True:
for key, matcher in self._matches.items():
if matcher.match(method, url):
response_or_exc = await matcher.build_response(
url, allow_redirects=allow_redirects, **kwargs
)
break
else:
return None
if matcher.repeat is False:
del self._matches[key]
if self.is_exception(response_or_exc):
raise response_or_exc
is_redirect = response_or_exc.status in (301, 302, 303, 307, 308)
if is_redirect and allow_redirects:
if hdrs.LOCATION not in response_or_exc.headers:
break
history.append(response_or_exc)
url = URL(response_or_exc.headers[hdrs.LOCATION])
method = 'get'
continue
else:
break
response_or_exc._history = tuple(history)
return response_or_exc
async def _request_mock(self, orig_self: ClientSession,
method: str, url: 'Union[URL, str]',
*args: Tuple,
**kwargs: Dict) -> 'ClientResponse':
"""Return mocked response object or raise connection error."""
if orig_self.closed:
raise RuntimeError('Session is closed')
url_origin = url
url = normalize_url(merge_params(url, kwargs.get('params')))
url_str = str(url)
for prefix in self._passthrough:
if url_str.startswith(prefix):
return (await self.patcher.temp_original(
orig_self, method, url_origin, *args, **kwargs
))
key = (method, url)
self.requests.setdefault(key, [])
try:
kwargs_copy = copy.deepcopy(kwargs)
except (TypeError, ValueError):
# Handle the fact that some values cannot be deep copied
kwargs_copy = kwargs
self.requests[key].append(RequestCall(args, kwargs_copy))
response = await self.match(method, url, **kwargs)
if response is None:
raise ClientConnectionError(
'Connection refused: {} {}'.format(method, url)
)
self._responses.append(response)
# Automatically call response.raise_for_status() on a request if the
# request was initialized with raise_for_status=True. Also call
# response.raise_for_status() if the client session was initialized
# with raise_for_status=True, unless the request was called with
# raise_for_status=False.
raise_for_status = kwargs.get('raise_for_status')
if raise_for_status is None:
raise_for_status = getattr(
orig_self, '_raise_for_status', False
)
if raise_for_status:
response.raise_for_status()
return response
aioresponses-0.7.3/aioresponses/py.typed 0000664 0000000 0000000 00000000000 14167132246 0020440 0 ustar 00root root 0000000 0000000 aioresponses-0.7.3/docs/ 0000775 0000000 0000000 00000000000 14167132246 0015171 5 ustar 00root root 0000000 0000000 aioresponses-0.7.3/docs/Makefile 0000664 0000000 0000000 00000015202 14167132246 0016631 0 ustar 00root root 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/aioresponses.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/aioresponses.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/aioresponses"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/aioresponses"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
aioresponses-0.7.3/docs/aioresponses.rst 0000664 0000000 0000000 00000000511 14167132246 0020432 0 ustar 00root root 0000000 0000000 aioresponses package
====================
Submodules
----------
aioresponses.core module
------------------------
.. automodule:: aioresponses.core
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: aioresponses
:members:
:undoc-members:
:show-inheritance:
aioresponses-0.7.3/docs/authors.rst 0000664 0000000 0000000 00000000034 14167132246 0017405 0 ustar 00root root 0000000 0000000 .. include:: ../AUTHORS.rst
aioresponses-0.7.3/docs/conf.py 0000775 0000000 0000000 00000020420 14167132246 0016471 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# aioresponses documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
# If extensions (or modules to document with autodoc) are in another
# directory, add these directories to sys.path here. If the directory is
# relative to the documentation root, use os.path.abspath to make it
# absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# Get the project root dir, which is the parent dir of this
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
# Insert the project root dir as the first element in the PYTHONPATH.
# This lets us ensure that the source package is imported, and that its
# version is used.
sys.path.insert(0, project_root)
import aioresponses
# -- General configuration ---------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'aioresponses'
copyright = u"2016, Pawel Nuckowski"
# The version info for the project you're documenting, acts as replacement
# for |version| and |release|, also used in various other places throughout
# the built documents.
#
# The short X.Y version.
version = aioresponses.__version__
# The full version, including alpha/beta/rc tags.
release = aioresponses.__version__
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to
# some non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built
# documents.
#keep_warnings = False
# -- Options for HTML output -------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a
# theme further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as
# html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the
# top of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon
# of the docs. This file should be a Windows icon file (.ico) being
# 16x16 or 32x32 pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets)
# here, relative to this directory. They are copied after the builtin
# static files, so a file named "default.css" will overwrite the builtin
# "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names
# to template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer.
# Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer.
# Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages
# will contain a tag referring to it. The value of this option
# must be the base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'aioresponsesdoc'
# -- Options for LaTeX output ------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass
# [howto/manual]).
latex_documents = [
('index', 'aioresponses.tex',
u'aioresponses Documentation',
u'Pawel Nuckowski', 'manual'),
]
# The name of an image file (relative to this directory) to place at
# the top of the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings
# are parts, not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'aioresponses',
u'aioresponses Documentation',
[u'Pawel Nuckowski'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ----------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'aioresponses',
u'aioresponses Documentation',
u'Pawel Nuckowski',
'aioresponses',
'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
aioresponses-0.7.3/docs/contributing.rst 0000664 0000000 0000000 00000000041 14167132246 0020425 0 ustar 00root root 0000000 0000000 .. include:: ../CONTRIBUTING.rst
aioresponses-0.7.3/docs/history.rst 0000664 0000000 0000000 00000000034 14167132246 0017421 0 ustar 00root root 0000000 0000000 .. include:: ../HISTORY.rst
aioresponses-0.7.3/docs/index.rst 0000664 0000000 0000000 00000000772 14167132246 0017040 0 ustar 00root root 0000000 0000000 .. aioresponses documentation master file, created by
sphinx-quickstart on Tue Jul 9 22:26:36 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to aioresponses's documentation!
======================================
Contents:
.. toctree::
:maxdepth: 2
readme
installation
usage
contributing
authorshistory
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
aioresponses-0.7.3/docs/installation.rst 0000664 0000000 0000000 00000002213 14167132246 0020422 0 ustar 00root root 0000000 0000000 .. highlight:: shell
============
Installation
============
Stable release
--------------
To install aioresponses, run this command in your terminal:
.. code-block:: console
$ pip install aioresponses
This is the preferred method to install aioresponses, as it will always install the most recent stable release.
If you don't have `pip`_ installed, this `Python installation guide`_ can guide
you through the process.
.. _pip: https://pip.pypa.io
.. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/
From sources
------------
The sources for aioresponses can be downloaded from the `Github repo`_.
You can either clone the public repository:
.. code-block:: console
$ git clone git://github.com/pnuckowski/aioresponses
Or download the `tarball`_:
.. code-block:: console
$ curl -OL https://github.com/pnuckowski/aioresponses/tarball/master
Once you have a copy of the source, you can install it with:
.. code-block:: console
$ python setup.py install
.. _Github repo: https://github.com/pnuckowski/aioresponses
.. _tarball: https://github.com/pnuckowski/aioresponses/tarball/master
aioresponses-0.7.3/docs/make.bat 0000664 0000000 0000000 00000014507 14167132246 0016605 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
set I18NSPHINXOPTS=%SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\aioresponses.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\aioresponses.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %BUILDDIR%/..
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
:end
aioresponses-0.7.3/docs/modules.rst 0000664 0000000 0000000 00000000111 14167132246 0017364 0 ustar 00root root 0000000 0000000 aioresponses
============
.. toctree::
:maxdepth: 4
aioresponses
aioresponses-0.7.3/docs/readme.rst 0000664 0000000 0000000 00000000033 14167132246 0017154 0 ustar 00root root 0000000 0000000 .. include:: ../README.rst
aioresponses-0.7.3/docs/usage.rst 0000664 0000000 0000000 00000000117 14167132246 0017026 0 ustar 00root root 0000000 0000000 =====
Usage
=====
To use aioresponses in a project::
import aioresponses
aioresponses-0.7.3/requirements-dev.txt 0000664 0000000 0000000 00000000231 14167132246 0020275 0 ustar 00root root 0000000 0000000 pip
wheel
flake8==3.8.3
tox==3.19.0
coverage==5.2.1
Sphinx==1.5.6
pytest==6.0.1
pytest-cov==2.10.1
pytest-html==2.1.1
ddt==1.4.1
typing
asynctest==0.13.0 aioresponses-0.7.3/requirements.txt 0000664 0000000 0000000 00000000026 14167132246 0017523 0 ustar 00root root 0000000 0000000 aiohttp>=2.0.0,<4.0.0
aioresponses-0.7.3/setup.cfg 0000664 0000000 0000000 00000001703 14167132246 0016063 0 ustar 00root root 0000000 0000000 [metadata]
name = aioresponses
author = Pawel Nuckowski
author_email = p.nuckowski@gmail.com
summary = Mock out requests made by ClientSession from aiohttp package
description_file = README.rst
home_page = https://github.com/pnuckowski/aioresponses
classifier =
Development Status :: 4 - Beta
Intended Audience :: Developers
Operating System :: OS Independent
Topic :: Internet :: WWW/HTTP
Topic :: Software Development :: Testing
Topic :: Software Development :: Testing :: Mocking
License :: OSI Approved :: MIT License
Natural Language :: English
Programming Language :: Python :: 3
Programming Language :: Python :: 3.6
Programming Language :: Python :: 3.7
Programming Language :: Python :: 3.8
Programming Language :: Python :: 3.9
[files]
packages =
aioresponses
[build_sphinx]
all_files = 1
build-dir = docs/build
source-dir = docs/source
[bdist_wheel]
universal = 1
[flake8]
exclude = docs
[tool:pytest]
testpaths = tests
aioresponses-0.7.3/setup.py 0000664 0000000 0000000 00000000147 14167132246 0015755 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
import setuptools
setuptools.setup(
setup_requires=['pbr'],
pbr=True,
)
aioresponses-0.7.3/tests/ 0000775 0000000 0000000 00000000000 14167132246 0015403 5 ustar 00root root 0000000 0000000 aioresponses-0.7.3/tests/__init__.py 0000664 0000000 0000000 00000000000 14167132246 0017502 0 ustar 00root root 0000000 0000000 aioresponses-0.7.3/tests/base.py 0000664 0000000 0000000 00000002571 14167132246 0016674 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
import asyncio
import sys
try:
# as from Py3.8 unittest supports coroutines as test functions
from unittest import IsolatedAsyncioTestCase, skipIf
def fail_on(**kw): # noqa
def outer(fn):
def inner(*args, **kwargs):
return fn(*args, **kwargs)
return inner
return outer
except ImportError:
# fallback to asynctest
from asynctest import fail_on, skipIf
from asynctest.case import TestCase as IsolatedAsyncioTestCase
IS_GTE_PY38 = sys.version_info >= (3, 8)
class AsyncTestCase(IsolatedAsyncioTestCase):
"""Asynchronous test case class that covers up differences in usage
between unittest (starting from Python 3.8) and asynctest.
`setup` and `teardown` is used to be called before each test case
(note: that they are in lowercase)
"""
async def setup(self):
pass
async def teardown(self):
pass
if IS_GTE_PY38:
# from Python3.8
async def asyncSetUp(self):
self.loop = asyncio.get_event_loop()
await self.setup()
async def asyncTearDown(self):
await self.teardown()
else:
# asynctest
use_default_loop = False
async def setUp(self) -> None:
await self.setup()
async def tearDown(self) -> None:
await self.teardown()
aioresponses-0.7.3/tests/test_aioresponses.py 0000664 0000000 0000000 00000056437 14167132246 0021545 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
import asyncio
import re
from asyncio import CancelledError, TimeoutError
from random import uniform
from typing import Coroutine, Generator, Union
from unittest.mock import patch
from aiohttp import hdrs
from aiohttp import http
from aiohttp.client import ClientSession
from aiohttp.client_reqrep import ClientResponse
from ddt import ddt, data
from pkg_resources import parse_version
try:
from aiohttp.errors import (
ClientConnectionError,
ClientResponseError,
HttpProcessingError,
)
except ImportError:
from aiohttp.client_exceptions import (
ClientConnectionError,
ClientResponseError,
)
from aiohttp.http_exceptions import HttpProcessingError
from aioresponses.compat import AIOHTTP_VERSION, URL
from aioresponses import CallbackResult, aioresponses
from .base import fail_on, skipIf, AsyncTestCase
@ddt
class AIOResponsesTestCase(AsyncTestCase):
async def setup(self):
self.url = 'http://example.com/api?foo=bar#fragment'
self.session = ClientSession()
async def teardown(self):
close_result = self.session.close()
if close_result is not None:
await close_result
def run_async(self, coroutine: Union[Coroutine, Generator]):
return self.loop.run_until_complete(coroutine)
async def request(self, url: str):
return await self.session.get(url)
@data(
hdrs.METH_HEAD,
hdrs.METH_GET,
hdrs.METH_POST,
hdrs.METH_PUT,
hdrs.METH_PATCH,
hdrs.METH_DELETE,
hdrs.METH_OPTIONS,
)
@patch('aioresponses.aioresponses.add')
@fail_on(unused_loop=False)
def test_shortcut_method(self, http_method, mocked):
with aioresponses() as m:
getattr(m, http_method.lower())(self.url)
mocked.assert_called_once_with(self.url, method=http_method)
@aioresponses()
def test_returned_instance(self, m):
m.get(self.url)
response = self.run_async(self.session.get(self.url))
self.assertIsInstance(response, ClientResponse)
@aioresponses()
async def test_returned_instance_and_status_code(self, m):
m.get(self.url, status=204)
response = await self.session.get(self.url)
self.assertIsInstance(response, ClientResponse)
self.assertEqual(response.status, 204)
@aioresponses()
async def test_returned_response_headers(self, m):
m.get(self.url,
content_type='text/html',
headers={'Connection': 'keep-alive'})
response = await self.session.get(self.url)
self.assertEqual(response.headers['Connection'], 'keep-alive')
self.assertEqual(response.headers[hdrs.CONTENT_TYPE], 'text/html')
@aioresponses()
async def test_returned_response_cookies(self, m):
m.get(self.url,
headers={'Set-Cookie': 'cookie=value'})
response = await self.session.get(self.url)
self.assertEqual(response.cookies['cookie'].value, 'value')
@aioresponses()
async def test_returned_response_raw_headers(self, m):
m.get(self.url,
content_type='text/html',
headers={'Connection': 'keep-alive'})
response = await self.session.get(self.url)
expected_raw_headers = (
(hdrs.CONTENT_TYPE.encode(), b'text/html'),
(b'Connection', b'keep-alive')
)
self.assertEqual(response.raw_headers, expected_raw_headers)
@aioresponses()
async def test_raise_for_status(self, m):
m.get(self.url, status=400)
with self.assertRaises(ClientResponseError) as cm:
response = await self.session.get(self.url)
response.raise_for_status()
self.assertEqual(cm.exception.message, http.RESPONSES[400][0])
@aioresponses()
@skipIf(condition=AIOHTTP_VERSION < parse_version('3.4.0'),
reason='aiohttp<3.4.0 does not support raise_for_status '
'arguments for requests')
async def test_request_raise_for_status(self, m):
m.get(self.url, status=400)
with self.assertRaises(ClientResponseError) as cm:
await self.session.get(self.url, raise_for_status=True)
self.assertEqual(cm.exception.message, http.RESPONSES[400][0])
@aioresponses()
async def test_returned_instance_and_params_handling(self, m):
expected_url = 'http://example.com/api?foo=bar&x=42#fragment'
m.get(expected_url)
response = await self.session.get(self.url, params={'x': 42})
self.assertIsInstance(response, ClientResponse)
self.assertEqual(response.status, 200)
expected_url = 'http://example.com/api?x=42#fragment'
m.get(expected_url)
response = await self.session.get(
'http://example.com/api#fragment',
params={'x': 42}
)
self.assertIsInstance(response, ClientResponse)
self.assertEqual(response.status, 200)
@aioresponses()
def test_method_dont_match(self, m):
m.get(self.url)
with self.assertRaises(ClientConnectionError):
self.run_async(self.session.post(self.url))
@aioresponses()
async def test_streaming(self, m):
m.get(self.url, body='Test')
resp = await self.session.get(self.url)
content = await resp.content.read()
self.assertEqual(content, b'Test')
@aioresponses()
async def test_streaming_up_to(self, m):
m.get(self.url, body='Test')
resp = await self.session.get(self.url)
content = await resp.content.read(2)
self.assertEqual(content, b'Te')
content = await resp.content.read(2)
self.assertEqual(content, b'st')
@aioresponses()
async def test_binary_body(self, m):
body = b'Invalid utf-8: \x95\x00\x85'
m.get(self.url, body=body)
resp = await self.session.get(self.url)
content = await resp.read()
self.assertEqual(content, body)
@aioresponses()
async def test_binary_body_via_callback(self, m):
body = b'\x00\x01\x02\x80\x81\x82\x83\x84\x85'
def callback(url, **kwargs):
return CallbackResult(body=body)
m.get(self.url, callback=callback)
resp = await self.session.get(self.url)
content = await resp.read()
self.assertEqual(content, body)
async def test_mocking_as_context_manager(self):
with aioresponses() as aiomock:
aiomock.add(self.url, payload={'foo': 'bar'})
resp = await self.session.get(self.url)
self.assertEqual(resp.status, 200)
payload = await resp.json()
self.assertDictEqual(payload, {'foo': 'bar'})
def test_mocking_as_decorator(self):
@aioresponses()
def foo(loop, m):
m.add(self.url, payload={'foo': 'bar'})
resp = loop.run_until_complete(self.session.get(self.url))
self.assertEqual(resp.status, 200)
payload = loop.run_until_complete(resp.json())
self.assertDictEqual(payload, {'foo': 'bar'})
foo(self.loop)
async def test_passing_argument(self):
@aioresponses(param='mocked')
async def foo(mocked):
mocked.add(self.url, payload={'foo': 'bar'})
resp = await self.session.get(self.url)
self.assertEqual(resp.status, 200)
await foo()
@fail_on(unused_loop=False)
def test_mocking_as_decorator_wrong_mocked_arg_name(self):
@aioresponses(param='foo')
def foo(bar):
# no matter what is here it should raise an error
pass
with self.assertRaises(TypeError) as cm:
foo()
exc = cm.exception
self.assertIn("foo() got an unexpected keyword argument 'foo'",
str(exc))
async def test_unknown_request(self):
with aioresponses() as aiomock:
aiomock.add(self.url, payload={'foo': 'bar'})
with self.assertRaises(ClientConnectionError):
await self.session.get('http://example.com/foo')
async def test_raising_exception(self):
with aioresponses() as aiomock:
url = 'http://example.com/Exception'
aiomock.get(url, exception=Exception)
with self.assertRaises(Exception):
await self.session.get(url)
url = 'http://example.com/Exception_object'
aiomock.get(url, exception=Exception())
with self.assertRaises(Exception):
await self.session.get(url)
url = 'http://example.com/BaseException'
aiomock.get(url, exception=BaseException)
with self.assertRaises(BaseException):
await self.session.get(url)
url = 'http://example.com/BaseException_object'
aiomock.get(url, exception=BaseException())
with self.assertRaises(BaseException):
await self.session.get(url)
url = 'http://example.com/CancelError'
aiomock.get(url, exception=CancelledError)
with self.assertRaises(CancelledError):
await self.session.get(url)
url = 'http://example.com/TimeoutError'
aiomock.get(url, exception=TimeoutError)
with self.assertRaises(TimeoutError):
await self.session.get(url)
url = 'http://example.com/HttpProcessingError'
aiomock.get(url, exception=HttpProcessingError(message='foo'))
with self.assertRaises(HttpProcessingError):
await self.session.get(url)
callback_called = asyncio.Event()
url = 'http://example.com/HttpProcessingError'
aiomock.get(url, exception=HttpProcessingError(message='foo'),
callback=lambda *_, **__: callback_called.set())
with self.assertRaises(HttpProcessingError):
await self.session.get(url)
await callback_called.wait()
async def test_multiple_requests(self):
"""Ensure that requests are saved the way they would have been sent."""
with aioresponses() as m:
m.get(self.url, status=200)
m.get(self.url, status=201)
m.get(self.url, status=202)
json_content_as_ref = [1]
resp = await self.session.get(
self.url, json=json_content_as_ref
)
self.assertEqual(resp.status, 200)
json_content_as_ref[:] = [2]
resp = await self.session.get(
self.url, json=json_content_as_ref
)
self.assertEqual(resp.status, 201)
json_content_as_ref[:] = [3]
resp = await self.session.get(
self.url, json=json_content_as_ref
)
self.assertEqual(resp.status, 202)
key = ('GET', URL(self.url))
self.assertIn(key, m.requests)
self.assertEqual(len(m.requests[key]), 3)
first_request = m.requests[key][0]
self.assertEqual(first_request.args, tuple())
self.assertEqual(first_request.kwargs,
{'allow_redirects': True, "json": [1]})
second_request = m.requests[key][1]
self.assertEqual(second_request.args, tuple())
self.assertEqual(second_request.kwargs,
{'allow_redirects': True, "json": [2]})
third_request = m.requests[key][2]
self.assertEqual(third_request.args, tuple())
self.assertEqual(third_request.kwargs,
{'allow_redirects': True, "json": [3]})
async def test_request_with_non_deepcopyable_parameter(self):
def non_deep_copyable():
"""A generator does not allow deepcopy."""
for line in ["header1,header2", "v1,v2", "v10,v20"]:
yield line
generator_value = non_deep_copyable()
with aioresponses() as m:
m.get(self.url, status=200)
resp = await self.session.get(self.url, data=generator_value)
self.assertEqual(resp.status, 200)
key = ('GET', URL(self.url))
self.assertIn(key, m.requests)
self.assertEqual(len(m.requests[key]), 1)
request = m.requests[key][0]
self.assertEqual(request.args, tuple())
self.assertEqual(request.kwargs,
{'allow_redirects': True,
"data": generator_value})
async def test_request_retrieval_in_case_no_response(self):
with aioresponses() as m:
with self.assertRaises(ClientConnectionError):
await self.session.get(self.url)
key = ('GET', URL(self.url))
self.assertIn(key, m.requests)
self.assertEqual(len(m.requests[key]), 1)
self.assertEqual(m.requests[key][0].args, tuple())
self.assertEqual(m.requests[key][0].kwargs,
{'allow_redirects': True})
async def test_request_failure_in_case_session_is_closed(self):
async def do_request(session):
return (await session.get(self.url))
with aioresponses():
coro = do_request(self.session)
await self.session.close()
with self.assertRaises(RuntimeError) as exception_info:
await coro
assert str(exception_info.exception) == "Session is closed"
async def test_address_as_instance_of_url_combined_with_pass_through(self):
external_api = 'http://httpbin.org/status/201'
async def doit():
api_resp = await self.session.get(self.url)
# we have to hit actual url,
# otherwise we do not test pass through option properly
ext_rep = await self.session.get(URL(external_api))
return api_resp, ext_rep
with aioresponses(passthrough=[external_api]) as m:
m.get(self.url, status=200)
api, ext = await doit()
self.assertEqual(api.status, 200)
self.assertEqual(ext.status, 201)
async def test_pass_through_with_origin_params(self):
external_api = 'http://httpbin.org/get'
async def doit(params):
# we have to hit actual url,
# otherwise we do not test pass through option properly
ext_rep = await self.session.get(
URL(external_api), params=params
)
return ext_rep
with aioresponses(passthrough=[external_api]) as m:
params = {'foo': 'bar'}
ext = await doit(params=params)
self.assertEqual(ext.status, 200)
self.assertEqual(str(ext.url), 'http://httpbin.org/get?foo=bar')
@aioresponses()
async def test_custom_response_class(self, m):
class CustomClientResponse(ClientResponse):
pass
m.get(self.url, body='Test', response_class=CustomClientResponse)
resp = await self.session.get(self.url)
self.assertTrue(isinstance(resp, CustomClientResponse))
@aioresponses()
def test_exceptions_in_the_middle_of_responses(self, mocked):
mocked.get(self.url, payload={}, status=204)
mocked.get(self.url, exception=ValueError('oops'), )
mocked.get(self.url, payload={}, status=204)
mocked.get(self.url, exception=ValueError('oops'), )
mocked.get(self.url, payload={}, status=200)
async def doit():
return (await self.session.get(self.url))
self.assertEqual(self.run_async(doit()).status, 204)
with self.assertRaises(ValueError):
self.run_async(doit())
self.assertEqual(self.run_async(doit()).status, 204)
with self.assertRaises(ValueError):
self.run_async(doit())
self.assertEqual(self.run_async(doit()).status, 200)
@aioresponses()
async def test_request_should_match_regexp(self, mocked):
mocked.get(
re.compile(r'^http://example\.com/api\?foo=.*$'),
payload={}, status=200
)
response = await self.request(self.url)
self.assertEqual(response.status, 200)
@aioresponses()
async def test_request_does_not_match_regexp(self, mocked):
mocked.get(
re.compile(r'^http://exampleexample\.com/api\?foo=.*$'),
payload={}, status=200
)
with self.assertRaises(ClientConnectionError):
await self.request(self.url)
@aioresponses()
def test_timeout(self, mocked):
mocked.get(self.url, timeout=True)
with self.assertRaises(asyncio.TimeoutError):
self.run_async(self.request(self.url))
@aioresponses()
def test_callback(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)
m.get(self.url, callback=callback)
response = self.run_async(self.request(self.url))
data = self.run_async(response.read())
assert data == body
@aioresponses()
def test_callback_coroutine(self, m):
body = b'New body'
event = asyncio.Event()
async def callback(url, **kwargs):
await event.wait()
self.assertEqual(str(url), self.url)
self.assertEqual(kwargs, {'allow_redirects': True})
return CallbackResult(body=body)
m.get(self.url, callback=callback)
future = asyncio.ensure_future(self.request(self.url))
self.run_async(asyncio.wait([future], timeout=0))
assert not future.done()
event.set()
self.run_async(asyncio.wait([future], timeout=0))
assert future.done()
response = future.result()
data = self.run_async(response.read())
assert data == body
@aioresponses()
async def test_exception_requests_are_tracked(self, mocked):
kwargs = {"json": [42], "allow_redirects": True}
mocked.get(self.url, exception=ValueError('oops'))
with self.assertRaises(ValueError):
await self.session.get(self.url, **kwargs)
key = ('GET', URL(self.url))
mocked_requests = mocked.requests[key]
self.assertEqual(len(mocked_requests), 1)
request = mocked_requests[0]
self.assertEqual(request.args, ())
self.assertEqual(request.kwargs, kwargs)
async def test_possible_race_condition(self):
async def random_sleep_cb(url, **kwargs):
await asyncio.sleep(uniform(0.1, 1))
return CallbackResult(body='test')
with aioresponses() as mocked:
for i in range(20):
mocked.get(
'http://example.org/id-{}'.format(i),
callback=random_sleep_cb
)
tasks = [
self.session.get('http://example.org/id-{}'.format(i)) for
i in range(20)
]
await asyncio.gather(*tasks)
class AIOResponsesRaiseForStatusSessionTestCase(AsyncTestCase):
"""Test case for sessions with raise_for_status=True.
This flag, introduced in aiohttp v2.0.0, automatically calls
`raise_for_status()`.
It is overridden by the `raise_for_status` argument of the request since
aiohttp v3.4.a0.
"""
async def setup(self):
self.url = 'http://example.com/api?foo=bar#fragment'
self.session = ClientSession(raise_for_status=True)
async def teardown(self):
close_result = self.session.close()
if close_result is not None:
await close_result
@aioresponses()
async def test_raise_for_status(self, m):
m.get(self.url, status=400)
with self.assertRaises(ClientResponseError) as cm:
await self.session.get(self.url)
self.assertEqual(cm.exception.message, http.RESPONSES[400][0])
@aioresponses()
@skipIf(condition=AIOHTTP_VERSION < parse_version('3.4.0'),
reason='aiohttp<3.4.0 does not support raise_for_status '
'arguments for requests')
async def test_do_not_raise_for_status(self, m):
m.get(self.url, status=400)
response = await self.session.get(self.url,
raise_for_status=False)
self.assertEqual(response.status, 400)
class AIOResponseRedirectTest(AsyncTestCase):
async def setup(self):
self.url = "http://10.1.1.1:8080/redirect"
self.session = ClientSession()
async def teardown(self):
close_result = self.session.close()
if close_result is not None:
await close_result
@aioresponses()
async def test_redirect_followed(self, rsps):
rsps.get(
self.url,
status=307,
headers={"Location": "https://httpbin.org"},
)
rsps.get("https://httpbin.org")
response = await self.session.get(
self.url, allow_redirects=True
)
self.assertEqual(response.status, 200)
self.assertEqual(str(response.url), "https://httpbin.org")
self.assertEqual(len(response.history), 1)
self.assertEqual(str(response.history[0].url), self.url)
@aioresponses()
async def test_post_redirect_followed(self, rsps):
rsps.post(
self.url,
status=307,
headers={"Location": "https://httpbin.org"},
)
rsps.get("https://httpbin.org")
response = await self.session.post(
self.url, allow_redirects=True
)
self.assertEqual(response.status, 200)
self.assertEqual(str(response.url), "https://httpbin.org")
self.assertEqual(response.method, "get")
self.assertEqual(len(response.history), 1)
self.assertEqual(str(response.history[0].url), self.url)
@aioresponses()
async def test_redirect_missing_mocked_match(self, rsps):
rsps.get(
self.url,
status=307,
headers={"Location": "https://httpbin.org"},
)
with self.assertRaises(ClientConnectionError) as cm:
await self.session.get(
self.url, allow_redirects=True
)
self.assertEqual(
str(cm.exception),
'Connection refused: GET http://10.1.1.1:8080/redirect'
)
@aioresponses()
async def test_redirect_missing_location_header(self, rsps):
rsps.get(self.url, status=307)
response = await self.session.get(self.url, allow_redirects=True)
self.assertEqual(str(response.url), self.url)
@aioresponses()
@skipIf(condition=AIOHTTP_VERSION < parse_version('3.1.0'),
reason='aiohttp<3.1.0 does not add request info on response')
async def test_request_info(self, rsps):
rsps.get(self.url, status=200)
response = await self.session.get(self.url)
request_info = response.request_info
assert str(request_info.url) == self.url
assert request_info.headers == {}
@aioresponses()
@skipIf(condition=AIOHTTP_VERSION < parse_version('3.1.0'),
reason='aiohttp<3.1.0 does not add request info on response')
async def test_request_info_with_original_request_headers(self, rsps):
headers = {"Authorization": "Bearer access-token"}
rsps.get(self.url, status=200)
response = await self.session.get(self.url, headers=headers)
request_info = response.request_info
assert str(request_info.url) == self.url
assert request_info.headers == headers
aioresponses-0.7.3/tests/test_compat.py 0000664 0000000 0000000 00000003051 14167132246 0020276 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
from typing import Union
from unittest import TestCase
from ddt import ddt, data
from yarl import URL
from aioresponses.compat import merge_params
def get_url(url: str, as_str: bool) -> Union[URL, str]:
return url if as_str else URL(url)
@ddt
class CompatTestCase(TestCase):
use_default_loop = False
def setUp(self):
self.url_with_parameters = 'http://example.com/api?foo=bar#fragment'
self.url_without_parameters = 'http://example.com/api?#fragment'
@data(True, False)
def test_no_params_returns_same_url__as_str(self, as_str):
url = get_url(self.url_with_parameters, as_str)
self.assertEqual(
merge_params(url, None), URL(self.url_with_parameters)
)
@data(True, False)
def test_empty_params_returns_same_url__as_str(self, as_str):
url = get_url(self.url_with_parameters, as_str)
self.assertEqual(merge_params(url, {}), URL(self.url_with_parameters))
@data(True, False)
def test_both_with_params_returns_corrected_url__as_str(self, as_str):
url = get_url(self.url_with_parameters, as_str)
self.assertEqual(
merge_params(url, {'x': 42}),
URL('http://example.com/api?foo=bar&x=42#fragment'),
)
@data(True, False)
def test_base_without_params_returns_corrected_url__as_str(self, as_str):
expected_url = URL('http://example.com/api?x=42#fragment')
url = get_url(self.url_without_parameters, as_str)
self.assertEqual(merge_params(url, {'x': 42}), expected_url)
aioresponses-0.7.3/tox.ini 0000664 0000000 0000000 00000001661 14167132246 0015560 0 ustar 00root root 0000000 0000000 [tox]
envlist =
flake8,
coverage,
py3.6-aiohttp{30,31,32,33,34,35,36,37}
py3.7-aiohttp{33,34,35,36,37}
py3.8-aiohttp{33,34,35,36,37}
py3.9-aiohttp{37}
skipsdist = True
[testenv:flake8]
deps = flake8
commands = flake8 aioresponses
[testenv]
setenv =
PYTHONDONTWRITEBYTECODE=1
PYTHONPATH = {toxinidir}:{toxinidir}/aioresponses
passenv = PYTEST_ADDOPTS
deps =
aiohttp20: aiohttp>=2.0,<2.1
aiohttp20: yarl<1.2.0
aiohttp21: aiohttp>=2.1,<2.2
aiohttp21: yarl<1.2.0
aiohttp22: aiohttp>=2.2,<2.3
aiohttp22: yarl<1.2.0
aiohttp23: aiohttp>=2.3,<2.4
aiohttp30: aiohttp>=3.0,<3.1
aiohttp31: aiohttp>=3.1,<3.2
aiohttp32: aiohttp>=3.2,<3.3
aiohttp33: aiohttp>=3.3,<3.4
aiohttp34: aiohttp>=3.4,<3.5
aiohttp35: aiohttp>=3.5,<3.6
aiohttp36: aiohttp>=3.6,<3.7
aiohttp37: aiohttp>=3.7,<3.8
-r{toxinidir}/requirements-dev.txt
commands = python -m pytest {posargs}
aioresponses-0.7.3/unittest.cfg 0000664 0000000 0000000 00000000223 14167132246 0016576 0 ustar 00root root 0000000 0000000 [unittest]
plugins=nose2.plugins.junitxml
[coverage]
always-on = True
coverage-report = html,xml
[junit-xml]
always-on = True
path=nosetests.xml