pax_global_header00006660000000000000000000000064136206176270014524gustar00rootroot0000000000000052 comment=e6e3e84dd666f87a07f4d0267ea2e1a39faae952 aioresponses-0.6.3/000077500000000000000000000000001362061762700142445ustar00rootroot00000000000000aioresponses-0.6.3/.coveragerc000066400000000000000000000001241362061762700163620ustar00rootroot00000000000000[run] source = aioresponses [report] omit = /usr*,setup.py,*egg*,.venv/*,*/tests/* aioresponses-0.6.3/.gitignore000066400000000000000000000020561362061762700162370ustar00rootroot00000000000000# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python env/ build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ *.egg-info/ .installed.cfg *.egg # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *,cover .hypothesis/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder target/ # IPython Notebook .ipynb_checkpoints # pyenv .python-version # celery beat schedule file celerybeat-schedule # dotenv .env # virtualenv venv/ ENV/ # Spyder project settings .spyderproject # Rope project settings .ropeproject *.idea/* .envrc .direnv aioresponses-0.6.3/.landscape.yml000066400000000000000000000000251362061762700167740ustar00rootroot00000000000000python-targets: - 3aioresponses-0.6.3/.pyup.yml000066400000000000000000000002061362061762700160400ustar00rootroot00000000000000label_prs: update requirements: - requirements.txt: pin: False - requirements-dev.txt: update: False pin: Falseaioresponses-0.6.3/.travis.yml000066400000000000000000000040141362061762700163540ustar00rootroot00000000000000# Config file for automatic testing at travis-ci.org # This file will be regenerated if you run travis_pypi_setup.py language: python matrix: include: - python: 3.5 env: TOXENV=py35-aiohttp20 - python: 3.5 env: TOXENV=py35-aiohttp21 - python: 3.5 env: TOXENV=py35-aiohttp22 - python: 3.5 env: TOXENV=py35-aiohttp23 - python: 3.5 env: TOXENV=py35-aiohttp30 - python: 3.5 env: TOXENV=py35-aiohttp31 - python: 3.5 env: TOXENV=py35-aiohttp32 - python: 3.5 env: TOXENV=py35-aiohttp33 - python: 3.5 env: TOXENV=py35-aiohttp34 - python: 3.5 env: TOXENV=py35-aiohttp35 - python: 3.5 env: TOXENV=py35-aiohttp36 - python: 3.6 env: TOXENV=py36-aiohttp20 - python: 3.6 env: TOXENV=py36-aiohttp21 - python: 3.6 env: TOXENV=py36-aiohttp22 - python: 3.6 env: TOXENV=py36-aiohttp23 - python: 3.6 env: TOXENV=py36-aiohttp30 - python: 3.6 env: TOXENV=py36-aiohttp31 - python: 3.6 env: TOXENV=py36-aiohttp32 - python: 3.6 env: TOXENV=py36-aiohttp33 - python: 3.6 env: TOXENV=py36-aiohttp34 - python: 3.6 env: TOXENV=py36-aiohttp35 - python: 3.6 env: TOXENV=py36-aiohttp36 - python: 3.7 dist: xenial env: TOXENV=py37-aiohttp33 - python: 3.7 dist: xenial env: TOXENV=py37-aiohttp34 - python: 3.7 dist: xenial env: TOXENV=py37-aiohttp35 - python: 3.7 dist: xenial env: TOXENV=py37-aiohttp36 - python: 3.8 dist: xenial env: TOXENV=py38-aiohttp33 - python: 3.8 dist: xenial env: TOXENV=py38-aiohttp34 - python: 3.8 dist: xenial env: TOXENV=py38-aiohttp35 - python: 3.8 dist: xenial env: TOXENV=py38-aiohttp36 # - python: 3.8 # dist: xenial # env: TOXENV=py38-aiohttp-master - python: 3.8 dist: xenial env: TOXENV=flake8 env: global: - PYTEST_ADDOPTS="--cov --cov-report=xml" install: pip install -U tox after_success: - bash <(curl -s https://codecov.io/bash) -Z -X coveragepy -X gcov -X xcode -f coverage.xml script: tox -e ${TOXENV} aioresponses-0.6.3/AUTHORS.rst000066400000000000000000000002421362061762700161210ustar00rootroot00000000000000======= Credits ======= Development Lead ---------------- * Pawel Nuckowski Contributors ------------ None yet. Why not be the first? aioresponses-0.6.3/CONTRIBUTING.rst000066400000000000000000000063131362061762700167100ustar00rootroot00000000000000.. 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.6.3/HISTORY.rst000066400000000000000000000001211362061762700161310ustar00rootroot00000000000000======= History ======= 0.1.0 (2016-10-17) ------------------ * initial commit aioresponses-0.6.3/LICENSE000066400000000000000000000020531362061762700152510ustar00rootroot00000000000000MIT 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.6.3/MANIFEST.in000066400000000000000000000004101362061762700157750ustar00rootroot00000000000000 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.6.3/Makefile000066400000000000000000000044101362061762700157030ustar00rootroot00000000000000.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 -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.6.3/README.rst000066400000000000000000000154431362061762700157420ustar00rootroot00000000000000=============================== 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.6.3/aioresponses/000077500000000000000000000000001362061762700167565ustar00rootroot00000000000000aioresponses-0.6.3/aioresponses/__init__.py000066400000000000000000000002271362061762700210700ustar00rootroot00000000000000# -*- coding: utf-8 -*- from .core import CallbackResult, aioresponses __version__ = '0.6.3' __all__ = [ 'CallbackResult', 'aioresponses', ] aioresponses-0.6.3/aioresponses/compat.py000066400000000000000000000026661362061762700206250ustar00rootroot00000000000000# -*- coding: utf-8 -*- import asyncio # noqa: F401 import sys from distutils.version import StrictVersion 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 yarl import URL if sys.version_info < (3, 7): from re import _pattern_type as Pattern else: from re import Pattern AIOHTTP_VERSION = StrictVersion(aiohttp_version) if AIOHTTP_VERSION >= StrictVersion('3.0.0'): from aiohttp.client_proto import ResponseHandler def stream_reader_factory( loop: 'Optional[asyncio.AbstractEventLoop]' = None ): protocol = ResponseHandler(loop=loop) return StreamReader(protocol, 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)))) __all__ = [ 'URL', 'Pattern', 'AIOHTTP_VERSION', 'merge_params', 'stream_reader_factory', 'normalize_url', ] aioresponses-0.6.3/aioresponses/core.py000066400000000000000000000323441362061762700202660ustar00rootroot00000000000000# -*- coding: utf-8 -*- import asyncio import json import copy from collections import namedtuple from distutils.version import StrictVersion from functools import wraps from typing import Callable, Dict, Tuple, Union, Optional, List # noqa from unittest.mock import Mock, patch from aiohttp import ( ClientConnectionError, ClientResponse, ClientSession, hdrs, http ) from aiohttp.helpers import TimerNoop from multidict import CIMultiDict, CIMultiDictProxy from .compat import ( AIOHTTP_VERSION, URL, Pattern, stream_reader_factory, merge_params, normalize_url, ) class CallbackResult: def __init__(self, method: str = hdrs.METH_GET, status: int = 200, body: str = '', 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: str = '', 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: str = '', 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 >= StrictVersion('3.1.0'): loop = Mock() loop.get_debug = Mock() loop.get_debug.return_value = True kwargs['request_info'] = Mock( url=url, method=method, headers=CIMultiDictProxy(CIMultiDict(**request_headers)), ) kwargs['writer'] = Mock() kwargs['continue100'] = None kwargs['timer'] = TimerNoop() if AIOHTTP_VERSION < StrictVersion('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) if AIOHTTP_VERSION >= StrictVersion('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: Dict ) -> 'Union[ClientResponse, Exception]': if isinstance(self.exception, Exception): return self.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 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: List[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: str = '', 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.append(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, )) async def match( self, method: str, url: URL, allow_redirects: bool = True, **kwargs: Dict ) -> Optional['ClientResponse']: history = [] while True: for i, matcher in enumerate(self._matches): if matcher.match(method, url): response = await matcher.build_response( url, allow_redirects=allow_redirects, **kwargs ) break else: return None if matcher.repeat is False: del self._matches[i] if isinstance(response, Exception): raise response if response.status in ( 301, 302, 303, 307, 308) and allow_redirects: if hdrs.LOCATION not in response.headers: break history.append(response) url = URL(response.headers[hdrs.LOCATION]) continue else: break response._history = tuple(history) return response 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 = 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, *args, **kwargs )) key = (method, url) self.requests.setdefault(key, []) try: kwargs_copy = copy.deepcopy(kwargs) except TypeError: # 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.6.3/docs/000077500000000000000000000000001362061762700151745ustar00rootroot00000000000000aioresponses-0.6.3/docs/Makefile000066400000000000000000000152021362061762700166340ustar00rootroot00000000000000# 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.6.3/docs/aioresponses.rst000066400000000000000000000005111362061762700204350ustar00rootroot00000000000000aioresponses package ==================== Submodules ---------- aioresponses.core module ------------------------ .. automodule:: aioresponses.core :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: aioresponses :members: :undoc-members: :show-inheritance: aioresponses-0.6.3/docs/authors.rst000066400000000000000000000000341362061762700174100ustar00rootroot00000000000000.. include:: ../AUTHORS.rst aioresponses-0.6.3/docs/conf.py000077500000000000000000000204201362061762700164740ustar00rootroot00000000000000#!/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.6.3/docs/contributing.rst000066400000000000000000000000411362061762700204300ustar00rootroot00000000000000.. include:: ../CONTRIBUTING.rst aioresponses-0.6.3/docs/history.rst000066400000000000000000000000341362061762700174240ustar00rootroot00000000000000.. include:: ../HISTORY.rst aioresponses-0.6.3/docs/index.rst000066400000000000000000000007721362061762700170430ustar00rootroot00000000000000.. 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.6.3/docs/installation.rst000066400000000000000000000022131362061762700204250ustar00rootroot00000000000000.. 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.6.3/docs/make.bat000066400000000000000000000145071362061762700166100ustar00rootroot00000000000000@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.6.3/docs/modules.rst000066400000000000000000000001111362061762700173670ustar00rootroot00000000000000aioresponses ============ .. toctree:: :maxdepth: 4 aioresponses aioresponses-0.6.3/docs/readme.rst000066400000000000000000000000331362061762700171570ustar00rootroot00000000000000.. include:: ../README.rst aioresponses-0.6.3/docs/usage.rst000066400000000000000000000001171362061762700170310ustar00rootroot00000000000000===== Usage ===== To use aioresponses in a project:: import aioresponses aioresponses-0.6.3/requirements-dev.txt000066400000000000000000000002301362061762700202770ustar00rootroot00000000000000pip wheel flake8==3.5.0 tox==3.4.0 coverage==4.5.1 Sphinx==1.5.6 pytest==3.8.1 pytest-cov==2.6.0 pytest-html==1.19.0 ddt==1.2.0 typing asynctest==0.12.2aioresponses-0.6.3/requirements.txt000066400000000000000000000000261362061762700175260ustar00rootroot00000000000000aiohttp>=2.0.0,<4.0.0 aioresponses-0.6.3/setup.cfg000066400000000000000000000015011362061762700160620ustar00rootroot00000000000000[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 :: 3 - Alpha Intended Audience :: Developers Topic :: Internet :: WWW/HTTP Topic :: Software Development :: Testing License :: OSI Approved :: MIT License Natural Language :: English Programming Language :: Python :: 3 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Programming Language :: Python :: 3.7 [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.6.3/setup.py000066400000000000000000000001471362061762700157600ustar00rootroot00000000000000#!/usr/bin/env python import setuptools setuptools.setup( setup_requires=['pbr'], pbr=True, ) aioresponses-0.6.3/tests/000077500000000000000000000000001362061762700154065ustar00rootroot00000000000000aioresponses-0.6.3/tests/__init__.py000066400000000000000000000000001362061762700175050ustar00rootroot00000000000000aioresponses-0.6.3/tests/test_aioresponses.py000066400000000000000000000475451362061762700215500ustar00rootroot00000000000000# -*- coding: utf-8 -*- import asyncio import re 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 asynctest import fail_on, skipIf from asynctest.case import TestCase from ddt import ddt, data 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 @ddt class AIOResponsesTestCase(TestCase): use_default_loop = False @asyncio.coroutine def setUp(self): self.url = 'http://example.com/api?foo=bar#fragment' self.session = ClientSession() super().setUp() @asyncio.coroutine def tearDown(self): close_result = self.session.close() if close_result is not None: yield from close_result super().tearDown() def run_async(self, coroutine: Union[Coroutine, Generator]): return self.loop.run_until_complete(coroutine) @asyncio.coroutine def request(self, url: str): return (yield from 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() @asyncio.coroutine def test_returned_instance_and_status_code(self, m): m.get(self.url, status=204) response = yield from self.session.get(self.url) self.assertIsInstance(response, ClientResponse) self.assertEqual(response.status, 204) @aioresponses() @asyncio.coroutine def test_returned_response_headers(self, m): m.get(self.url, content_type='text/html', headers={'Connection': 'keep-alive'}) response = yield from self.session.get(self.url) self.assertEqual(response.headers['Connection'], 'keep-alive') self.assertEqual(response.headers[hdrs.CONTENT_TYPE], 'text/html') @aioresponses() @asyncio.coroutine def test_returned_response_raw_headers(self, m): m.get(self.url, content_type='text/html', headers={'Connection': 'keep-alive'}) response = yield from 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() @asyncio.coroutine def test_raise_for_status(self, m): m.get(self.url, status=400) with self.assertRaises(ClientResponseError) as cm: response = yield from self.session.get(self.url) response.raise_for_status() self.assertEqual(cm.exception.message, http.RESPONSES[400][0]) @aioresponses() @asyncio.coroutine @skipIf(condition=AIOHTTP_VERSION < '3.4.0', reason='aiohttp<3.4.0 does not support raise_for_status ' 'arguments for requests') def test_request_raise_for_status(self, m): m.get(self.url, status=400) with self.assertRaises(ClientResponseError) as cm: yield from self.session.get(self.url, raise_for_status=True) self.assertEqual(cm.exception.message, http.RESPONSES[400][0]) @aioresponses() @asyncio.coroutine 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 = yield from 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 = yield from 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() @asyncio.coroutine def test_streaming(self, m): m.get(self.url, body='Test') resp = yield from self.session.get(self.url) content = yield from resp.content.read() self.assertEqual(content, b'Test') @aioresponses() @asyncio.coroutine def test_streaming_up_to(self, m): m.get(self.url, body='Test') resp = yield from self.session.get(self.url) content = yield from resp.content.read(2) self.assertEqual(content, b'Te') content = yield from resp.content.read(2) self.assertEqual(content, b'st') @asyncio.coroutine def test_mocking_as_context_manager(self): with aioresponses() as aiomock: aiomock.add(self.url, payload={'foo': 'bar'}) resp = yield from self.session.get(self.url) self.assertEqual(resp.status, 200) payload = yield from 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) @asyncio.coroutine def test_passing_argument(self): @aioresponses(param='mocked') @asyncio.coroutine def foo(mocked): mocked.add(self.url, payload={'foo': 'bar'}) resp = yield from self.session.get(self.url) self.assertEqual(resp.status, 200) yield from 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)) @asyncio.coroutine def test_unknown_request(self): with aioresponses() as aiomock: aiomock.add(self.url, payload={'foo': 'bar'}) with self.assertRaises(ClientConnectionError): yield from self.session.get('http://example.com/foo') @asyncio.coroutine def test_raising_custom_error(self): with aioresponses() as aiomock: aiomock.get(self.url, exception=HttpProcessingError(message='foo')) with self.assertRaises(HttpProcessingError): yield from self.session.get(self.url) @asyncio.coroutine 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 = yield from self.session.get( self.url, json=json_content_as_ref ) self.assertEqual(resp.status, 200) json_content_as_ref[:] = [2] resp = yield from self.session.get( self.url, json=json_content_as_ref ) self.assertEqual(resp.status, 201) json_content_as_ref[:] = [3] resp = yield from 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]}) @asyncio.coroutine 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 = yield from 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}) @asyncio.coroutine def test_request_retrieval_in_case_no_response(self): with aioresponses() as m: with self.assertRaises(ClientConnectionError): yield from 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}) @asyncio.coroutine def test_request_failure_in_case_session_is_closed(self): @asyncio.coroutine def do_request(session): return (yield from session.get(self.url)) with aioresponses(): coro = do_request(self.session) yield from self.session.close() with self.assertRaises(RuntimeError) as exception_info: yield from coro assert str(exception_info.exception) == "Session is closed" @asyncio.coroutine def test_address_as_instance_of_url_combined_with_pass_through(self): external_api = 'http://httpbin.org/status/201' @asyncio.coroutine def doit(): api_resp = yield from self.session.get(self.url) # we have to hit actual url, # otherwise we do not test pass through option properly ext_rep = yield from 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 = yield from doit() self.assertEqual(api.status, 200) self.assertEqual(ext.status, 201) @aioresponses() @asyncio.coroutine def test_custom_response_class(self, m): class CustomClientResponse(ClientResponse): pass m.get(self.url, body='Test', response_class=CustomClientResponse) resp = yield from 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) @asyncio.coroutine def doit(): return (yield from 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() @asyncio.coroutine def test_request_should_match_regexp(self, mocked): mocked.get( re.compile(r'^http://example\.com/api\?foo=.*$'), payload={}, status=200 ) response = yield from self.request(self.url) self.assertEqual(response.status, 200) @aioresponses() @asyncio.coroutine 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): yield from 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() @asyncio.coroutine def callback(url, **kwargs): yield from 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() @asyncio.coroutine 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): yield from 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) class AIOResponsesRaiseForStatusSessionTestCase(TestCase): """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. """ use_default_loop = False @asyncio.coroutine def setUp(self): self.url = 'http://example.com/api?foo=bar#fragment' self.session = ClientSession(raise_for_status=True) super().setUp() @asyncio.coroutine def tearDown(self): close_result = self.session.close() if close_result is not None: yield from close_result super().tearDown() @aioresponses() @asyncio.coroutine def test_raise_for_status(self, m): m.get(self.url, status=400) with self.assertRaises(ClientResponseError) as cm: yield from self.session.get(self.url) self.assertEqual(cm.exception.message, http.RESPONSES[400][0]) @aioresponses() @asyncio.coroutine @skipIf(condition=AIOHTTP_VERSION < '3.4.0', reason='aiohttp<3.4.0 does not support raise_for_status ' 'arguments for requests') def test_do_not_raise_for_status(self, m): m.get(self.url, status=400) response = yield from self.session.get(self.url, raise_for_status=False) self.assertEqual(response.status, 400) class AIOResponseRedirectTest(TestCase): @asyncio.coroutine def setUp(self): self.url = "http://10.1.1.1:8080/redirect" self.session = ClientSession() super().setUp() @asyncio.coroutine def tearDown(self): close_result = self.session.close() if close_result is not None: yield from close_result super().tearDown() @aioresponses() @asyncio.coroutine def test_redirect_followed(self, rsps): rsps.get( self.url, status=307, headers={"Location": "https://httpbin.org"}, ) rsps.get("https://httpbin.org") response = yield from 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() @asyncio.coroutine 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: yield from self.session.get( self.url, allow_redirects=True ) self.assertEqual( str(cm.exception), 'Connection refused: GET http://10.1.1.1:8080/redirect' ) @aioresponses() @asyncio.coroutine def test_redirect_missing_location_header(self, rsps): rsps.get(self.url, status=307) response = yield from self.session.get(self.url, allow_redirects=True) self.assertEqual(str(response.url), self.url) @aioresponses() @asyncio.coroutine @skipIf(condition=AIOHTTP_VERSION < '3.1.0', reason='aiohttp<3.1.0 does not add request info on response') def test_request_info(self, rsps): rsps.get(self.url, status=200) response = yield from self.session.get(self.url) request_info = response.request_info assert str(request_info.url) == self.url assert request_info.headers == {} @aioresponses() @asyncio.coroutine @skipIf(condition=AIOHTTP_VERSION < '3.1.0', reason='aiohttp<3.1.0 does not add request info on response') def test_request_info_with_original_request_headers(self, rsps): headers = {"Authorization": "Bearer access-token"} rsps.get(self.url, status=200) response = yield from 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.6.3/tests/test_compat.py000066400000000000000000000030511362061762700203010ustar00rootroot00000000000000# -*- 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.6.3/tox.ini000066400000000000000000000021251362061762700155570ustar00rootroot00000000000000[tox] envlist = flake8, coverage, py35-aiohttp{20,21,22,23,30,31,32,33,34,35,36} py36-aiohttp-master py36-aiohttp{20,21,22,23,30,31,32,33,34,35,36} py37-aiohttp-master py37-aiohttp{30,31,32,33,34,35,36} py38-aiohttp-master py38-aiohttp{30,31,32,33,34,35,36} 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 aiohttp-master: https://github.com/aio-libs/aiohttp/archive/master.tar.gz -r{toxinidir}/requirements-dev.txt commands = python -m pytest {posargs} aioresponses-0.6.3/unittest.cfg000066400000000000000000000002231362061762700166010ustar00rootroot00000000000000[unittest] plugins=nose2.plugins.junitxml [coverage] always-on = True coverage-report = html,xml [junit-xml] always-on = True path=nosetests.xml