Pytest support for asyncio.

Overview

pytest-asyncio: pytest support for asyncio

https://travis-ci.org/pytest-dev/pytest-asyncio.svg?branch=master Supported Python versions

pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

@pytest.mark.asyncio
async def test_some_asyncio_code():
    res = await library.do_something()
    assert b'expected result' == res

pytest-asyncio has been strongly influenced by pytest-tornado.

Features

  • fixtures for creating and injecting versions of the asyncio event loop
  • fixtures for injecting unused tcp ports
  • pytest markers for treating tests as asyncio coroutines
  • easy testing with non-default event loops
  • support for async def fixtures and async generator fixtures

Installation

To install pytest-asyncio, simply:

$ pip install pytest-asyncio

This is enough for pytest to pick up pytest-asyncio.

Fixtures

event_loop

Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

def test_http_client(event_loop):
    url = 'http://httpbin.org/get'
    resp = event_loop.run_until_complete(http_client(url))
    assert b'HTTP/1.1 200 OK' in resp

This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

@pytest.fixture
def event_loop():
    loop = MyCustomLoop()
    yield loop
    loop.close()

If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

unused_tcp_port

Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

unused_tcp_port_factory

A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

def a_test(unused_tcp_port_factory):
    port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
    ...

Async fixtures

Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be coroutines or asynchronous generators.

@pytest.fixture
async def async_gen_fixture():
    await asyncio.sleep(0.1)
    yield 'a value'

@pytest.fixture(scope='module')
async def async_fixture():
    return await asyncio.sleep(0.1)

All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

Markers

pytest.mark.asyncio

Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

The event loop used can be overriden by overriding the event_loop fixture (see above).

In order to make your test code a little more concise, the pytest pytestmark feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

import asyncio
import pytest

# All test coroutines will be treated as marked.
pytestmark = pytest.mark.asyncio

async def test_example(event_loop):
    """No marker!"""
    await asyncio.sleep(0, loop=event_loop)

Changelog

0.15.0 (UNRELEASED)

  • Add support for Python 3.9
  • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
  • Set unused_tcp_port_factory fixture scope to 'session'. #163

0.14.0 (2020-06-24)

  • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

0.12.0 (2020-05-04)

  • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

0.11.0 (2020-04-20)

  • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
  • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
  • Better pytest.skip support. #126

0.10.0 (2019-01-08)

  • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
  • Pytest 4.1 support. #105

0.9.0 (2018-07-28)

  • Python 3.7 support.
  • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

0.8.0 (2017-09-23)

  • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

0.7.0 (2017-09-08)

0.6.0 (2017-05-28)

  • Support for Python versions pre-3.5 has been dropped.
  • pytestmark now works on both module and class level.
  • The forbid_global_loop parameter has been removed.
  • Support for async and async gen fixtures has been added. #45
  • The deprecation warning regarding asyncio.async() has been fixed. #51

0.5.0 (2016-09-07)

  • Introduced a changelog. #31
  • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
  • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

0.4.1 (2016-06-01)

  • Fix a bug preventing the propagation of exceptions from the plugin. #25

0.4.0 (2016-05-30)

  • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
  • Introduce the forbid_global_loop parameter. #21

0.3.0 (2015-12-19)

  • Support for Python 3.5 async/await syntax. #17

0.2.0 (2015-08-01)

  • unused_tcp_port_factory fixture. #10

0.1.1 (2015-04-23)

Initial release.

Contributing

Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

Comments
  • Error of

    Error of "attached to a different loop" appears in 0.11.0 but not in 0.10.0

    My testcase get the error of "attached to a different loop" in 0.11.0 but works fine in 0.10.0

    The detail is I have the following code in my testcase:

    asyncio.get_event_loop().run_in_executor(...)
    

    Is there any related change in 0.11.0?

    A simple testcase for reproducing:

    import asyncio
    import pytest
    
    @pytest.fixture(scope='function')
    async def loop():
        return asyncio.get_event_loop()
    
    def foo():
        return 0
    
    @pytest.mark.asyncio
    async def test_async(loop):
        await loop.run_in_executor(None, foo)
    
    opened by krizex 28
  • Automatically mark async test functions

    Automatically mark async test functions

    I have a test suite that uses pytest-asyncio for some of its tests and it works pretty well. Thank you for creating such a useful plugin.

    Enhancement Request

    All of my coroutine test functions are declared with async. To avoid marking every such function with @pytest.mark.asyncio, in the root conftest.py for that suite I have added the following pytest hook:

    import pytest
    import inspect
    
    def pytest_collection_modifyitems(session, config, items):
        for item in items:
            if isinstance(item, pytest.Function) and inspect.iscoroutinefunction(item.function):
                item.add_marker(pytest.mark.asyncio)
    

    So far I have not managed to find any drawback to doing this sort of thing - the async keyword indicates coroutine functions just as clearly as the decorator does, and this approach seems to correctly mark each async test.

    Could something like this be a part of pytest-asyncio itself, or is there a rationale for not including such a feature?

    I understand that this project existed before Python had async/await semantics; however, you appear to have dropped support for Python < 3.5 (#57), which means that every supported Python version also supports the async keyword. Furthermore, I am not suggesting the removal or deprecation of the decorator approach since there are probably valid use cases for creating coroutines without using async.

    If this kind of feature would be appreciated, I can contribute the changes myself when I can find the time.

    opened by lawsonjl 21
  • pytest fails while using version asyncio-0.15.0

    pytest fails while using version asyncio-0.15.0

    Python: 3.8 (docker image)

    My pytest setup:

    ...
    ============================= test session starts ==============================
    platform linux -- Python 3.8.9, pytest-6.2.3, py-1.10.0, pluggy-0.13.1 -- /builds/.../venv/bin/python3
    cachedir: .pytest_cache
    hypothesis profile 'default' -> database=DirectoryBasedExampleDatabase('/builds/.../.hypothesis/examples')
    rootdir: /builds/..., configfile: pytest.ini
    plugins: hypothesis-6.9.2, asyncio-0.15.0
    ...
    

    an error:

    ...
    ==================================== ERRORS ====================================
    _____________________ ERROR at setup of test_async_ticker ______________________
    
    fixturedef = <FixtureDef argname='event_loop' scope='function' baseid=''>
    request = <SubRequest 'event_loop' for <Function test_async_ticker>>
    
        @pytest.hookimpl(hookwrapper=True)
        def pytest_fixture_setup(fixturedef, request):
            """Adjust the event loop policy when an event loop is produced."""
            if fixturedef.argname == "event_loop":
                outcome = yield
                loop = outcome.get_result()
                policy = asyncio.get_event_loop_policy()
    >           old_loop = policy.get_event_loop()
    
    venv/lib/python3.8/site-packages/pytest_asyncio/plugin.py:94: 
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
    
    self = <asyncio.unix_events._UnixDefaultEventLoopPolicy object at 0x7f07326b2bb0>
    
        def get_event_loop(self):
            """Get the event loop for the current context.
        
            Returns an instance of EventLoop or raises an exception.
            """
            if (self._local._loop is None and
                    not self._local._set_called and
                    isinstance(threading.current_thread(), threading._MainThread)):
                self.set_event_loop(self.new_event_loop())
        
            if self._local._loop is None:
    >           raise RuntimeError('There is no current event loop in thread %r.'
                                   % threading.current_thread().name)
    E           RuntimeError: There is no current event loop in thread 'MainThread'.
    
    /usr/local/lib/python3.8/asyncio/events.py:639: RuntimeError
    ...
    

    The error appears when I run:

    python -m pytest tests/test_dates.py::test_async_ticker -vv -duration=6  
    

    where the test_async_ticker is:

    import asyncio
    
    import pytest
    
    @pytest.mark.asyncio
    async def test_async_ticker():
        async with dates.AsyncTicker() as ticker:
            await asyncio.sleep(0.001)
    
        assert ticker.time_elapsed().total_seconds() > 0
    

    and AsyncTicker:

    
    class AsyncTicker:
        '''Measures time between entering and exiting `async with` block.'''
        def __init__(self):
            self._start = None
            self._end = None
    
        async def __aenter__(self, *args, **kwargs):
            self._start = current_utc_instant()
            return self
    
        async def __aexit__(self, *args, **kwargs):
            self._end = current_utc_instant()
    
        def time_elapsed(self):
            return self._end - self._start
    
    opened by Kruszylo 20
  • Run tests asynchronously

    Run tests asynchronously

    Hi,

    I'm not sure this is the purpose of this library but I want to run pytest tests asynchronously.

    Consider this example:

    import asyncio
    import pytest
    
    
    @pytest.mark.asyncio
    async def test_1():
        await asyncio.sleep(2)
    
    
    @pytest.mark.asyncio
    async def test_2():
        await asyncio.sleep(2)
    
    $ py.test -q
    ..
    2 passed in 4.01 seconds
    

    It would be nice to run the test suite in ~2 seconds instead of 4. Is it currently possible with pytest-asyncio or with another library ? I guess we would need to asyncio.gather() all async tests and run them in the same event loop.

    Thanks !

    wontfix 
    opened by philpep 20
  • helping the maintenance bus factor

    helping the maintenance bus factor

    It seems that maintenance has come to a halt, in this issue i want to prepare communicating current factors and/or enable a call for help

    the goal being documenting the current state, so people have a idea what to expect while the shortage of committable volunteer time means less happens as well as organizing additional volunteers that can help the process.

    CC @pytest-dev/pytest-asyncio-admin

    enhancement help wanted 
    opened by RonnyPfannschmidt 19
  • Support for hypothesis in async methods

    Support for hypothesis in async methods

    hypothesis exits early when used on pytest-asyncio tests, complaining that the test returns a coroutine instead of None. This issue talks about how trio added support for hypothesis: https://github.com/HypothesisWorks/hypothesis/issues/968

    I can work around this with a decorator:

    def run_in_event_loop(async_func):
        @functools.wraps(async_func)
        def wrapped(operations, queue_size, add_size, get_size, event_loop):
            event_loop.run_until_complete(asyncio.ensure_future(
                async_func(operations, queue_size, add_size, get_size, event_loop),
                loop=event_loop,
            ))
        return wrapped
    
    @hypothesis.given(...)
    @run_in_event_loop
    @pytest.mark.asyncio
    async def test_...
    

    But it looks like the recommended approach is to tinker with the hypothesis attribute added to the test, like: https://github.com/python-trio/pytest-trio/pull/44/files#diff-aacce3c1178656a02aecc59c94209433R231

    Is this something pytest-asyncio is interested in supporting?

    enhancement 
    opened by carver 17
  • py.typed file is not included in v0.18.3 wheel

    py.typed file is not included in v0.18.3 wheel

    I just started getting complaints from CI about untyped decorators with @pytest_asyncio.fixture(). The py.typed file was not included in the v0.18.3 wheel released today. It does appear to be present in the v0.18.2 wheel as well as the v0.18.3 sdist.

    image

    I started looking around locally to try to figure it out but adding it to MANIFEST.in, trying old setuptools and build versions, passing --sdist --wheel to build... I haven't figured anything out quite yet.

    opened by altendky 14
  • Unable the use with unittest.TestCase

    Unable the use with unittest.TestCase

    I am trying to write a test with async code AND using the unittest.TestCase base class. When I use TestCase the test method always passes. What I am doing wrong?

    import pytest                                                                                  
    import unittest
    import aiohttp
    import asyncio
    
    URL = "http://www.github.com"
    
    
    class TestOnUnittestClass(unittest.TestCase):
    
        @pytest.mark.asyncio
        def test_get(self):
            req = (yield from aiohttp.request("GET", URL))
            assert req.status == 201
    
    class TestOnClass:
    
        @pytest.mark.asyncio
        def test_get(self):
            req = (yield from aiohttp.request("GET", URL))
            assert req.status == 201
    
    @pytest.mark.asyncio
    def test_async():
        req = (yield from aiohttp.request("GET", URL))
        assert req.status == 201
    

    The output is:

    $ py.test -vvvv async_on_class_test.py
    ===================================================================================== test session starts =====================================================================================
    platform linux -- Python 3.4.0 -- py-1.4.30 -- pytest-2.7.2 -- /home/paurullan/.virtualenvs/status/bin/python3
    rootdir: /home/paurullan/projects/status-qa, inifile: 
    plugins: asyncio, xdist, colordots
    collected 3 items 
    
    async_on_class_test.py::TestOnUnittestClass::test_get PASSED
    async_on_class_test.py::TestOnClass::test_get FAILED
    async_on_class_test.py::test_async FAILED
    
    ========================================================================================== FAILURES ===========================================================================================
    ____________________________________________________________________________________ TestOnClass.test_get _____________________________________________________________________________________
    
    self = <async_on_class_test.TestOnClass object at 0x7f70e6e3e898>
    
        @asyncio.coroutine
        @pytest.mark.asyncio
        def test_get(self):
            req = (yield from aiohttp.request("GET", URL))
    >       assert req.status == 201
    E       assert 200 == 201
    E        +  where 200 = <ClientResponse(https://github.com/) [200 OK]>\n<CIMultiDictProxy {'SERVER': 'GitHub.com', 'DATE': 'Tue, 11 Aug 2015 15...S': 'deny', 'VARY': 'Accept-Encoding', 'X-SERVED-BY': '53e13e5d66f560f3e2b04e74a099de0d', 'CONTENT-ENCODING': 'gzip'}>\n.status
    
    async_on_class_test.py:23: AssertionError
    _________________________________________________________________________________________ test_async __________________________________________________________________________________________
    
        @pytest.mark.asyncio
        def test_async():
            req = (yield from aiohttp.request("GET", URL))
    >       assert req.status == 201
    E       assert 200 == 201
    E        +  where 200 = <ClientResponse(https://github.com/) [200 OK]>\n<CIMultiDictProxy {'SERVER': 'GitHub.com', 'DATE': 'Tue, 11 Aug 2015 15...S': 'deny', 'VARY': 'Accept-Encoding', 'X-SERVED-BY': 'a128136e4734a9f74c013356c773ece7', 'CONTENT-ENCODING': 'gzip'}>\n.status
    
    async_on_class_test.py:28: AssertionError
    ============================================================================= 2 failed, 1 passed in 2.43 seconds ==============================================================================
    
    opened by paurullan 14
  • Release 0.14 breaks tests that rely on a specific event_loop_policy

    Release 0.14 breaks tests that rely on a specific event_loop_policy

    Problem

    We have many testcases that rely on asyncio.set_event_loop_policy(AnyThreadEventLoopPolicy()) We set the event loop policy in the conftest.py, such that it is set before any tests start.

    Since 0.14 these testcases produce errors

    RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-109_6'.
    

    Root cause

    The change here: https://github.com/pytest-dev/pytest-asyncio/pull/164/files#diff-4d85e8313d8e67cb777137411a11ac86R80

    Resets the event loop policy after the first test, breaking all the next tests.

    opened by wouterdb 13
  • v0.11 AttributeError: type object 'Function' has no attribute 'from_parent'

    v0.11 AttributeError: type object 'Function' has no attribute 'from_parent'

    my configuration is: platform linux -- Python 3.6.10, pytest-4.0.2, py-1.8.1, pluggy-0.13.1 plugins: asyncio-0.11.0, mock-3.1.0

    got me exception: _______ ERROR collecting ________ /usr/local/lib/python3.6/site-packages/pluggy/hooks.py:286: in call return self._hookexec(self, self.get_hookimpls(), kwargs) /usr/local/lib/python3.6/site-packages/pluggy/mantestos/allocator/tests/test_reload_machines.pyager.py:93: in _hookexec return self._inner_hookexec(hook, methods, kwargs) /usr/local/lib/python3.6/site-packages/pluggy/manager.py:87: in firstresult=hook.spec.opts.get("firstresult") if hook.spec else False, /usr/local/lib/python3.6/site-packages/_pytest/python.py:196: in pytest_pycollect_makeitem res = outcome.get_result() /usr/local/lib/python3.6/site-packages/pytest_asyncio/plugin.py:39: in pytest_pycollect_makeitem item = pytest.Function.from_parent(collector, name=name) E AttributeError: type object 'Function' has no attribute 'from_parent'

    going back to v0.10 the test pass.

    opened by yuval-lb 13
  • How to fix

    How to fix "attached to a different loop"?

    I have a very simple app called "myapp". It uses the AsyncElasticsearch client:

    from elasticsearch_async import AsyncElasticsearch
    
    def create_app():
        app = dict()
        app['es_client'] = AsyncElasticsearch('http://index:9200/')
        app['stuff'] = Stuff(app['es_client'])
        return app
    
    class Stuff:
        def __init__(self, es_client):
            self.es_client = es_client
    
        def do_async_stuff(self):
            return self.es_client.index(index='test',
                                        doc_type='test',
                                        body={'field': 'sample content'})
    

    My question is not about AsyncElasticsearch, it just happens to be an async thing I want to work with, could be sth else like a Mongo driver or whatever.

    I want to test do_async_stuff() and wrote the following conftest.py

    import pytest
    from myapp import create_app
    
    @pytest.fixture(scope='session')
    def app():
        return create_app()
    

    ... and test_stuff.py

    import pytest
    
    @pytest.mark.asyncio
    async def test_stuff(app):
        await app['stuff'].do_async_stuff()
        assert True
    

    When I execute the test I get an exception with the message "attached to a different loop". Digging into that matter I found that pytest-asyncio creates a new event_loop for each test case (right?). The Elasticsearch client however, takes the default loop on instantiation and sticks with it. So I tried to convince it to use the pytest-asyncio event_loop like so:

    import pytest
    
    @pytest.mark.asyncio
    async def test_stuff(app, event_loop):
        app['es_client'].transport.loop = event_loop
        await app['stuff'].do_async_stuff()
        assert True
    

    This however gives me another exception:

    __________________________________ test_stuff __________________________________
    
    app = {'es_client': <Elasticsearch([{'host': 'index', 'port': 9200, 'scheme': 'http'}])>, 'stuff': <myapp.Stuff object at 0x7ffbbaff1860>}
    
        @pytest.mark.asyncio
        async def test_stuff(app):
    >       await app['stuff'].do_async_stuff()
    
    test/test_stuff.py:6: 
    _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
    
    self = <Task pending coro=<AsyncTransport.main_loop() running at /usr/local/lib/python3.5/dist-packages/elasticsearch_async/transport.py:133>>
    
        def __iter__(self):
            if not self.done():
                self._blocking = True
    >           yield self  # This tells Task to wait for completion.
    E           RuntimeError: Task <Task pending coro=<test_stuff() running at /srv/app/backend/test/test_stuff.py:6> cb=[_run_until_complete_cb() at /usr/lib/python3.5/asyncio/base_events.py:164]> got Future <Task pending coro=<AsyncTransport.main_loop() running at /usr/local/lib/python3.5/dist-packages/elasticsearch_async/transport.py:133>> attached to a different loop
    

    How am I supposed to test this scenario?

    opened by Tim-Erwin 13
  • Build(deps): Bump exceptiongroup from 1.0.4 to 1.1.0 in /dependencies/default

    Build(deps): Bump exceptiongroup from 1.0.4 to 1.1.0 in /dependencies/default

    Bumps exceptiongroup from 1.0.4 to 1.1.0.

    Changelog

    Sourced from exceptiongroup's changelog.

    Version history

    This library adheres to Semantic Versioning 2.0 <http://semver.org/>_.

    1.1.0

    • Backported upstream fix for gh-99553 (custom subclasses of BaseExceptionGroup that also inherit from Exception should not be able to wrap base exceptions)
    • Moved all initialization code to __new__() (thus matching Python 3.11 behavior)

    1.0.4

    • Fixed regression introduced in v1.0.3 where the code computing the suggestions would assume that both the obj attribute of AttributeError is always available, even though this is only true from Python 3.10 onwards (#43; PR by Carl Friedrich Bolz-Tereick)

    1.0.3

    • Fixed monkey patching breaking suggestions (on a NameError or AttributeError) on Python 3.10 (#41; PR by Carl Friedrich Bolz-Tereick)

    1.0.2

    • Updated type annotations to match the ones in typeshed

    1.0.1

    • Fixed formatted traceback missing exceptions beyond 2 nesting levels of __context__ or __cause__

    1.0.0

    • Fixed AttributeError: 'PatchedTracebackException' object has no attribute '__cause__' on Python 3.10 (only) when a traceback is printed from an exception where an exception group is set as the cause (#33)
    • Fixed a loop in exception groups being rendered incorrectly (#35)
    • Fixed the patched formatting functions (format_exception()etc.) not passing the compact=True flag on Python 3.10 like the original functions do

    1.0.0rc9

    • Added custom versions of several traceback functions that work with exception groups even if monkey patching was disabled or blocked

    1.0.0rc8

    • Don't monkey patch anything if sys.excepthook has been altered

    ... (truncated)

    Commits
    • d6a0c30 Added the release version
    • a359629 Use new() only for initialization (#52)
    • 1bfa48a [pre-commit.ci] pre-commit autoupdate (#54)
    • 6e0f331 Backported upstream fix for gh-99553 (#51)
    • f32faa2 Added a better fix for the coveralls <-> coverage compatibility issue
    • 34bcf19 Worked around coveralls's allergy of coverage 7
    • a50b5d8 [pre-commit.ci] pre-commit autoupdate
    • 6abcee5 Updated tox configuration
    • 6ed0363 [pre-commit.ci] pre-commit autoupdate
    • 3fb346b [pre-commit.ci] pre-commit autoupdate (#47)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies python 
    opened by dependabot[bot] 0
  • Build(deps): Bump attrs from 22.1.0 to 22.2.0 in /dependencies/default

    Build(deps): Bump attrs from 22.1.0 to 22.2.0 in /dependencies/default

    Bumps attrs from 22.1.0 to 22.2.0.

    Release notes

    Sourced from attrs's releases.

    22.2.0

    Highlights

    It's been a lot busier than the changelog indicates, but a lot of the work happened under the hood (like some impressive performance improvements). But we've got still one big new feature that's are worthy the holidays:

    Fields now have an alias argument that allows you to set the field's name in the generated __init__ method. This is especially useful for those who aren't fans of attrs's behavior of stripping underscores from private attribute names.

    Special Thanks

    This release would not be possible without my generous sponsors! Thank you to all of you making sustainable maintenance possible! If you would like to join them, go to https://github.com/sponsors/hynek and check out the sweet perks!

    Above and Beyond

    Variomedia AG (@​variomedia), Tidelift (@​tidelift), Sentry (@​getsentry), HiredScore (@​HiredScore), FilePreviews (@​filepreviews), and Daniel Fortunov (@​asqui).

    Maintenance Sustainers

    @​rzijp, Adam Hill (@​adamghill), Dan Groshev (@​si14), Tamir Bahar (@​tmr232), Adi Roiban (@​adiroiban), Magnus Watn (@​magnuswatn), David Cramer (@​dcramer), Moving Content AG (@​moving-content), Stein Magnus Jodal (@​jodal), Iwan Aucamp (@​aucampia), ProteinQure (@​ProteinQure), Jesse Snyder (@​jessesnyder), Rivo Laks (@​rivol), Thomas Ballinger (@​thomasballinger), @​medecau, Ionel Cristian Mărieș (@​ionelmc), The Westervelt Company (@​westerveltco), Philippe Galvan (@​PhilippeGalvan), Birk Jernström (@​birkjernstrom), Jannis Leidel (@​jezdez), Tim Schilling (@​tim-schilling), Chris Withers (@​cjw296), and Christopher Dignam (@​chdsbd).

    Not to forget 2 more amazing humans who chose to be generous but anonymous!

    Full Changelog

    Backwards-incompatible Changes

    • Python 3.5 is not supported anymore. #988

    Deprecations

    • Python 3.6 is now deprecated and support will be removed in the next release. #1017

    Changes

    • attrs.field() now supports an alias option for explicit __init__ argument names.

      Get __init__ signatures matching any taste, peculiar or plain! The PEP 681 compatible alias option can be use to override private attribute name mangling, or add other arbitrary field argument name overrides. #950

    • attrs.NOTHING is now an enum value, making it possible to use with e.g. typing.Literal. #983

    • Added missing re-import of attr.AttrsInstance to the attrs namespace. #987

    • Fix slight performance regression in classes with custom __setattr__ and speedup even more. #991

    • Class-creation performance improvements by switching performance-sensitive templating operations to f-strings.

      You can expect an improvement of about 5% -- even for very simple classes. #995

    ... (truncated)

    Changelog

    Sourced from attrs's changelog.

    22.2.0 - 2022-12-21

    Backwards-incompatible Changes

    • Python 3.5 is not supported anymore. #988

    Deprecations

    • Python 3.6 is now deprecated and support will be removed in the next release. #1017

    Changes

    • attrs.field() now supports an alias option for explicit __init__ argument names.

      Get __init__ signatures matching any taste, peculiar or plain! The PEP 681 compatible alias option can be use to override private attribute name mangling, or add other arbitrary field argument name overrides. #950

    • attrs.NOTHING is now an enum value, making it possible to use with e.g. typing.Literal. #983

    • Added missing re-import of attr.AttrsInstance to the attrs namespace. #987

    • Fix slight performance regression in classes with custom __setattr__ and speedup even more. #991

    • Class-creation performance improvements by switching performance-sensitive templating operations to f-strings.

      You can expect an improvement of about 5% -- even for very simple classes. #995

    • attrs.has() is now a TypeGuard for AttrsInstance. That means that type checkers know a class is an instance of an attrs class if you check it using attrs.has() (or attr.has()) first. #997

    • Made attrs.AttrsInstance stub available at runtime and fixed type errors related to the usage of attrs.AttrsInstance in Pyright. #999

    • On Python 3.10 and later, call abc.update_abstractmethods() on dict classes after creation. This improves the detection of abstractness. #1001

    • attrs's pickling methods now use dicts instead of tuples. That is safer and more robust across different versions of a class. #1009

    • Added attrs.validators.not_(wrapped_validator) to logically invert wrapped_validator by accepting only values where wrapped_validator rejects the value with a ValueError or TypeError (by default, exception types configurable). #1010

    • The type stubs for attrs.cmp_using() now have default values. #1027

    • To conform with PEP 681, attr.s() and attrs.define() now accept unsafe_hash in addition to hash. #1065

    Commits
    • a9960de Prepare 22.2.0
    • 566248a Don't linkcheck tree links
    • 0f62805 Make towncrier marker independent from warning
    • b9f35eb Fix minor stub issues (#1072)
    • 4ad4ea0 Use MyST-native include
    • 519423d Use MyST-native doctest blocks in all MD
    • 403adab Remove stray file
    • 6957e4a Use new typographic branding in the last rst file, too
    • 1bb2864 Convert examples.rst to md
    • c1c24cc Convert glossary.rst to md
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies python 
    opened by dependabot[bot] 0
  • Build(deps): Bump coverage from 7.0.0 to 7.0.1 in /dependencies/default

    Build(deps): Bump coverage from 7.0.0 to 7.0.1 in /dependencies/default

    Bumps coverage from 7.0.0 to 7.0.1.

    Changelog

    Sourced from coverage's changelog.

    Version 7.0.1 — 2022-12-23

    • When checking if a file mapping resolved to a file that exists, we weren't considering files in .whl files. This is now fixed, closing issue 1511_.

    • File pattern rules were too strict, forbidding plus signs and curly braces in directory and file names. This is now fixed, closing issue 1513_.

    • Unusual Unicode or control characters in source files could prevent reporting. This is now fixed, closing issue 1512_.

    • The PyPy wheel now installs on PyPy 3.7, 3.8, and 3.9, closing issue 1510_.

    .. _issue 1510: nedbat/coveragepy#1510 .. _issue 1511: nedbat/coveragepy#1511 .. _issue 1512: nedbat/coveragepy#1512 .. _issue 1513: nedbat/coveragepy#1513

    .. _changes_7-0-0:

    Commits
    • c5cda3a docs: releases take a little bit longer now
    • 9d4226e docs: latest sample HTML report
    • 8c77758 docs: prep for 7.0.1
    • da1b282 fix: also look into .whl files for source
    • d327a70 fix: more information when mapping rules aren't working right.
    • 35e249f fix: certain strange characters caused reporting to fail. #1512
    • 152cdc7 fix: don't forbid plus signs in file names. #1513
    • 31513b4 chore: make upgrade
    • 873b059 test: don't run tests on Windows PyPy-3.9
    • 5c5caa2 build: PyPy wheel now installs on 3.7, 3.8, and 3.9. #1510
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies python 
    opened by dependabot[bot] 0
  • Add mypy as pre-commit hook

    Add mypy as pre-commit hook

    This changeset adds mypy as a pre-commit hook. As a result, the pipeline can simply run pre-commit and we can get rid of the make lint target and the tox -e lint environment.

    This patch also contains a couple of clean-ups to the CI pipeline.

    opened by seifertm 1
  • Python 3.10.9: DeprecationWarning: There is no current event loop

    Python 3.10.9: DeprecationWarning: There is no current event loop

    CPython 3.10.9 was released this week and tweaked the DeprecationWarning of asyncio.get_event_loop(): https://github.com/python/cpython/issues/93453

    As a consequence tests are now failing again, despite #214.

    opened by jakob-keller 4
  • Fix usage of anyio TaskGroups in fixtures

    Fix usage of anyio TaskGroups in fixtures

    When I use async generator fixutres with

    async with anyio.TaskGroup() as tg:
        ...
    

    inside I get this error on exit: Attempted to exit cancel scope in a different task than it was entered in This patch makes a single task for the fixture enter and exit. May be there is a more simple and elegant way to solve this (without using Queue) but this is what I found.

    opened by nikicat 0
Releases(v0.20.3)
  • v0.20.3(Dec 8, 2022)


    title: 'pytest-asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is a pytest plugin. It facilitates testing of code that uses the asyncio library.

    Specifically, pytest-asyncio provides support for coroutines as test functions. This allows users to await code inside their tests. For example, the following code is executed as a test item by pytest:

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    Note that test classes subclassing the standard unittest library are not supported. Users are advised to use unittest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    pytest-asyncio is available under the Apache License 2.0.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.20.3.tar.gz(28.26 KB)
    pytest_asyncio-0.20.3-py3-none-any.whl(12.24 KB)
  • v0.20.2(Nov 11, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Pytest-asyncio provides two modes: auto and strict with strict mode being the default.

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overridden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; please use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    This mode is used by default for the sake of project inter-compatibility.

    Fixtures

    event_loop

    Creates a new asyncio event loop based on the current event loop policy. The new loop is available as the return value of this fixture or via asyncio.get_running_loop. The event loop is closed when the fixture scope ends. The fixture scope defaults to function scope.

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    The event_loop fixture can be overridden in any of the standard pytest locations, e.g. directly in the test file, or in conftest.py. This allows redefining the fixture scope, for example:

    @pytest.fixture(scope="session")
    def event_loop():
        policy = asyncio.get_event_loop_policy()
        loop = policy.new_event_loop()
        yield loop
        loop.close()
    

    If you need to change the type of the event loop, prefer setting a custom event loop policy over redefining the event_loop fixture.

    If the pytest.mark.asyncio marker is applied to a test function, the event_loop fixture will be requested automatically by the test function.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unittest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.20.2.tar.gz(28.22 KB)
    pytest_asyncio-0.20.2-py3-none-any.whl(14.30 KB)
  • v0.20.1(Oct 21, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Pytest-asyncio provides two modes: auto and strict with strict mode being the default.

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overridden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; please use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    This mode is used by default for the sake of project inter-compatibility.

    Fixtures

    event_loop

    Creates a new asyncio event loop based on the current event loop policy. The new loop is available as the return value of this fixture or via asyncio.get_running_loop. The event loop is closed when the fixture scope ends. The fixture scope defaults to function scope.

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    The event_loop fixture can be overridden in any of the standard pytest locations, e.g. directly in the test file, or in conftest.py. This allows redefining the fixture scope, for example:

    @pytest.fixture(scope="session")
    def event_loop():
        policy = asyncio.get_event_loop_policy()
        loop = policy.new_event_loop()
        yield loop
        loop.close()
    

    If you need to change the type of the event loop, prefer setting a custom event loop policy over redefining the event_loop fixture.

    If the pytest.mark.asyncio marker is applied to a test function, the event_loop fixture will be requested automatically by the test function.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unittest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.20.1.tar.gz(27.78 KB)
    pytest_asyncio-0.20.1-py3-none-any.whl(14.05 KB)
  • v0.20.0(Oct 21, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Pytest-asyncio provides two modes: auto and strict with strict mode being the default.

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overridden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; please use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    This mode is used by default for the sake of project inter-compatibility.

    Fixtures

    event_loop

    Creates a new asyncio event loop based on the current event loop policy. The new loop is available as the return value of this fixture or via asyncio.get_running_loop. The event loop is closed when the fixture scope ends. The fixture scope defaults to function scope.

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    The event_loop fixture can be overridden in any of the standard pytest locations, e.g. directly in the test file, or in conftest.py. This allows redefining the fixture scope, for example:

    @pytest.fixture(scope="session")
    def event_loop():
        policy = asyncio.get_event_loop_policy()
        loop = policy.new_event_loop()
        yield loop
        loop.close()
    

    If you need to change the type of the event loop, prefer setting a custom event loop policy over redefining the event_loop fixture.

    If the pytest.mark.asyncio marker is applied to a test function, the event_loop fixture will be requested automatically by the test function.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unittest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.20.0.tar.gz(27.58 KB)
    pytest_asyncio-0.20.0-py3-none-any.whl(14.06 KB)
  • v0.19.0(Jul 15, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy. Starting from pytest-asyncio>=0.19 the strict mode is the default.

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overridden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; please use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    This mode is used by default for the sake of project inter-compatibility.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    Deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    The default was changed to strict in pytest-asyncio>=0.19.

    Fixtures

    event_loop

    Creates a new asyncio event loop based on the current event loop policy. The new loop is available as the return value of this fixture or via asyncio.get_running_loop. The event loop is closed when the fixture scope ends. The fixture scope defaults to function scope.

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    The event_loop fixture can be overridden in any of the standard pytest locations, e.g. directly in the test file, or in conftest.py. This allows redefining the fixture scope, for example:

    @pytest.fixture(scope="session")
    def event_loop():
        policy = asyncio.get_event_loop_policy()
        loop = policy.new_event_loop()
        yield loop
        loop.close()
    

    If you need to change the type of the event loop, prefer setting a custom event loop policy over redefining the event_loop fixture.

    If the pytest.mark.asyncio marker is applied to a test function, the event_loop fixture will be requested automatically by the test function.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unittest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.19.0.tar.gz(28.18 KB)
    pytest_asyncio-0.19.0-py3-none-any.whl(14.39 KB)
  • v0.18.3(Mar 25, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overridden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; please use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.18.3.tar.gz(27.39 KB)
    pytest_asyncio-0.18.3-py3-none-any.whl(14.25 KB)
  • v0.18.2(Mar 3, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overridden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; please use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Changelog

    0.18.2 (22-03-03)

    • Fix asyncio auto mode not marking static methods. #295
    • Fix a compatibility issue with Hypothesis 6.39.0. #302

    0.18.1 (22-02-10)

    • Fixes a regression that prevented async fixtures from working in synchronous tests. #286

    0.18.0 (22-02-07)

    • Raise a warning if @pytest.mark.asyncio is applied to non-async function. #275
    • Support parametrized event_loop fixture. #278

    0.17.2 (22-01-17)

    • Require typing-extensions on Python<3.8 only. #269
    • Fix a regression in tests collection introduced by 0.17.1, the plugin works fine with non-python tests again. #267

    0.17.1 (22-01-16)

    • Fixes a bug that prevents async Hypothesis tests from working without explicit asyncio marker when --asyncio-mode=auto is set. #258
    • Fixed a bug that closes the default event loop if the loop doesn't exist #257
    • Added type annotations. #198
    • Show asyncio mode in pytest report headers. #266
    • Relax asyncio_mode type definition; it allows to support pytest 6.1+. #262

    0.17.0 (22-01-13)

    • [pytest-asyncio]{.title-ref} no longer alters existing event loop policies. #168, #188
    • Drop support for Python 3.6
    • Fixed an issue when pytest-asyncio was used in combination with [flaky]{.title-ref} or inherited asynchronous Hypothesis tests. #178 #231
    • Added flaky to test dependencies
    • Added unused_udp_port and unused_udp_port_factory fixtures (similar to unused_tcp_port and unused_tcp_port_factory counterparts. #99
    • Added the plugin modes: strict, auto, and legacy. See documentation for details. #125
    • Correctly process KeyboardInterrupt during async fixture setup phase #219

    0.16.0 (2021-10-16)

    • Add support for Python 3.10

    0.15.1 (2021-04-22)

    • Hotfix for errors while closing event loops while replacing them. #209 #210

    0.15.0 (2021-04-19)

    • Add support for Python 3.9
    • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    • Set unused_tcp_port_factory fixture scope to 'session'. #163
    • Properly close event loops when replacing them. #208

    0.14.0 (2020-06-24)

    • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

    0.12.0 (2020-05-04)

    • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

    0.11.0 (2020-04-20)

    • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
    • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
    • Better pytest.skip support. #126

    0.10.0 (2019-01-08)

    • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
    • Pytest 4.1 support. #105

    0.9.0 (2018-07-28)

    • Python 3.7 support.
    • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

    0.8.0 (2017-09-23)

    • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

    0.7.0 (2017-09-08)

    • Python versions pre-3.6 can use the async_generator library for async fixtures. [#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>]{.title-ref}

    0.6.0 (2017-05-28)

    • Support for Python versions pre-3.5 has been dropped.
    • pytestmark now works on both module and class level.
    • The forbid_global_loop parameter has been removed.
    • Support for async and async gen fixtures has been added. #45
    • The deprecation warning regarding asyncio.async() has been fixed. #51

    0.5.0 (2016-09-07)

    • Introduced a changelog. #31
    • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
    • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

    0.4.1 (2016-06-01)

    • Fix a bug preventing the propagation of exceptions from the plugin. #25

    0.4.0 (2016-05-30)

    • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
    • Introduce the forbid_global_loop parameter. #21

    0.3.0 (2015-12-19)

    • Support for Python 3.5 async/await syntax. #17

    0.2.0 (2015-08-01)

    • unused_tcp_port_factory fixture. #10

    0.1.1 (2015-04-23)

    Initial release.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.18.2.tar.gz(31.33 KB)
    pytest_asyncio-0.18.2-py3-none-any.whl(16.34 KB)
  • v0.18.1(Feb 10, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overridden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; please use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Changelog

    0.18.1 (22-02-10)

    • Fixes a regression that prevented async fixtures from working in synchronous tests. #286

    0.18.0 (22-02-07)

    • Raise a warning if @pytest.mark.asyncio is applied to non-async function. #275
    • Support parametrized event_loop fixture. #278

    0.17.2 (22-01-17)

    • Require typing-extensions on Python<3.8 only. #269
    • Fix a regression in tests collection introduced by 0.17.1, the plugin works fine with non-python tests again. #267

    0.17.1 (22-01-16)

    • Fixes a bug that prevents async Hypothesis tests from working without explicit asyncio marker when --asyncio-mode=auto is set. #258
    • Fixed a bug that closes the default event loop if the loop doesn't exist #257
    • Added type annotations. #198
    • Show asyncio mode in pytest report headers. #266
    • Relax asyncio_mode type definition; it allows to support pytest 6.1+. #262

    0.17.0 (22-01-13)

    • [pytest-asyncio]{.title-ref} no longer alters existing event loop policies. #168, #188
    • Drop support for Python 3.6
    • Fixed an issue when pytest-asyncio was used in combination with [flaky]{.title-ref} or inherited asynchronous Hypothesis tests. #178 #231
    • Added flaky to test dependencies
    • Added unused_udp_port and unused_udp_port_factory fixtures (similar to unused_tcp_port and unused_tcp_port_factory counterparts. #99
    • Added the plugin modes: strict, auto, and legacy. See documentation for details. #125
    • Correctly process KeyboardInterrupt during async fixture setup phase #219

    0.16.0 (2021-10-16)

    • Add support for Python 3.10

    0.15.1 (2021-04-22)

    • Hotfix for errors while closing event loops while replacing them. #209 #210

    0.15.0 (2021-04-19)

    • Add support for Python 3.9
    • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    • Set unused_tcp_port_factory fixture scope to 'session'. #163
    • Properly close event loops when replacing them. #208

    0.14.0 (2020-06-24)

    • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

    0.12.0 (2020-05-04)

    • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

    0.11.0 (2020-04-20)

    • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
    • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
    • Better pytest.skip support. #126

    0.10.0 (2019-01-08)

    • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
    • Pytest 4.1 support. #105

    0.9.0 (2018-07-28)

    • Python 3.7 support.
    • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

    0.8.0 (2017-09-23)

    • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

    0.7.0 (2017-09-08)

    • Python versions pre-3.6 can use the async_generator library for async fixtures. [#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>]{.title-ref}

    0.6.0 (2017-05-28)

    • Support for Python versions pre-3.5 has been dropped.
    • pytestmark now works on both module and class level.
    • The forbid_global_loop parameter has been removed.
    • Support for async and async gen fixtures has been added. #45
    • The deprecation warning regarding asyncio.async() has been fixed. #51

    0.5.0 (2016-09-07)

    • Introduced a changelog. #31
    • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
    • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

    0.4.1 (2016-06-01)

    • Fix a bug preventing the propagation of exceptions from the plugin. #25

    0.4.0 (2016-05-30)

    • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
    • Introduce the forbid_global_loop parameter. #21

    0.3.0 (2015-12-19)

    • Support for Python 3.5 async/await syntax. #17

    0.2.0 (2015-08-01)

    • unused_tcp_port_factory fixture. #10

    0.1.1 (2015-04-23)

    Initial release.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.18.1.tar.gz(31.15 KB)
    pytest_asyncio-0.18.1-py3-none-any.whl(16.24 KB)
  • v0.18.0(Feb 7, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overriden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; plase use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Changelog

    0.18.0 (22-02-07)

    • Raise a warning if @pytest.mark.asyncio is applied to non-async function. #275
    • Support parametrized event_loop fixture. #278

    0.17.2 (22-01-17)

    • Require typing-extensions on Python<3.8 only. #269
    • Fix a regression in tests collection introduced by 0.17.1, the plugin works fine with non-python tests again. #267

    0.17.1 (22-01-16)

    • Fixes a bug that prevents async Hypothesis tests from working without explicit asyncio marker when --asyncio-mode=auto is set. #258
    • Fixed a bug that closes the default event loop if the loop doesn't exist #257
    • Added type annotations. #198
    • Show asyncio mode in pytest report headers. #266
    • Relax asyncio_mode type definition; it allows to support pytest 6.1+. #262

    0.17.0 (22-01-13)

    • [pytest-asyncio]{.title-ref} no longer alters existing event loop policies. #168, #188
    • Drop support for Python 3.6
    • Fixed an issue when pytest-asyncio was used in combination with [flaky]{.title-ref} or inherited asynchronous Hypothesis tests. #178 #231
    • Added flaky to test dependencies
    • Added unused_udp_port and unused_udp_port_factory fixtures (similar to unused_tcp_port and unused_tcp_port_factory counterparts. #99
    • Added the plugin modes: strict, auto, and legacy. See documentation for details. #125
    • Correctly process KeyboardInterrupt during async fixture setup phase #219

    0.16.0 (2021-10-16)

    • Add support for Python 3.10

    0.15.1 (2021-04-22)

    • Hotfix for errors while closing event loops while replacing them. #209 #210

    0.15.0 (2021-04-19)

    • Add support for Python 3.9
    • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    • Set unused_tcp_port_factory fixture scope to 'session'. #163
    • Properly close event loops when replacing them. #208

    0.14.0 (2020-06-24)

    • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

    0.12.0 (2020-05-04)

    • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

    0.11.0 (2020-04-20)

    • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
    • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
    • Better pytest.skip support. #126

    0.10.0 (2019-01-08)

    • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
    • Pytest 4.1 support. #105

    0.9.0 (2018-07-28)

    • Python 3.7 support.
    • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

    0.8.0 (2017-09-23)

    • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

    0.7.0 (2017-09-08)

    • Python versions pre-3.6 can use the async_generator library for async fixtures. [#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>]{.title-ref}

    0.6.0 (2017-05-28)

    • Support for Python versions pre-3.5 has been dropped.
    • pytestmark now works on both module and class level.
    • The forbid_global_loop parameter has been removed.
    • Support for async and async gen fixtures has been added. #45
    • The deprecation warning regarding asyncio.async() has been fixed. #51

    0.5.0 (2016-09-07)

    • Introduced a changelog. #31
    • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
    • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

    0.4.1 (2016-06-01)

    • Fix a bug preventing the propagation of exceptions from the plugin. #25

    0.4.0 (2016-05-30)

    • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
    • Introduce the forbid_global_loop parameter. #21

    0.3.0 (2015-12-19)

    • Support for Python 3.5 async/await syntax. #17

    0.2.0 (2015-08-01)

    • unused_tcp_port_factory fixture. #10

    0.1.1 (2015-04-23)

    Initial release.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.18.0.tar.gz(30.98 KB)
    pytest_asyncio-0.18.0-py3-none-any.whl(16.20 KB)
  • v0.17.2(Jan 17, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overriden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; plase use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Changelog

    0.17.2 (22-01-17)

    • Require typing-extensions on Python<3.8 only. #269
    • Fix a regression in tests collection introduced by 0.17.1, the plugin works fine with non-python tests again. #267

    0.17.1 (22-01-16)

    • Fixes a bug that prevents async Hypothesis tests from working without explicit asyncio marker when --asyncio-mode=auto is set. #258
    • Fixed a bug that closes the default event loop if the loop doesn't exist #257
    • Added type annotations. #198
    • Show asyncio mode in pytest report headers. #266
    • Relax asyncio_mode type definition; it allows to support pytest 6.1+. #262

    0.17.0 (22-01-13)

    • [pytest-asyncio]{.title-ref} no longer alters existing event loop policies. #168, #188
    • Drop support for Python 3.6
    • Fixed an issue when pytest-asyncio was used in combination with [flaky]{.title-ref} or inherited asynchronous Hypothesis tests. #178 #231
    • Added flaky to test dependencies
    • Added unused_udp_port and unused_udp_port_factory fixtures (similar to unused_tcp_port and unused_tcp_port_factory counterparts. #99
    • Added the plugin modes: strict, auto, and legacy. See documentation for details. #125
    • Correctly process KeyboardInterrupt during async fixture setup phase #219

    0.16.0 (2021-10-16)

    • Add support for Python 3.10

    0.15.1 (2021-04-22)

    • Hotfix for errors while closing event loops while replacing them. #209 #210

    0.15.0 (2021-04-19)

    • Add support for Python 3.9
    • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    • Set unused_tcp_port_factory fixture scope to 'session'. #163
    • Properly close event loops when replacing them. #208

    0.14.0 (2020-06-24)

    • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

    0.12.0 (2020-05-04)

    • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

    0.11.0 (2020-04-20)

    • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
    • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
    • Better pytest.skip support. #126

    0.10.0 (2019-01-08)

    • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
    • Pytest 4.1 support. #105

    0.9.0 (2018-07-28)

    • Python 3.7 support.
    • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

    0.8.0 (2017-09-23)

    • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

    0.7.0 (2017-09-08)

    • Python versions pre-3.6 can use the async_generator library for async fixtures. [#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>]{.title-ref}

    0.6.0 (2017-05-28)

    • Support for Python versions pre-3.5 has been dropped.
    • pytestmark now works on both module and class level.
    • The forbid_global_loop parameter has been removed.
    • Support for async and async gen fixtures has been added. #45
    • The deprecation warning regarding asyncio.async() has been fixed. #51

    0.5.0 (2016-09-07)

    • Introduced a changelog. #31
    • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
    • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

    0.4.1 (2016-06-01)

    • Fix a bug preventing the propagation of exceptions from the plugin. #25

    0.4.0 (2016-05-30)

    • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
    • Introduce the forbid_global_loop parameter. #21

    0.3.0 (2015-12-19)

    • Support for Python 3.5 async/await syntax. #17

    0.2.0 (2015-08-01)

    • unused_tcp_port_factory fixture. #10

    0.1.1 (2015-04-23)

    Initial release.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.17.2.tar.gz(30.46 KB)
    pytest_asyncio-0.17.2-py3-none-any.whl(16.07 KB)
  • v0.17.1(Jan 16, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overriden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; plase use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Changelog

    0.17.1 (22-01-16)

    • Fixes a bug that prevents async Hypothesis tests from working without explicit asyncio marker when --asyncio-mode=auto is set. #258
    • Fixed a bug that closes the default event loop if the loop doesn't exist #257
    • Added type annotations. #198
    • Show asyncio mode in pytest report headers. #266
    • Relax asyncio_mode type definition; it allows to support pytest 6.1+. #262

    0.17.0 (22-01-13)

    • [pytest-asyncio]{.title-ref} no longer alters existing event loop policies. #168, #188
    • Drop support for Python 3.6
    • Fixed an issue when pytest-asyncio was used in combination with [flaky]{.title-ref} or inherited asynchronous Hypothesis tests. #178 #231
    • Added flaky to test dependencies
    • Added unused_udp_port and unused_udp_port_factory fixtures (similar to unused_tcp_port and unused_tcp_port_factory counterparts. #99
    • Added the plugin modes: strict, auto, and legacy. See documentation for details. #125
    • Correctly process KeyboardInterrupt during async fixture setup phase #219

    0.16.0 (2021-10-16)

    • Add support for Python 3.10

    0.15.1 (2021-04-22)

    • Hotfix for errors while closing event loops while replacing them. #209 #210

    0.15.0 (2021-04-19)

    • Add support for Python 3.9
    • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    • Set unused_tcp_port_factory fixture scope to 'session'. #163
    • Properly close event loops when replacing them. #208

    0.14.0 (2020-06-24)

    • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

    0.12.0 (2020-05-04)

    • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

    0.11.0 (2020-04-20)

    • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
    • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
    • Better pytest.skip support. #126

    0.10.0 (2019-01-08)

    • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
    • Pytest 4.1 support. #105

    0.9.0 (2018-07-28)

    • Python 3.7 support.
    • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

    0.8.0 (2017-09-23)

    • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

    0.7.0 (2017-09-08)

    • Python versions pre-3.6 can use the async_generator library for async fixtures. [#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>]{.title-ref}

    0.6.0 (2017-05-28)

    • Support for Python versions pre-3.5 has been dropped.
    • pytestmark now works on both module and class level.
    • The forbid_global_loop parameter has been removed.
    • Support for async and async gen fixtures has been added. #45
    • The deprecation warning regarding asyncio.async() has been fixed. #51

    0.5.0 (2016-09-07)

    • Introduced a changelog. #31
    • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
    • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

    0.4.1 (2016-06-01)

    • Fix a bug preventing the propagation of exceptions from the plugin. #25

    0.4.0 (2016-05-30)

    • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
    • Introduce the forbid_global_loop parameter. #21

    0.3.0 (2015-12-19)

    • Support for Python 3.5 async/await syntax. #17

    0.2.0 (2015-08-01)

    • unused_tcp_port_factory fixture. #10

    0.1.1 (2015-04-23)

    Initial release.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.17.1.tar.gz(30.21 KB)
    pytest_asyncio-0.17.1-py3-none-any.whl(15.93 KB)
  • v0.17.0(Jan 13, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overriden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; plase use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Changelog

    0.17.0 (22-01-13)

    • [pytest-asyncio]{.title-ref} no longer alters existing event loop policies. #168, #188
    • Drop support for Python 3.6
    • Fixed an issue when pytest-asyncio was used in combination with [flaky]{.title-ref} or inherited asynchronous Hypothesis tests. #178 #231
    • Added flaky to test dependencies
    • Added unused_udp_port and unused_udp_port_factory fixtures (similar to unused_tcp_port and unused_tcp_port_factory counterparts. #99
    • Added the plugin modes: strict, auto, and legacy. See documentation for details. #125
    • Correctly process KeyboardInterrupt during async fixture setup phase #219

    0.16.0 (2021-10-16)

    • Add support for Python 3.10

    0.15.1 (2021-04-22)

    • Hotfix for errors while closing event loops while replacing them. #209 #210

    0.15.0 (2021-04-19)

    • Add support for Python 3.9
    • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    • Set unused_tcp_port_factory fixture scope to 'session'. #163
    • Properly close event loops when replacing them. #208

    0.14.0 (2020-06-24)

    • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

    0.12.0 (2020-05-04)

    • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

    0.11.0 (2020-04-20)

    • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
    • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
    • Better pytest.skip support. #126

    0.10.0 (2019-01-08)

    • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
    • Pytest 4.1 support. #105

    0.9.0 (2018-07-28)

    • Python 3.7 support.
    • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

    0.8.0 (2017-09-23)

    • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

    0.7.0 (2017-09-08)

    • Python versions pre-3.6 can use the async_generator library for async fixtures. [#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>]{.title-ref}

    0.6.0 (2017-05-28)

    • Support for Python versions pre-3.5 has been dropped.
    • pytestmark now works on both module and class level.
    • The forbid_global_loop parameter has been removed.
    • Support for async and async gen fixtures has been added. #45
    • The deprecation warning regarding asyncio.async() has been fixed. #51

    0.5.0 (2016-09-07)

    • Introduced a changelog. #31
    • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
    • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

    0.4.1 (2016-06-01)

    • Fix a bug preventing the propagation of exceptions from the plugin. #25

    0.4.0 (2016-05-30)

    • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
    • Introduce the forbid_global_loop parameter. #21

    0.3.0 (2015-12-19)

    • Support for Python 3.5 async/await syntax. #17

    0.2.0 (2015-08-01)

    • unused_tcp_port_factory fixture. #10

    0.1.1 (2015-04-23)

    Initial release.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.17.0.tar.gz(28.63 KB)
    pytest_asyncio-0.17.0-py3-none-any.whl(14.70 KB)
  • v0.17.0a6(Jan 13, 2022)


    title: 'pytest-asyncio: pytest support for asyncio'

    image

    image

    image

    Supported Python versions

    image

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado.

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for [async def]{.title-ref} fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file:

    # pytest.ini
    [pytest]
    asyncio_mode = auto
    

    The value can be overriden by command-line option for pytest invocation:

    $ pytest tests --asyncio-mode=strict
    

    Auto mode

    When the mode is auto, all discovered async tests are considered asyncio-driven even if they have no @pytest.mark.asyncio marker.

    All async fixtures are considered asyncio-driven as well, even if they are decorated with a regular @pytest.fixture decorator instead of dedicated @pytest_asyncio.fixture counterpart.

    asyncio-driven means that tests and fixtures are executed by pytest-asyncio plugin.

    This mode requires the simplest tests and fixtures configuration and is recommended for default usage unless the same project and its test suite should execute tests from different async frameworks, e.g. asyncio and trio. In this case, auto-handling can break tests designed for other framework; plase use strict mode instead.

    Strict mode

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    This mode follows rules used by pytest-asyncio<0.17: tests are not auto-marked but fixtures are.

    This mode is used by default for the sake of backward compatibility, deprecation warnings are emitted with suggestion to either switching to auto mode or using strict mode with @pytest_asyncio.fixture decorators.

    In future, the default will be changed.

    Fixtures

    event_loop

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for binding temporary test servers.

    unused_tcp_port_factory

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.

    Async fixtures

    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with @pytest_asyncio.fixture.

    import pytest_asyncio
    
    
    @pytest_asyncio.fixture
    async def async_gen_fixture():
        await asyncio.sleep(0.1)
        yield "a value"
    
    
    @pytest_asyncio.fixture(scope="module")
    async def async_fixture():
        return await asyncio.sleep(0.1)
    

    All scopes are supported, but if you use a non-function scope you will need to redefine the event_loop fixture to have the same or broader scope. Async fixtures need the event loop, and so must have the same or narrower scope than the event_loop fixture.

    auto and legacy mode automatically converts async fixtures declared with the standard @pytest.fixture decorator to asyncio-driven versions.

    Markers

    pytest.mark.asyncio

    Mark your test coroutine with this marker and pytest will execute it as an asyncio task using the event loop provided by the event_loop fixture. See the introductory section for an example.

    The event loop used can be overridden by overriding the event_loop fixture (see above).

    In order to make your test code a little more concise, the pytest pytestmark_ feature can be used to mark entire modules or classes with this marker. Only test coroutines will be affected (by default, coroutines prefixed by test_), so, for example, fixtures are safe to define.

    import asyncio
    
    import pytest
    
    # All test coroutines will be treated as marked.
    pytestmark = pytest.mark.asyncio
    
    
    async def test_example(event_loop):
        """No marker!"""
        await asyncio.sleep(0, loop=event_loop)
    

    In auto mode, the pytest.mark.asyncio marker can be omitted, the marker is added automatically to async test functions.

    Note about unittest

    Test classes subclassing the standard unittest library are not supported, users are recommended to use unitest.IsolatedAsyncioTestCase or an async framework such as asynctest.

    Changelog

    0.17.0 (UNRELEASED)

    • [pytest-asyncio]{.title-ref} no longer alters existing event loop policies. #168, #188
    • Drop support for Python 3.6
    • Fixed an issue when pytest-asyncio was used in combination with [flaky]{.title-ref} or inherited asynchronous Hypothesis tests. #178 #231
    • Added flaky to test dependencies
    • Added unused_udp_port and unused_udp_port_factory fixtures (similar to unused_tcp_port and unused_tcp_port_factory counterparts. #99
    • Added the plugin modes: strict, auto, and legacy. See documentation for details. #125
    • Correctly process KeyboardInterrupt during async fixture setup phase #219

    0.16.0 (2021-10-16)

    • Add support for Python 3.10

    0.15.1 (2021-04-22)

    • Hotfix for errors while closing event loops while replacing them. #209 #210

    0.15.0 (2021-04-19)

    • Add support for Python 3.9
    • Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    • Set unused_tcp_port_factory fixture scope to 'session'. #163
    • Properly close event loops when replacing them. #208

    0.14.0 (2020-06-24)

    • Fix #162, and event_loop fixture behavior now is coherent on all scopes. #164

    0.12.0 (2020-05-04)

    • Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop. #156

    0.11.0 (2020-04-20)

    • Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions. #152
    • Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0. #142
    • Better pytest.skip support. #126

    0.10.0 (2019-01-08)

    • pytest-asyncio integrates with Hypothesis to support @given on async test functions using asyncio. #102
    • Pytest 4.1 support. #105

    0.9.0 (2018-07-28)

    • Python 3.7 support.
    • Remove event_loop_process_pool fixture and pytest.mark.asyncio_process_pool marker (see https://bugs.python.org/issue34075 for deprecation and removal details)

    0.8.0 (2017-09-23)

    • Improve integration with other packages (like aiohttp) with more careful event loop handling. #64

    0.7.0 (2017-09-08)

    • Python versions pre-3.6 can use the async_generator library for async fixtures. [#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>]{.title-ref}

    0.6.0 (2017-05-28)

    • Support for Python versions pre-3.5 has been dropped.
    • pytestmark now works on both module and class level.
    • The forbid_global_loop parameter has been removed.
    • Support for async and async gen fixtures has been added. #45
    • The deprecation warning regarding asyncio.async() has been fixed. #51

    0.5.0 (2016-09-07)

    • Introduced a changelog. #31
    • The event_loop fixture is again responsible for closing itself. This makes the fixture slightly harder to correctly override, but enables other fixtures to depend on it correctly. #30
    • Deal with the event loop policy by wrapping a special pytest hook, pytest_fixture_setup. This allows setting the policy before fixtures dependent on the event_loop fixture run, thus allowing them to take advantage of the forbid_global_loop parameter. As a consequence of this, we now depend on pytest 3.0. #29

    0.4.1 (2016-06-01)

    • Fix a bug preventing the propagation of exceptions from the plugin. #25

    0.4.0 (2016-05-30)

    • Make event_loop fixtures simpler to override by closing them in the plugin, instead of directly in the fixture. #21
    • Introduce the forbid_global_loop parameter. #21

    0.3.0 (2015-12-19)

    • Support for Python 3.5 async/await syntax. #17

    0.2.0 (2015-08-01)

    • unused_tcp_port_factory fixture. #10

    0.1.1 (2015-04-23)

    Initial release.

    Contributing

    Contributions are very welcome. Tests can be run with tox, please ensure the coverage at least stays the same before you submit a pull request.

    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.17.0a6.tar.gz(28.69 KB)
    pytest_asyncio-0.17.0a6-py3-none-any.whl(14.73 KB)
  • v0.17.0a4(Jan 13, 2022)

    pytest-asyncio: pytest support for asyncio

    .. image:: https://img.shields.io/pypi/v/pytest-asyncio.svg :target: https://pypi.python.org/pypi/pytest-asyncio .. image:: https://github.com/pytest-dev/pytest-asyncio/workflows/CI/badge.svg :target: https://github.com/pytest-dev/pytest-asyncio/actions?workflow=CI .. image:: https://codecov.io/gh/pytest-dev/pytest-asyncio/branch/master/graph/badge.svg :target: https://codecov.io/gh/pytest-dev/pytest-asyncio .. image:: https://img.shields.io/pypi/pyversions/pytest-asyncio.svg :target: https://github.com/pytest-dev/pytest-asyncio :alt: Supported Python versions .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    .. code-block:: python

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado_.

    .. _pytest-tornado: https://github.com/eugeniy/pytest-tornado

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for async def fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    .. code-block:: bash

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file <https://docs.pytest.org/en/latest/reference/customize.html>_:

    .. code-block:: ini

    pytest.ini

    [pytest] asyncio_mode = auto

    The value can be overriden by command-line option for pytest invocation:

    .. code-block:: bash

    $ pytest tests --asyncio-mode=strict

    Auto mode

    
    When the mode is auto, all discovered *async* tests are considered *asyncio-driven* even
    if they have no ``@pytest.mark.asyncio`` marker.
    
    All async fixtures are considered *asyncio-driven* as well, even if they are decorated
    with a regular ``@pytest.fixture`` decorator instead of dedicated
    ``@pytest_asyncio.fixture`` counterpart.
    
    *asyncio-driven* means that tests and fixtures are executed by ``pytest-asyncio``
    plugin.
    
    This mode requires the simplest tests and fixtures configuration and is
    recommended for default usage *unless* the same project and its test suite should
    execute tests from different async frameworks, e.g. ``asyncio`` and ``trio``.  In this
    case, auto-handling can break tests designed for other framework; plase use *strict*
    mode instead.
    
    Strict mode
    

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    
    This mode follows rules used by ``pytest-asyncio<0.17``: tests are not auto-marked but
    fixtures are.
    
    This mode is used by default for the sake of backward compatibility, deprecation
    warnings are emitted with suggestion to either switching to ``auto`` mode or using
    ``strict`` mode with ``@pytest_asyncio.fixture`` decorators.
    
    In future, the default will be changed.
    
    
    Fixtures
    --------
    
    ``event_loop``
    

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    .. code-block:: python

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    .. code-block:: python

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for
    binding temporary test servers.
    
    ``unused_tcp_port_factory``
    

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    .. code-block:: python

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.
    
    
    Async fixtures
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with ``@pytest_asyncio.fixture``.
    
    .. code-block:: python3
    
        import pytest_asyncio
    
    
        @pytest_asyncio.fixture
        async def async_gen_fixture():
            await asyncio.sleep(0.1)
            yield "a value"
    
    
        @pytest_asyncio.fixture(scope="module")
        async def async_fixture():
            return await asyncio.sleep(0.1)
    
    All scopes are supported, but if you use a non-function scope you will need
    to redefine the ``event_loop`` fixture to have the same or broader scope.
    Async fixtures need the event loop, and so must have the same or narrower scope
    than the ``event_loop`` fixture.
    
    *auto* and *legacy* mode automatically converts async fixtures declared with the
    standard ``@pytest.fixture`` decorator to *asyncio-driven* versions.
    
    
    Markers
    -------
    
    ``pytest.mark.asyncio``
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Mark your test coroutine with this marker and pytest will execute it as an
    asyncio task using the event loop provided by the ``event_loop`` fixture. See
    the introductory section for an example.
    
    The event loop used can be overridden by overriding the ``event_loop`` fixture
    (see above).
    
    In order to make your test code a little more concise, the pytest |pytestmark|_
    feature can be used to mark entire modules or classes with this marker.
    Only test coroutines will be affected (by default, coroutines prefixed by
    ``test_``), so, for example, fixtures are safe to define.
    
    .. code-block:: python
    
        import asyncio
    
        import pytest
    
        # All test coroutines will be treated as marked.
        pytestmark = pytest.mark.asyncio
    
    
        async def test_example(event_loop):
            """No marker!"""
            await asyncio.sleep(0, loop=event_loop)
    
    In *auto* mode, the ``pytest.mark.asyncio`` marker can be omitted, the marker is added
    automatically to *async* test functions.
    
    
    .. |pytestmark| replace:: ``pytestmark``
    .. _pytestmark: http://doc.pytest.org/en/latest/example/markers.html#marking-whole-classes-or-modules
    
    Note about unittest
    -------------------
    
    Test classes subclassing the standard `unittest <https://docs.python.org/3/library/unittest.html>`__ library are not supported, users
    are recommended to use `unitest.IsolatedAsyncioTestCase <https://docs.python.org/3/library/unittest.html#unittest.IsolatedAsyncioTestCase>`__
    or an async framework such as `asynctest <https://asynctest.readthedocs.io/en/latest>`__.
    
    Changelog
    ---------
    0.17.0 (UNRELEASED)
    ~~~~~~~~~~~~~~~~~~~
    - `pytest-asyncio` no longer alters existing event loop policies. `#168 <https://github.com/pytest-dev/pytest-asyncio/issues/168>`_, `#188 <https://github.com/pytest-dev/pytest-asyncio/issues/168>`_
    - Drop support for Python 3.6
    - Fixed an issue when pytest-asyncio was used in combination with `flaky` or inherited asynchronous Hypothesis tests. `#178 <https://github.com/pytest-dev/pytest-asyncio/issues/178>`_ `#231 <https://github.com/pytest-dev/pytest-asyncio/issues/231>`_
    - Added `flaky <https://pypi.org/project/flaky/>`_ to test dependencies
    - Added ``unused_udp_port`` and ``unused_udp_port_factory`` fixtures (similar to ``unused_tcp_port`` and ``unused_tcp_port_factory`` counterparts. `#99 <https://github.com/pytest-dev/pytest-asyncio/issues/99>`_
    - Added the plugin modes: *strict*, *auto*, and *legacy*. See `documentation <https://github.com/pytest-dev/pytest-asyncio#modes>`_ for details. `#125 <https://github.com/pytest-dev/pytest-asyncio/issues/125>`_
    - Correctly process ``KeyboardInterrupt`` during async fixture setup phase `#219 <https://github.com/pytest-dev/pytest-asyncio/issues/219>`_
    
    0.16.0 (2021-10-16)
    ~~~~~~~~~~~~~~~~~~~
    - Add support for Python 3.10
    
    0.15.1 (2021-04-22)
    ~~~~~~~~~~~~~~~~~~~
    - Hotfix for errors while closing event loops while replacing them.
      `#209 <https://github.com/pytest-dev/pytest-asyncio/issues/209>`_
      `#210 <https://github.com/pytest-dev/pytest-asyncio/issues/210>`_
    
    0.15.0 (2021-04-19)
    ~~~~~~~~~~~~~~~~~~~
    - Add support for Python 3.9
    - Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    - Set ``unused_tcp_port_factory`` fixture scope to 'session'.
      `#163 <https://github.com/pytest-dev/pytest-asyncio/pull/163>`_
    - Properly close event loops when replacing them.
      `#208 <https://github.com/pytest-dev/pytest-asyncio/issues/208>`_
    
    0.14.0 (2020-06-24)
    ~~~~~~~~~~~~~~~~~~~
    - Fix `#162 <https://github.com/pytest-dev/pytest-asyncio/issues/162>`_, and ``event_loop`` fixture behavior now is coherent on all scopes.
      `#164 <https://github.com/pytest-dev/pytest-asyncio/pull/164>`_
    
    0.12.0 (2020-05-04)
    ~~~~~~~~~~~~~~~~~~~
    - Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop.
      `#156 <https://github.com/pytest-dev/pytest-asyncio/pull/156>`_
    
    0.11.0 (2020-04-20)
    ~~~~~~~~~~~~~~~~~~~
    - Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions.
      `#152 <https://github.com/pytest-dev/pytest-asyncio/pull/152>`_
    - Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0.
      `#142 <https://github.com/pytest-dev/pytest-asyncio/pull/142>`_
    - Better ``pytest.skip`` support.
      `#126 <https://github.com/pytest-dev/pytest-asyncio/pull/126>`_
    
    0.10.0 (2019-01-08)
    ~~~~~~~~~~~~~~~~~~~~
    - ``pytest-asyncio`` integrates with `Hypothesis <https://hypothesis.readthedocs.io>`_
      to support ``@given`` on async test functions using ``asyncio``.
      `#102 <https://github.com/pytest-dev/pytest-asyncio/pull/102>`_
    - Pytest 4.1 support.
      `#105 <https://github.com/pytest-dev/pytest-asyncio/pull/105>`_
    
    0.9.0 (2018-07-28)
    ~~~~~~~~~~~~~~~~~~
    - Python 3.7 support.
    - Remove ``event_loop_process_pool`` fixture and
      ``pytest.mark.asyncio_process_pool`` marker (see
      https://bugs.python.org/issue34075 for deprecation and removal details)
    
    0.8.0 (2017-09-23)
    ~~~~~~~~~~~~~~~~~~
    - Improve integration with other packages (like aiohttp) with more careful event loop handling.
      `#64 <https://github.com/pytest-dev/pytest-asyncio/pull/64>`_
    
    0.7.0 (2017-09-08)
    ~~~~~~~~~~~~~~~~~~
    - Python versions pre-3.6 can use the async_generator library for async fixtures.
      `#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>`
    
    
    0.6.0 (2017-05-28)
    ~~~~~~~~~~~~~~~~~~
    - Support for Python versions pre-3.5 has been dropped.
    - ``pytestmark`` now works on both module and class level.
    - The ``forbid_global_loop`` parameter has been removed.
    - Support for async and async gen fixtures has been added.
      `#45 <https://github.com/pytest-dev/pytest-asyncio/pull/45>`_
    - The deprecation warning regarding ``asyncio.async()`` has been fixed.
      `#51 <https://github.com/pytest-dev/pytest-asyncio/pull/51>`_
    
    0.5.0 (2016-09-07)
    ~~~~~~~~~~~~~~~~~~
    - Introduced a changelog.
      `#31 <https://github.com/pytest-dev/pytest-asyncio/issues/31>`_
    - The ``event_loop`` fixture is again responsible for closing itself.
      This makes the fixture slightly harder to correctly override, but enables
      other fixtures to depend on it correctly.
      `#30 <https://github.com/pytest-dev/pytest-asyncio/issues/30>`_
    - Deal with the event loop policy by wrapping a special pytest hook,
      ``pytest_fixture_setup``. This allows setting the policy before fixtures
      dependent on the ``event_loop`` fixture run, thus allowing them to take
      advantage of the ``forbid_global_loop`` parameter. As a consequence of this,
      we now depend on pytest 3.0.
      `#29 <https://github.com/pytest-dev/pytest-asyncio/issues/29>`_
    
    
    0.4.1 (2016-06-01)
    ~~~~~~~~~~~~~~~~~~
    - Fix a bug preventing the propagation of exceptions from the plugin.
      `#25 <https://github.com/pytest-dev/pytest-asyncio/issues/25>`_
    
    0.4.0 (2016-05-30)
    ~~~~~~~~~~~~~~~~~~
    - Make ``event_loop`` fixtures simpler to override by closing them in the
      plugin, instead of directly in the fixture.
      `#21 <https://github.com/pytest-dev/pytest-asyncio/pull/21>`_
    - Introduce the ``forbid_global_loop`` parameter.
      `#21 <https://github.com/pytest-dev/pytest-asyncio/pull/21>`_
    
    0.3.0 (2015-12-19)
    ~~~~~~~~~~~~~~~~~~
    - Support for Python 3.5 ``async``/``await`` syntax.
      `#17 <https://github.com/pytest-dev/pytest-asyncio/pull/17>`_
    
    0.2.0 (2015-08-01)
    ~~~~~~~~~~~~~~~~~~
    - ``unused_tcp_port_factory`` fixture.
      `#10 <https://github.com/pytest-dev/pytest-asyncio/issues/10>`_
    
    
    0.1.1 (2015-04-23)
    ~~~~~~~~~~~~~~~~~~
    Initial release.
    
    
    Contributing
    ------------
    Contributions are very welcome. Tests can be run with ``tox``, please ensure
    the coverage at least stays the same before you submit a pull request.
    
    Source code(tar.gz)
    Source code(zip)
    pytest-asyncio-0.17.0a4.tar.gz(28.61 KB)
    pytest_asyncio-0.17.0a4-py3-none-any.whl(14.73 KB)
  • v0.17.0a3(Jan 13, 2022)

    pytest-asyncio: pytest support for asyncio

    .. image:: https://img.shields.io/pypi/v/pytest-asyncio.svg :target: https://pypi.python.org/pypi/pytest-asyncio .. image:: https://github.com/pytest-dev/pytest-asyncio/workflows/CI/badge.svg :target: https://github.com/pytest-dev/pytest-asyncio/actions?workflow=CI .. image:: https://codecov.io/gh/pytest-dev/pytest-asyncio/branch/master/graph/badge.svg :target: https://codecov.io/gh/pytest-dev/pytest-asyncio .. image:: https://img.shields.io/pypi/pyversions/pytest-asyncio.svg :target: https://github.com/pytest-dev/pytest-asyncio :alt: Supported Python versions .. image:: https://img.shields.io/badge/code%20style-black-000000.svg :target: https://github.com/ambv/black

    pytest-asyncio is an Apache2 licensed library, written in Python, for testing asyncio code with pytest.

    asyncio code is usually written in the form of coroutines, which makes it slightly more difficult to test using normal testing tools. pytest-asyncio provides useful fixtures and markers to make testing easier.

    .. code-block:: python

    @pytest.mark.asyncio
    async def test_some_asyncio_code():
        res = await library.do_something()
        assert b"expected result" == res
    

    pytest-asyncio has been strongly influenced by pytest-tornado_.

    .. _pytest-tornado: https://github.com/eugeniy/pytest-tornado

    Features

    • fixtures for creating and injecting versions of the asyncio event loop
    • fixtures for injecting unused tcp/udp ports
    • pytest markers for treating tests as asyncio coroutines
    • easy testing with non-default event loops
    • support for async def fixtures and async generator fixtures
    • support auto mode to handle all async fixtures and tests automatically by asyncio; provide strict mode if a test suite should work with different async frameworks simultaneously, e.g. asyncio and trio.

    Installation

    To install pytest-asyncio, simply:

    .. code-block:: bash

    $ pip install pytest-asyncio
    

    This is enough for pytest to pick up pytest-asyncio.

    Modes

    Starting from pytest-asyncio>=0.17, three modes are provided: auto, strict and legacy (default).

    The mode can be set by asyncio_mode configuration option in configuration file <https://docs.pytest.org/en/latest/reference/customize.html>_:

    .. code-block:: ini

    pytest.ini

    [pytest] asyncio_mode = auto

    The value can be overriden by command-line option for pytest invocation:

    .. code-block:: bash

    $ pytest tests --asyncio-mode=strict

    Auto mode

    
    When the mode is auto, all discovered *async* tests are considered *asyncio-driven* even
    if they have no ``@pytest.mark.asyncio`` marker.
    
    All async fixtures are considered *asyncio-driven* as well, even if they are decorated
    with a regular ``@pytest.fixture`` decorator instead of dedicated
    ``@pytest_asyncio.fixture`` counterpart.
    
    *asyncio-driven* means that tests and fixtures are executed by ``pytest-asyncio``
    plugin.
    
    This mode requires the simplest tests and fixtures configuration and is
    recommended for default usage *unless* the same project and its test suite should
    execute tests from different async frameworks, e.g. ``asyncio`` and ``trio``.  In this
    case, auto-handling can break tests designed for other framework; plase use *strict*
    mode instead.
    
    Strict mode
    

    Strict mode enforces @pytest.mark.asyncio and @pytest_asyncio.fixture usage. Without these markers, tests and fixtures are not considered as asyncio-driven, other pytest plugin can handle them.

    Please use this mode if multiple async frameworks should be combined in the same test suite.

    Legacy mode

    
    This mode follows rules used by ``pytest-asyncio<0.17``: tests are not auto-marked but
    fixtures are.
    
    This mode is used by default for the sake of backward compatibility, deprecation
    warnings are emitted with suggestion to either switching to ``auto`` mode or using
    ``strict`` mode with ``@pytest_asyncio.fixture`` decorators.
    
    In future, the default will be changed.
    
    
    Fixtures
    --------
    
    ``event_loop``
    

    Creates and injects a new instance of the default asyncio event loop. By default, the loop will be closed at the end of the test (i.e. the default fixture scope is function).

    Note that just using the event_loop fixture won't make your test function a coroutine. You'll need to interact with the event loop directly, using methods like event_loop.run_until_complete. See the pytest.mark.asyncio marker for treating test functions like coroutines.

    Simply using this fixture will not set the generated event loop as the default asyncio event loop, or change the asyncio event loop policy in any way. Use pytest.mark.asyncio for this purpose.

    .. code-block:: python

    def test_http_client(event_loop):
        url = "http://httpbin.org/get"
        resp = event_loop.run_until_complete(http_client(url))
        assert b"HTTP/1.1 200 OK" in resp
    

    This fixture can be easily overridden in any of the standard pytest locations (e.g. directly in the test file, or in conftest.py) to use a non-default event loop. This will take effect even if you're using the pytest.mark.asyncio marker and not the event_loop fixture directly.

    .. code-block:: python

    @pytest.fixture
    def event_loop():
        loop = MyCustomLoop()
        yield loop
        loop.close()
    

    If the pytest.mark.asyncio marker is applied, a pytest hook will ensure the produced loop is set as the default global loop. Fixtures depending on the event_loop fixture can expect the policy to be properly modified when they run.

    unused_tcp_port

    Finds and yields a single unused TCP port on the localhost interface. Useful for
    binding temporary test servers.
    
    ``unused_tcp_port_factory``
    

    A callable which returns a different unused TCP port each invocation. Useful when several unused TCP ports are required in a test.

    .. code-block:: python

    def a_test(unused_tcp_port_factory):
        port1, port2 = unused_tcp_port_factory(), unused_tcp_port_factory()
        ...
    

    unused_udp_port and unused_udp_port_factory

    Work just like their TCP counterparts but return unused UDP ports.
    
    
    Async fixtures
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Asynchronous fixtures are defined just like ordinary pytest fixtures, except they should be decorated with ``@pytest_asyncio.fixture``.
    
    .. code-block:: python3
    
        import pytest_asyncio
    
    
        @pytest_asyncio.fixture
        async def async_gen_fixture():
            await asyncio.sleep(0.1)
            yield "a value"
    
    
        @pytest_asyncio.fixture(scope="module")
        async def async_fixture():
            return await asyncio.sleep(0.1)
    
    All scopes are supported, but if you use a non-function scope you will need
    to redefine the ``event_loop`` fixture to have the same or broader scope.
    Async fixtures need the event loop, and so must have the same or narrower scope
    than the ``event_loop`` fixture.
    
    *auto* and *legacy* mode automatically converts async fixtures declared with the
    standard ``@pytest.fixture`` decorator to *asyncio-driven* versions.
    
    
    Markers
    -------
    
    ``pytest.mark.asyncio``
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Mark your test coroutine with this marker and pytest will execute it as an
    asyncio task using the event loop provided by the ``event_loop`` fixture. See
    the introductory section for an example.
    
    The event loop used can be overridden by overriding the ``event_loop`` fixture
    (see above).
    
    In order to make your test code a little more concise, the pytest |pytestmark|_
    feature can be used to mark entire modules or classes with this marker.
    Only test coroutines will be affected (by default, coroutines prefixed by
    ``test_``), so, for example, fixtures are safe to define.
    
    .. code-block:: python
    
        import asyncio
    
        import pytest
    
        # All test coroutines will be treated as marked.
        pytestmark = pytest.mark.asyncio
    
    
        async def test_example(event_loop):
            """No marker!"""
            await asyncio.sleep(0, loop=event_loop)
    
    In *auto* mode, the ``pytest.mark.asyncio`` marker can be omitted, the marker is added
    automatically to *async* test functions.
    
    
    .. |pytestmark| replace:: ``pytestmark``
    .. _pytestmark: http://doc.pytest.org/en/latest/example/markers.html#marking-whole-classes-or-modules
    
    Note about unittest
    -------------------
    
    Test classes subclassing the standard `unittest <https://docs.python.org/3/library/unittest.html>`__ library are not supported, users
    are recommended to use `unitest.IsolatedAsyncioTestCase <https://docs.python.org/3/library/unittest.html#unittest.IsolatedAsyncioTestCase>`__
    or an async framework such as `asynctest <https://asynctest.readthedocs.io/en/latest>`__.
    
    Changelog
    ---------
    0.17.0 (UNRELEASED)
    ~~~~~~~~~~~~~~~~~~~
    - `pytest-asyncio` no longer alters existing event loop policies. `#168 <https://github.com/pytest-dev/pytest-asyncio/issues/168>`_, `#188 <https://github.com/pytest-dev/pytest-asyncio/issues/168>`_
    - Drop support for Python 3.6
    - Fixed an issue when pytest-asyncio was used in combination with `flaky` or inherited asynchronous Hypothesis tests. `#178 <https://github.com/pytest-dev/pytest-asyncio/issues/178>`_ `#231 <https://github.com/pytest-dev/pytest-asyncio/issues/231>`_
    - Added `flaky <https://pypi.org/project/flaky/>`_ to test dependencies
    - Added ``unused_udp_port`` and ``unused_udp_port_factory`` fixtures (similar to ``unused_tcp_port`` and ``unused_tcp_port_factory`` counterparts. `#99 <https://github.com/pytest-dev/pytest-asyncio/issues/99>`_
    - Added the plugin modes: *strict*, *auto*, and *legacy*. See `documentation <https://github.com/pytest-dev/pytest-asyncio#modes>`_ for details. `#125 <https://github.com/pytest-dev/pytest-asyncio/issues/125>`_
    - Correctly process ``KeyboardInterrupt`` during async fixture setup phase `#219 <https://github.com/pytest-dev/pytest-asyncio/issues/219>`_
    
    0.16.0 (2021-10-16)
    ~~~~~~~~~~~~~~~~~~~
    - Add support for Python 3.10
    
    0.15.1 (2021-04-22)
    ~~~~~~~~~~~~~~~~~~~
    - Hotfix for errors while closing event loops while replacing them.
      `#209 <https://github.com/pytest-dev/pytest-asyncio/issues/209>`_
      `#210 <https://github.com/pytest-dev/pytest-asyncio/issues/210>`_
    
    0.15.0 (2021-04-19)
    ~~~~~~~~~~~~~~~~~~~
    - Add support for Python 3.9
    - Abandon support for Python 3.5. If you still require support for Python 3.5, please use pytest-asyncio v0.14 or earlier.
    - Set ``unused_tcp_port_factory`` fixture scope to 'session'.
      `#163 <https://github.com/pytest-dev/pytest-asyncio/pull/163>`_
    - Properly close event loops when replacing them.
      `#208 <https://github.com/pytest-dev/pytest-asyncio/issues/208>`_
    
    0.14.0 (2020-06-24)
    ~~~~~~~~~~~~~~~~~~~
    - Fix `#162 <https://github.com/pytest-dev/pytest-asyncio/issues/162>`_, and ``event_loop`` fixture behavior now is coherent on all scopes.
      `#164 <https://github.com/pytest-dev/pytest-asyncio/pull/164>`_
    
    0.12.0 (2020-05-04)
    ~~~~~~~~~~~~~~~~~~~
    - Run the event loop fixture as soon as possible. This helps with fixtures that have an implicit dependency on the event loop.
      `#156 <https://github.com/pytest-dev/pytest-asyncio/pull/156>`_
    
    0.11.0 (2020-04-20)
    ~~~~~~~~~~~~~~~~~~~
    - Test on 3.8, drop 3.3 and 3.4. Stick to 0.10 for these versions.
      `#152 <https://github.com/pytest-dev/pytest-asyncio/pull/152>`_
    - Use the new Pytest 5.4.0 Function API. We therefore depend on pytest >= 5.4.0.
      `#142 <https://github.com/pytest-dev/pytest-asyncio/pull/142>`_
    - Better ``pytest.skip`` support.
      `#126 <https://github.com/pytest-dev/pytest-asyncio/pull/126>`_
    
    0.10.0 (2019-01-08)
    ~~~~~~~~~~~~~~~~~~~~
    - ``pytest-asyncio`` integrates with `Hypothesis <https://hypothesis.readthedocs.io>`_
      to support ``@given`` on async test functions using ``asyncio``.
      `#102 <https://github.com/pytest-dev/pytest-asyncio/pull/102>`_
    - Pytest 4.1 support.
      `#105 <https://github.com/pytest-dev/pytest-asyncio/pull/105>`_
    
    0.9.0 (2018-07-28)
    ~~~~~~~~~~~~~~~~~~
    - Python 3.7 support.
    - Remove ``event_loop_process_pool`` fixture and
      ``pytest.mark.asyncio_process_pool`` marker (see
      https://bugs.python.org/issue34075 for deprecation and removal details)
    
    0.8.0 (2017-09-23)
    ~~~~~~~~~~~~~~~~~~
    - Improve integration with other packages (like aiohttp) with more careful event loop handling.
      `#64 <https://github.com/pytest-dev/pytest-asyncio/pull/64>`_
    
    0.7.0 (2017-09-08)
    ~~~~~~~~~~~~~~~~~~
    - Python versions pre-3.6 can use the async_generator library for async fixtures.
      `#62 <https://github.com/pytest-dev/pytest-asyncio/pull/62>`
    
    
    0.6.0 (2017-05-28)
    ~~~~~~~~~~~~~~~~~~
    - Support for Python versions pre-3.5 has been dropped.
    - ``pytestmark`` now works on both module and class level.
    - The ``forbid_global_loop`` parameter has been removed.
    - Support for async and async gen fixtures has been added.
      `#45 <https://github.com/pytest-dev/pytest-asyncio/pull/45>`_
    - The deprecation warning regarding ``asyncio.async()`` has been fixed.
      `#51 <https://github.com/pytest-dev/pytest-asyncio/pull/51>`_
    
    0.5.0 (2016-09-07)
    ~~~~~~~~~~~~~~~~~~
    - Introduced a changelog.
      `#31 <https://github.com/pytest-dev/pytest-asyncio/issues/31>`_
    - The ``event_loop`` fixture is again responsible for closing itself.
      This makes the fixture slightly harder to correctly override, but enables
      other fixtures to depend on it correctly.
      `#30 <https://github.com/pytest-dev/pytest-asyncio/issues/30>`_
    - Deal with the event loop policy by wrapping a special pytest hook,
      ``pytest_fixture_setup``. This allows setting the policy before fixtures
      dependent on the ``event_loop`` fixture run, thus allowing them to take
      advantage of the ``forbid_global_loop`` parameter. As a consequence of this,
      we now depend on pytest 3.0.
      `#29 <https://github.com/pytest-dev/pytest-asyncio/issues/29>`_
    
    
    0.4.1 (2016-06-01)
    ~~~~~~~~~~~~~~~~~~
    - Fix a bug preventing the propagation of exceptions from the plugin.
      `#25 <https://github.com/pytest-dev/pytest-asyncio/issues/25>`_
    
    0.4.0 (2016-05-30)
    ~~~~~~~~~~~~~~~~~~
    - Make ``event_loop`` fixtures simpler to override by closing them in the
      plugin, instead of directly in the fixture.
      `#21 <https://github.com/pytest-dev/pytest-asyncio/pull/21>`_
    - Introduce the ``forbid_global_loop`` parameter.
      `#21 <https://github.com/pytest-dev/pytest-asyncio/pull/21>`_
    
    0.3.0 (2015-12-19)
    ~~~~~~~~~~~~~~~~~~
    - Support for Python 3.5 ``async``/``await`` syntax.
      `#17 <https://github.com/pytest-dev/pytest-asyncio/pull/17>`_
    
    0.2.0 (2015-08-01)
    ~~~~~~~~~~~~~~~~~~
    - ``unused_tcp_port_factory`` fixture.
      `#10 <https://github.com/pytest-dev/pytest-asyncio/issues/10>`_
    
    
    0.1.1 (2015-04-23)
    ~~~~~~~~~~~~~~~~~~
    Initial release.
    
    
    Contributing
    ------------
    Contributions are very welcome. Tests can be run with ``tox``, please ensure
    the coverage at least stays the same before you submit a pull request.
    
    Source code(tar.gz)
    Source code(zip)
Owner
pytest-dev
pytest-dev
Playwright Python tool practice pytest pytest-bdd screen-play page-object allure cucumber-report

pytest-ui-automatic Playwright Python tool practice pytest pytest-bdd screen-play page-object allure cucumber-report How to run Run tests execute_test

moyu6027 11 Nov 8, 2022
pytest plugin providing a function to check if pytest is running.

pytest-is-running pytest plugin providing a function to check if pytest is running. Installation Install with: python -m pip install pytest-is-running

Adam Johnson 21 Nov 1, 2022
Pytest-typechecker - Pytest plugin to test how type checkers respond to code

pytest-typechecker this is a plugin for pytest that allows you to create tests t

vivax 2 Aug 20, 2022
Pytest-rich - Pytest + rich integration (proof of concept)

pytest-rich Leverage rich for richer test session output. This plugin is not pub

Bruno Oliveira 170 Dec 2, 2022
A pytest plugin to run an ansible collection's unit tests with pytest.

pytest-ansible-units An experimental pytest plugin to run an ansible collection's unit tests with pytest. Description pytest-ansible-units is a pytest

Community managed Ansible repositories 9 Dec 9, 2022
The pytest framework makes it easy to write small tests, yet scales to support complex functional testing

The pytest framework makes it easy to write small tests, yet scales to support complex functional testing for applications and libraries. An example o

pytest-dev 9.6k Jan 2, 2023
A Django plugin for pytest.

Welcome to pytest-django! pytest-django allows you to test your Django project/applications with the pytest testing tool. Quick start / tutorial Chang

pytest-dev 1.1k Dec 31, 2022
A set of pytest fixtures to test Flask applications

pytest-flask An extension of pytest test runner which provides a set of useful tools to simplify testing and development of the Flask extensions and a

pytest-dev 433 Dec 23, 2022
A command-line tool and Python library and Pytest plugin for automated testing of RESTful APIs, with a simple, concise and flexible YAML-based syntax

1.0 Release See here for details about breaking changes with the upcoming 1.0 release: https://github.com/taverntesting/tavern/issues/495 Easier API t

null 909 Dec 15, 2022
pytest splinter and selenium integration for anyone interested in browser interaction in tests

Splinter plugin for the pytest runner Install pytest-splinter pip install pytest-splinter Features The plugin provides a set of fixtures to use splin

pytest-dev 238 Nov 14, 2022
Coverage plugin for pytest.

Overview docs tests package This plugin produces coverage reports. Compared to just using coverage run this plugin does some extras: Subprocess suppor

pytest-dev 1.4k Dec 29, 2022
Thin-wrapper around the mock package for easier use with pytest

pytest-mock This plugin provides a mocker fixture which is a thin-wrapper around the patching API provided by the mock package: import os class UnixF

pytest-dev 1.5k Jan 5, 2023
pytest plugin for distributed testing and loop-on-failures testing modes.

xdist: pytest distributed testing plugin The pytest-xdist plugin extends pytest with some unique test execution modes: test run parallelization: if yo

pytest-dev 1.1k Dec 30, 2022
Plugin for generating HTML reports for pytest results

pytest-html pytest-html is a plugin for pytest that generates a HTML report for test results. Resources Documentation Release Notes Issue Tracker Code

pytest-dev 548 Dec 28, 2022
Mypy static type checker plugin for Pytest

pytest-mypy Mypy static type checker plugin for pytest Features Runs the mypy static type checker on your source files as part of your pytest test run

Dan Bader 218 Jan 3, 2023
:game_die: Pytest plugin to randomly order tests and control random.seed

pytest-randomly Pytest plugin to randomly order tests and control random.seed. Features All of these features are on by default but can be disabled wi

pytest-dev 471 Dec 30, 2022
A rewrite of Python's builtin doctest module (with pytest plugin integration) but without all the weirdness

The xdoctest package is a re-write of Python's builtin doctest module. It replaces the old regex-based parser with a new abstract-syntax-tree based pa

Jon Crall 174 Dec 16, 2022
Selects tests affected by changed files. Continous test runner when used with pytest-watch.

This is a pytest plug-in which automatically selects and re-executes only tests affected by recent changes. How is this possible in dynamic language l

Tibor Arpas 614 Dec 30, 2022
It helps to use fixtures in pytest.mark.parametrize

pytest-lazy-fixture Use your fixtures in @pytest.mark.parametrize. Installation pip install pytest-lazy-fixture Usage import pytest @pytest.fixture(p

Marsel Zaripov 299 Dec 24, 2022