pax_global_header00006660000000000000000000000064144761044440014522gustar00rootroot0000000000000052 comment=74b6faf80a24af9c34dfab0e74379a5fec8fa980 pytest-aiohttp-1.0.5/000077500000000000000000000000001447610444400145235ustar00rootroot00000000000000pytest-aiohttp-1.0.5/.github/000077500000000000000000000000001447610444400160635ustar00rootroot00000000000000pytest-aiohttp-1.0.5/.github/workflows/000077500000000000000000000000001447610444400201205ustar00rootroot00000000000000pytest-aiohttp-1.0.5/.github/workflows/ci.yaml000066400000000000000000000040141447610444400213760ustar00rootroot00000000000000--- name: CI on: push: branches: [master] tags: [v*] pull_request: branches: [master] workflow_dispatch: jobs: lint: name: Run linters runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - name: Install check-wheel-content, pre-commit, and twine run: python -m pip install build pre-commit check-wheel-contents twine - name: Build package run: python -m build - name: Run linter run: python -m pre_commit run --all-files --show-diff-on-failure - name: Check wheel contents run: check-wheel-contents dist/*.whl - name: Check by twine run: python -m twine check dist/* test: strategy: matrix: python-version: ['3.7', '3.8', '3.9', '3.10'] runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install Python ${{ matrix.python-version }} dependencies run: | python -m pip install --upgrade pip pip install . - name: Run pytest run: pytest deploy: name: Deploy environment: release # Run only on pushing a tag if: github.event_name == 'push' && contains(github.ref, 'refs/tags/') needs: [lint, test] runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2.4.0 with: fetch-depth: 0 - name: Install build run: python -m pip install build pre-commit check-wheel-contents twine - name: Build package run: python -m build - name: PyPI upload uses: pypa/gh-action-pypi-publish@v1.5.0 with: packages_dir: dist password: ${{ secrets.PYPI_API_TOKEN }} - name: GitHub Release uses: ncipollo/release-action@v1 with: name: pytest-aiohttp ${{ github.ref_name }} artifacts: dist/* bodyFile: README.rst token: ${{ secrets.GITHUB_TOKEN }} pytest-aiohttp-1.0.5/.github/workflows/codeql.yml000066400000000000000000000014361447610444400221160ustar00rootroot00000000000000--- name: CodeQL on: push: branches: [master] pull_request: branches: [master] schedule: - cron: 30 13 * * 6 jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [python] steps: - name: Checkout uses: actions/checkout@v3 - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} queries: +security-and-quality - name: Autobuild uses: github/codeql-action/autobuild@v2 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 with: category: /language:${{ matrix.language }} pytest-aiohttp-1.0.5/.gitignore000066400000000000000000000021401447610444400165100ustar00rootroot00000000000000# 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 .python-version # generated by setuptools_scm pytest_aiohttp/_version.py pytest-aiohttp-1.0.5/.pre-commit-config.yaml000066400000000000000000000024071447610444400210070ustar00rootroot00000000000000--- repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: check-merge-conflict exclude: rst$ - repo: https://github.com/asottile/yesqa rev: v1.5.0 hooks: - id: yesqa - repo: https://github.com/Zac-HD/shed rev: 2023.6.1 # 0.7 does not support Python 3.7 hooks: - id: shed args: - --refactor types_or: - python - markdown - rst - repo: https://github.com/jumanjihouse/pre-commit-hook-yamlfmt rev: 0.2.3 hooks: - id: yamlfmt args: [--mapping, '2', --sequence, '2', --offset, '0'] - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: fix-encoding-pragma args: [--remove] - id: check-case-conflict - id: check-json - id: check-xml - id: check-yaml - id: debug-statements - repo: https://github.com/PyCQA/flake8 rev: 6.1.0 hooks: - id: flake8 language_version: python3 - repo: https://github.com/pre-commit/pygrep-hooks rev: v1.10.0 hooks: - id: python-use-type-annotations - repo: https://github.com/python-jsonschema/check-jsonschema rev: 0.26.3 hooks: - id: check-github-actions - id: check-github-workflows ci: skip: - check-github-actions - check-github-workflows pytest-aiohttp-1.0.5/CHANGES.rst000066400000000000000000000024261447610444400163310ustar00rootroot00000000000000CHANGES ======= 1.0.5 (2023-09-06) ------------------ - Fix some compatibility with Pytest 7. 1.0.4 (2022-02-12) ------------------ - Fix failure with ``aiohttp_client`` fixture usage when ``asyncio_mode=strict``. `#25 `_ 1.0.3 (2022-01-03) ------------------ - Fix ``loop`` and ``proactor_loop`` fixtures. `#22 `_ 1.0.2 (2022-01-20) ------------------ - Restore implicit switch to ``asyncio_mode = auto`` if *legacy* mode is detected. 1.0.1 (2022-01-20) ------------------ - Don't implicitly switch from legacy to auto asyncio_mode, the integration doesn't work well. 1.0.0 (2022-1-20) ------------------ - The plugin is compatible with ``pytest-asyncio`` now. It uses ``pytest-asyncio`` for async tests running and async fixtures support, providing by itself only fixtures for creating aiohttp test server and client. 0.2.0 (2017-11-30) ------------------ - Fix backward incompatibility changes introduced by `pytest` 3.3+ 0.1.3 (2016-09-08) ------------------ - Add MANIFEST.in file 0.1.2 (2016-08-07) ------------------ - Fix README markup 0.1.1 (2016-07-22) ------------------ - Fix an url in setup.py 0.1.0 (2016-07-22) ------------------ - Initial release pytest-aiohttp-1.0.5/LICENSE000066400000000000000000000261461447610444400155410ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2016-2018 Andrew Svetlov and aiohttp team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. pytest-aiohttp-1.0.5/MANIFEST.in000066400000000000000000000001411447610444400162550ustar00rootroot00000000000000grasp pytest_aiohttp include LICENSE include CHANGES.rst include README.rst global-exclude *.pyc pytest-aiohttp-1.0.5/README.rst000066400000000000000000000025221447610444400162130ustar00rootroot00000000000000pytest-aiohttp ============== pytest plugin for aiohttp support The library provides useful fixtures for creation test aiohttp server and client. Installation ------------ .. code-block:: console $ pip install pytest-aiohttp Add ``asyncio_mode = auto`` line to `pytest configuration `_ (see `pytest-asyncio modes `_ for details). The plugin works with ``strict`` mode also. Usage ----- Write tests in `pytest-asyncio `_ style using provided fixtures for aiohttp test server and client creation. The plugin provides resources cleanup out-of-the-box. The simple usage example: .. code-block:: python from aiohttp import web async def hello(request): return web.Response(body=b"Hello, world") def create_app(): app = web.Application() app.router.add_route("GET", "/", hello) return app async def test_hello(aiohttp_client): client = await aiohttp_client(create_app()) resp = await client.get("/") assert resp.status == 200 text = await resp.text() assert "Hello, world" in text See `aiohttp documentation ` for more details about fixtures usage. pytest-aiohttp-1.0.5/pyproject.toml000066400000000000000000000003041447610444400174340ustar00rootroot00000000000000[build-system] requires = [ "setuptools>=51.0", "wheel>=0.36", "setuptools_scm>=6.2" ] build-backend = "setuptools.build_meta" [tool.setuptools_scm] write_to = "pytest_aiohttp/_version.py" pytest-aiohttp-1.0.5/pytest_aiohttp/000077500000000000000000000000001447610444400176035ustar00rootroot00000000000000pytest-aiohttp-1.0.5/pytest_aiohttp/__init__.py000066400000000000000000000000651447610444400217150ustar00rootroot00000000000000from ._version import version as __version__ # noqa pytest-aiohttp-1.0.5/pytest_aiohttp/plugin.py000066400000000000000000000113721447610444400214570ustar00rootroot00000000000000import asyncio import warnings from typing import Any, Awaitable, Callable, Dict, Generator, Optional, Type, Union import pytest import pytest_asyncio from aiohttp.test_utils import BaseTestServer, RawTestServer, TestClient, TestServer from aiohttp.web import Application, BaseRequest, StreamResponse AiohttpClient = Callable[[Union[Application, BaseTestServer]], Awaitable[TestClient]] LEGACY_MODE = DeprecationWarning( "The 'asyncio_mode' is 'legacy', switching to 'auto' for the sake of " "pytest-aiohttp backward compatibility. " "Please explicitly use 'asyncio_mode=strict' or 'asyncio_mode=auto' " "in pytest configuration file." ) @pytest.hookimpl(tryfirst=True) def pytest_configure(config) -> None: val = config.getoption("asyncio_mode") if val is None: val = config.getini("asyncio_mode") if val == "legacy": config.option.asyncio_mode = "auto" config.issue_config_time_warning(LEGACY_MODE, stacklevel=2) @pytest.fixture def loop(event_loop: asyncio.AbstractEventLoop) -> asyncio.AbstractEventLoop: warnings.warn( "'loop' fixture is deprecated and scheduled for removal, " "please use 'event_loop' instead", DeprecationWarning, ) return event_loop @pytest.fixture def proactor_loop(event_loop: asyncio.AbstractEventLoop) -> asyncio.AbstractEventLoop: warnings.warn( "'proactor_loop' fixture is deprecated and scheduled for removal, " "please use 'event_loop' instead", DeprecationWarning, ) return event_loop @pytest.fixture def aiohttp_unused_port( unused_tcp_port_factory: Callable[[], int] ) -> Callable[[], int]: warnings.warn( "'aiohttp_unused_port' fixture is deprecated " "and scheduled for removal, " "please use 'unused_tcp_port_factory' instead", DeprecationWarning, ) return unused_tcp_port_factory @pytest_asyncio.fixture async def aiohttp_server() -> Callable[..., Awaitable[TestServer]]: """Factory to create a TestServer instance, given an app. aiohttp_server(app, **kwargs) """ servers = [] async def go( app: Application, *, port: Optional[int] = None, **kwargs: Any ) -> TestServer: server = TestServer(app, port=port) await server.start_server(**kwargs) servers.append(server) return server yield go while servers: await servers.pop().close() @pytest_asyncio.fixture async def aiohttp_raw_server() -> Callable[..., Awaitable[RawTestServer]]: """Factory to create a RawTestServer instance, given a web handler. aiohttp_raw_server(handler, **kwargs) """ servers = [] async def go( handler: Callable[[BaseRequest], Awaitable[StreamResponse]], *, port: Optional[int] = None, **kwargs: Any, ) -> RawTestServer: server = RawTestServer(handler, port=port) await server.start_server(**kwargs) servers.append(server) return server yield go while servers: await servers.pop().close() @pytest.fixture def aiohttp_client_cls() -> Type[TestClient]: """ Client class to use in ``aiohttp_client`` factory. Use it for passing custom ``TestClient`` implementations. Example:: class MyClient(TestClient): async def login(self, *, user, pw): payload = {"username": user, "password": pw} return await self.post("/login", json=payload) @pytest.fixture def aiohttp_client_cls(): return MyClient def test_login(aiohttp_client): app = web.Application() client = await aiohttp_client(app) await client.login(user="admin", pw="s3cr3t") """ return TestClient @pytest_asyncio.fixture async def aiohttp_client( aiohttp_client_cls: Type[TestClient], ) -> Generator[AiohttpClient, None, None]: """Factory to create a TestClient instance. aiohttp_client(app, **kwargs) aiohttp_client(server, **kwargs) aiohttp_client(raw_server, **kwargs) """ clients = [] async def go( __param: Union[Application, BaseTestServer], *, server_kwargs: Optional[Dict[str, Any]] = None, **kwargs: Any, ) -> TestClient: if isinstance(__param, Application): server_kwargs = server_kwargs or {} server = TestServer(__param, **server_kwargs) client = aiohttp_client_cls(server, **kwargs) elif isinstance(__param, BaseTestServer): client = aiohttp_client_cls(__param, **kwargs) else: raise ValueError("Unknown argument type: %r" % type(__param)) await client.start_server() clients.append(client) return client yield go while clients: await clients.pop().close() pytest-aiohttp-1.0.5/setup.cfg000066400000000000000000000030151447610444400163430ustar00rootroot00000000000000[metadata] name = pytest-aiohttp version = attr: pytest_aiohttp.__version__ url = https://github.com/aio-libs/pytest-aiohttp project_urls = GitHub = https://github.com/aio-libs/pytest-aiohttp Changelog = https://github.com/aio-libs/pytest-aiohttp/blob/master/CHANGES.rst description = Pytest plugin for aiohttp support long_description = file: README.rst long_description_content_type = text/x-rst maintainer = aiohttp team maintainer_email = team@aiohttp.org license = Apache 2.0 license_file = LICENSE classifiers = Development Status :: 4 - Beta Intended Audience :: Developers License :: OSI Approved :: Apache Software License Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Topic :: Software Development :: Testing Framework :: AsyncIO Framework :: Pytest Framework :: aiohttp Typing :: Typed [options] python_requires = >=3.7 packages = find: include_package_data = True setup_requires = setuptools_scm >= 6.2 install_requires = pytest >= 6.1.0 aiohttp >= 3.8.1 pytest-asyncio >= 0.17.2 [options.extras_require] testing = coverage == 6.2 mypy == 0.931 [options.entry_points] pytest11 = aiohttp = pytest_aiohttp.plugin [coverage:run] source = pytest_aiohttp branch = true [coverage:report] show_missing = true [tool:pytest] addopts = -rsx --tb=short testpaths = tests asyncio_mode = auto junit_family=xunit2 filterwarnings = error [flake8] max-line-length = 88 pytest-aiohttp-1.0.5/setup.py000066400000000000000000000000461447610444400162350ustar00rootroot00000000000000from setuptools import setup setup() pytest-aiohttp-1.0.5/tests/000077500000000000000000000000001447610444400156655ustar00rootroot00000000000000pytest-aiohttp-1.0.5/tests/test_fixtures.py000066400000000000000000000117561447610444400211610ustar00rootroot00000000000000from typing import Any pytest_plugins: str = "pytester" def test_aiohttp_plugin(testdir: Any) -> None: testdir.makepyfile( """\ import pytest from unittest import mock from aiohttp import web async def hello(request): return web.Response(body=b'Hello, world') async def create_app(): app = web.Application() app.router.add_route('GET', '/', hello) return app async def test_hello(aiohttp_client) -> None: client = await aiohttp_client(await create_app()) resp = await client.get('/') assert resp.status == 200 text = await resp.text() assert 'Hello, world' in text async def test_hello_from_app(aiohttp_client) -> None: app = web.Application() app.router.add_get('/', hello) client = await aiohttp_client(app) resp = await client.get('/') assert resp.status == 200 text = await resp.text() assert 'Hello, world' in text async def test_hello_with_loop(aiohttp_client) -> None: client = await aiohttp_client(await create_app()) resp = await client.get('/') assert resp.status == 200 text = await resp.text() assert 'Hello, world' in text async def test_noop() -> None: pass async def previous(request): if request.method == 'POST': with pytest.warns(DeprecationWarning): request.app['value'] = (await request.post())['value'] return web.Response(body=b'thanks for the data') else: v = request.app.get('value', 'unknown') return web.Response(body='value: {}'.format(v).encode()) def create_stateful_app(): app = web.Application() app.router.add_route('*', '/', previous) return app @pytest.fixture async def cli(aiohttp_client): return await aiohttp_client(create_stateful_app()) def test_noncoro() -> None: assert True async def test_failed_to_create_client(aiohttp_client) -> None: def make_app(): raise RuntimeError() with pytest.raises(RuntimeError): await aiohttp_client(make_app()) async def test_custom_port_aiohttp_client(aiohttp_client, unused_tcp_port): client = await aiohttp_client(await create_app(), server_kwargs={'port': unused_tcp_port}) assert client.port == unused_tcp_port resp = await client.get('/') assert resp.status == 200 text = await resp.text() assert 'Hello, world' in text async def test_custom_port_test_server(aiohttp_server, unused_tcp_port): app = await create_app() server = await aiohttp_server(app, port=unused_tcp_port) assert server.port == unused_tcp_port """ ) result = testdir.runpytest("--asyncio-mode=auto") result.assert_outcomes(passed=8) def test_aiohttp_raw_server(testdir: Any) -> None: testdir.makepyfile( """\ import pytest from aiohttp import web async def handler(request): return web.Response(text="OK") @pytest.fixture async def server(aiohttp_raw_server): return await aiohttp_raw_server(handler) @pytest.fixture async def cli(aiohttp_client, server): client = await aiohttp_client(server) return client async def test_hello(cli) -> None: resp = await cli.get('/') assert resp.status == 200 text = await resp.text() assert 'OK' in text """ ) result = testdir.runpytest("--asyncio-mode=auto") result.assert_outcomes(passed=1) def test_aiohttp_client_cls_fixture_custom_client_used(testdir: Any) -> None: testdir.makepyfile( """ import pytest from aiohttp.web import Application from aiohttp.test_utils import TestClient class CustomClient(TestClient): pass @pytest.fixture def aiohttp_client_cls(): return CustomClient async def test_hello(aiohttp_client) -> None: client = await aiohttp_client(Application()) assert isinstance(client, CustomClient) """ ) result = testdir.runpytest("--asyncio-mode=auto") result.assert_outcomes(passed=1) def test_aiohttp_client_cls_fixture_factory(testdir: Any) -> None: testdir.makeconftest( """\ def pytest_configure(config): config.addinivalue_line("markers", "rest: RESTful API tests") config.addinivalue_line("markers", "graphql: GraphQL API tests") """ ) testdir.makepyfile( """ import pytest from aiohttp.web import Application from aiohttp.test_utils import TestClient class RESTfulClient(TestClient): pass class GraphQLClient(TestClient): pass @pytest.fixture def aiohttp_client_cls(request): if request.node.get_closest_marker('rest') is not None: return RESTfulClient elif request.node.get_closest_marker('graphql') is not None: return GraphQLClient return TestClient @pytest.mark.rest async def test_rest(aiohttp_client) -> None: client = await aiohttp_client(Application()) assert isinstance(client, RESTfulClient) @pytest.mark.graphql async def test_graphql(aiohttp_client) -> None: client = await aiohttp_client(Application()) assert isinstance(client, GraphQLClient) """ ) result = testdir.runpytest("--asyncio-mode=auto") result.assert_outcomes(passed=2) pytest-aiohttp-1.0.5/tests/test_obsolete_fixtures.py000066400000000000000000000027101447610444400230430ustar00rootroot00000000000000from typing import Any pytest_plugins: str = "pytester" def test_loop_fixture(testdir: Any) -> None: testdir.makepyfile( """\ async def test_a(loop): pass """ ) result = testdir.runpytest_subprocess("--asyncio-mode=auto") result.assert_outcomes(passed=1) result.stdout.fnmatch_lines( [ "*DeprecationWarning: 'loop' fixture is deprecated " "and scheduled for removal, " "please use 'event_loop' instead*" ] ) def test_proactor_loop_fixture(testdir: Any) -> None: testdir.makepyfile( """\ async def test_a(proactor_loop): pass """ ) result = testdir.runpytest_subprocess("--asyncio-mode=auto") result.assert_outcomes(passed=1) result.stdout.fnmatch_lines( [ "*DeprecationWarning: 'proactor_loop' fixture is deprecated " "and scheduled for removal, " "please use 'event_loop' instead*" ] ) def test_aiohttp_unused_port(testdir: Any) -> None: testdir.makepyfile( """\ async def test_a(aiohttp_unused_port): aiohttp_unused_port() """ ) result = testdir.runpytest_subprocess("--asyncio-mode=auto") result.assert_outcomes(passed=1) result.stdout.fnmatch_lines( [ "*DeprecationWarning: 'aiohttp_unused_port' fixture is deprecated " "and scheduled for removal, " "please use 'unused_tcp_port_factory' instead*" ] ) pytest-aiohttp-1.0.5/tests/test_switch_mode.py000066400000000000000000000017761447610444400216160ustar00rootroot00000000000000from typing import Any from pytest_aiohttp.plugin import LEGACY_MODE pytest_plugins: str = "pytester" def test_warning_for_legacy_mode(testdir: Any) -> None: testdir.makepyfile( """\ async def test_a(): pass """ ) result = testdir.runpytest_subprocess("--asyncio-mode=legacy") result.assert_outcomes(passed=1) result.stdout.fnmatch_lines(["*" + str(LEGACY_MODE) + "*"]) def test_auto_mode(testdir: Any) -> None: testdir.makepyfile( """\ async def test_a(): pass """ ) result = testdir.runpytest_subprocess("--asyncio-mode=auto") result.assert_outcomes(passed=1) result.stdout.no_fnmatch_line("*" + str(LEGACY_MODE) + "*") def test_strict_mode(testdir: Any) -> None: testdir.makepyfile( """\ import pytest @pytest.mark.asyncio async def test_a(): pass """ ) result = testdir.runpytest_subprocess("--asyncio-mode=strict") result.assert_outcomes(passed=1) result.stdout.no_fnmatch_line("*" + str(LEGACY_MODE) + "*")