### Request Custom Event Loop Factory in Tests Source: https://pytest-asyncio.readthedocs.io/en/stable/how-to-guides/configure_loop_factories_per_test.html These are example tests demonstrating how to utilize the configured event loop factories. `test_runs_with_default_factory_only` runs with the default factory, while `test_runs_with_custom_factory_only` requests the 'custom' factory by depending on the `requires_custom_loop` fixture. ```python import pytest @pytest.mark.asyncio async def test_runs_with_default_factory_only(): pass @pytest.mark.asyncio async def test_runs_with_custom_factory_only(requires_custom_loop): pass ``` -------------------------------- ### Provide Multiple Event Loop Policies via Fixture Parameters Source: https://pytest-asyncio.readthedocs.io/en/stable/reference/fixtures/index.html This example shows how to provide multiple event loop policies using fixture parameters. pytest-asyncio will run the tests once for each provided policy, allowing for comprehensive testing across different loop configurations. The deprecation warning is also handled. ```python import asyncio import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) from asyncio import DefaultEventLoopPolicy import pytest class CustomEventLoopPolicy(DefaultEventLoopPolicy): pass @pytest.fixture( params=( DefaultEventLoopPolicy(), CustomEventLoopPolicy(), ), ) def event_loop_policy(request): return request.param @pytest.mark.asyncio @pytest.mark.filterwarnings("ignore::DeprecationWarning") async def test_uses_custom_event_loop_policy(): assert isinstance(asyncio.get_event_loop_policy(), DefaultEventLoopPolicy) ``` -------------------------------- ### Parametrize event_loop_policy for multiple event loops Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/multiple_loops.rst.txt This example shows how to parametrize the event_loop_policy fixture to run all async tests multiple times, once for each specified event loop. This is useful for ensuring compatibility across different event loop implementations. ```python import asyncio import pytest @pytest.fixture(params=["asyncio", "uvloop"]) async def event_loop_policy(request): if request.param == "asyncio": policy = asyncio.DefaultEventLoopPolicy() elif request.param == "uvloop": import uvloop policy = uvloop.EventLoopPolicy() else: raise ValueError("Unknown event loop policy") asyncio.set_event_loop_policy(policy) loop = asyncio.get_event_loop_policy().new_event_loop() yield loop loop.close() async def test_example(): await asyncio.sleep(0.01) assert True ``` -------------------------------- ### Pytest Collection Output Source: https://pytest-asyncio.readthedocs.io/en/stable/concepts.html Example output of `pytest --collect-only` showing how pytest discovers test modules and functions. ```text ``` -------------------------------- ### Parametrizing event_loop_policy for multiple event loops Source: https://pytest-asyncio.readthedocs.io/en/stable/how-to-guides/multiple_loops.html This example demonstrates how to parametrize the `event_loop_policy` fixture to run all async tests multiple times, once for each provided event loop policy. It includes a custom policy and a test to verify its usage. Note that overriding `event_loop_policy` is deprecated. ```python import asyncio import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) from asyncio import DefaultEventLoopPolicy import pytest class CustomEventLoopPolicy(DefaultEventLoopPolicy): pass @pytest.fixture( scope="session", params=( CustomEventLoopPolicy(), CustomEventLoopPolicy(), ), ) def event_loop_policy(request): return request.param @pytest.mark.asyncio @pytest.mark.filterwarnings("ignore::DeprecationWarning") async def test_uses_custom_event_loop_policy(): assert isinstance(asyncio.get_event_loop_policy(), CustomEventLoopPolicy) ``` -------------------------------- ### Implement pytest_asyncio_loop_factories Hook Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/custom_loop_factory.rst.txt Implement the `pytest_asyncio_loop_factories` hook in your `conftest.py` to define custom event loop factories. This example shows how to provide both the standard library loop and a custom `CustomEventLoop`. ```python import asyncio import pytest class CustomEventLoop(asyncio.SelectorEventLoop): pass def pytest_asyncio_loop_factories(config, item): return { "stdlib": asyncio.new_event_loop, "custom": CustomEventLoop, } ``` -------------------------------- ### Basic Async Test Function Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/concepts.rst.txt A simple asynchronous test function that will be collected and run by pytest. This example demonstrates a test that runs within an event loop. ```python async def test_runs_in_a_loop(): await asyncio.sleep(0.1) assert True ``` -------------------------------- ### Run Module Tests in Same Event Loop Source: https://pytest-asyncio.readthedocs.io/en/stable/how-to-guides/run_module_tests_in_same_loop.html Mark your module with `pytest.mark.asyncio(loop_scope="module")` to run all tests within that module in the same event loop. This is useful for tests that rely on shared loop state or for simplifying test setup. ```python import asyncio import pytest pytestmark = pytest.mark.asyncio(loop_scope="module") loop: asyncio.AbstractEventLoop async def test_remember_loop(): global loop loop = asyncio.get_running_loop() async def test_assert_same_loop(): global loop assert asyncio.get_running_loop() is loop ``` -------------------------------- ### Configure Session-Scoped Loop in setup.cfg Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/change_default_test_loop.rst.txt Sets the default event loop scope to 'session' for all tests when using setup.cfg. ```ini [tool:pytest] asyncio_default_test_loop_scope = session ``` -------------------------------- ### Configure setup.cfg for Session-Scoped Loop Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/change_default_fixture_loop.rst.txt Configure your setup.cfg file to set the default event loop scope for all fixtures to session-scoped. This method is an alternative to using pytest.ini or pyproject.toml. ```ini [tool:pytest] asyncio_default_fixture_loop_scope = session ``` -------------------------------- ### Marking a Test Package for a Shared Event Loop Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/run_package_tests_in_same_loop.rst.txt Add this marker to the `__init__.py` file of your test package to run all tests within that package in the same event loop. This is useful for tests that require a consistent event loop state across the entire package. ```python import pytest pytestmark = pytest.mark.asyncio(loop_scope="package") ``` -------------------------------- ### Set asyncio mode via command line Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/configuration.rst.txt Use the '--asyncio-mode' command-line option to specify the asyncio mode, such as 'strict'. ```bash $ pytest tests --asyncio-mode=strict ``` -------------------------------- ### test_extra_loop_factories.py: Request custom loop factory via parametrization Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/configure_loop_factories_per_test.rst.txt This test file demonstrates how to request a specific event loop factory by parametrizing tests. It shows how tests can be configured to run with either the default or a custom factory based on the parametrization. ```python import pytest @pytest.mark.parametrize("loop_factory", ["default"], indirect=True) def test_runs_with_default_factory_only(loop_factory): assert loop_factory.is_running() @pytest.mark.parametrize("loop_factory", ["custom"], indirect=True) def test_runs_with_custom_factory_only(loop_factory): assert loop_factory.is_running() ``` -------------------------------- ### Using unused_tcp_port_factory Fixture Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/fixtures/index.rst.txt Illustrates the usage of the unused_tcp_port_factory fixture to obtain multiple distinct unused TCP ports for testing network servers. Each call to the factory yields a new port. ```python def a_test(unused_tcp_port_factory): _port1, _port2 = unused_tcp_port_factory(), unused_tcp_port_factory() ``` -------------------------------- ### Async Fixtures with pytest_asyncio.fixture Source: https://pytest-asyncio.readthedocs.io/en/stable/reference/decorators/index.html Demonstrates the basic usage of the @pytest_asyncio.fixture decorator for coroutines. Each fixture runs in a fresh event loop for every test function by default. ```python import pytest_asyncio @pytest_asyncio.fixture async def fixture_runs_in_fresh_loop_for_every_function(): ... ``` -------------------------------- ### Selecting a subset of loop factories for a test Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/run_test_with_specific_loop_factories.rst.txt Runs a test function using only the 'my_loop_factory' and 'another_loop_factory' event loop factories, as defined in conftest.py. ```python import pytest @pytest.mark.parametrize("loop_factory", ["my_loop_factory", "another_loop_factory"], indirect=True) async def test_specific_loop_factories(loop_factory): """Test that runs with specific loop factories.""" pass ``` -------------------------------- ### Using @pytest_asyncio.fixture Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/decorators/index.rst.txt Demonstrates how to use the @pytest_asyncio.fixture decorator with coroutines and async generators. This snippet requires importing pytest_asyncio. ```python import pytest import pytest_asyncio @pytest_asyncio.fixture async def async_fixture(): return 5 @pytest_asyncio.fixture(scope="module") async def async_module_fixture(): return 10 @pytest_asyncio.fixture async def async_generator_fixture(): yield 15 async def test_async_fixture(async_fixture): assert async_fixture == 5 async def test_async_module_fixture(async_module_fixture): assert async_module_fixture == 10 async def test_async_generator_fixture(async_generator_fixture): assert async_generator_fixture == 15 ``` -------------------------------- ### Define uvloop loop factory using pytest_asyncio_loop_factories Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/uvloop.rst.txt Configure uvloop as a loop factory by mapping a name (e.g., 'uvloop') to `uvloop.new_event_loop` in your `conftest.py`. This is the recommended approach for modern Python versions. ```python import uvloop def pytest_asyncio_loop_factories(config, item): return { "uvloop": uvloop.new_event_loop, } ``` -------------------------------- ### conftest.py: Configure loop factories based on test item fixtures Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/configure_loop_factories_per_test.rst.txt This snippet shows how to implement the `pytest_asyncio_loop_factories` hook in `conftest.py`. It inspects the test item's fixture names to conditionally provide different event loop factory mappings. ```python import pytest @pytest.hookimpl(hookwrapper=True) def pytest_asyncio_loop_factories(item): outcome = yield factories = outcome.get_result() if "custom" in item.fixturenames: factories["custom"] = "tests.custom_loop.custom_loop_factory" else: factories["default"] = "tests.default_loop.default_loop_factory" return factories ``` -------------------------------- ### Using ``pytestmark`` for ``pytest.mark.asyncio`` Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/markers/index.rst.txt Assign the ``pytest.mark.asyncio`` marker to the ``pytestmark`` attribute of a class or module to apply it to all async test functions within that scope. ```python import pytest @pytest.mark.asyncio class TestClass: async def test_one(self): assert True async def test_two(self): assert True ``` -------------------------------- ### Async Fixtures with Custom Loop and Caching Scopes Source: https://pytest-asyncio.readthedocs.io/en/stable/reference/decorators/index.html Shows how to configure @pytest_asyncio.fixture with specific loop scopes (e.g., 'session') and caching scopes (e.g., 'module'). The event loop scope must be larger than or equal to the caching scope. ```python import pytest_asyncio @pytest_asyncio.fixture(loop_scope="session", scope="module") async def fixture_runs_in_session_loop_once_per_module(): ... ``` ```python import pytest_asyncio @pytest_asyncio.fixture(loop_scope="module", scope="module") async def fixture_runs_in_module_loop_once_per_module(): ... ``` ```python import pytest_asyncio @pytest_asyncio.fixture(loop_scope="module") async def fixture_runs_in_module_loop_once_per_function(): ... ``` -------------------------------- ### Using event_loop_policy Fixture Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/fixtures/index.rst.txt Demonstrates how to use the event_loop_policy fixture to obtain the current event loop policy. This fixture is automatically applied to all pytest-asyncio tests. ```python import asyncio def test_event_loop_policy(event_loop_policy): assert isinstance(event_loop_policy, asyncio.AbstractEventLoopPolicy) ``` -------------------------------- ### Auto Mode Configuration (TOML) Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/concepts.rst.txt Sets pytest-asyncio to auto mode using a TOML configuration file. In this mode, pytest-asyncio automatically marks async test functions and takes ownership of all async fixtures. ```toml [tool.pytest.ini_options] asyncio_mode = "auto" ``` -------------------------------- ### Strict Mode Configuration (TOML) Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/concepts.rst.txt Sets pytest-asyncio to strict mode using a TOML configuration file. In this mode, only tests marked with 'asyncio' and async fixtures with '@pytest_asyncio.fixture' are handled by pytest-asyncio. ```toml [tool.pytest.ini_options] asyncio_mode = "strict" ``` -------------------------------- ### Run tests with specific event loop factories Source: https://pytest-asyncio.readthedocs.io/en/stable/how-to-guides/run_test_with_specific_loop_factories.html This snippet demonstrates how to use the `pytest.mark.asyncio` marker with the `loop_factories` argument to specify which event loop factories a test should run with. The first test runs with all configured factories, while the second runs only with the 'custom' factory. ```python import pytest @pytest.mark.asyncio async def test_runs_with_every_configured_factory(): pass @pytest.mark.asyncio(loop_factories=["custom"]) async def test_runs_with_only_custom_factory(): pass ``` -------------------------------- ### Configure Session-Scoped Loop in pyproject.toml Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/change_default_test_loop.rst.txt Sets the default event loop scope to 'session' for all tests when using pyproject.toml. ```toml [tool.pytest.ini_options] asyncio_default_test_loop_scope = "session" ``` -------------------------------- ### Enable asyncio debug mode via command line Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/configuration.rst.txt Use the '--asyncio-debug' command-line option to enable asyncio debug mode when running pytest. ```bash $ pytest tests --asyncio-debug ``` -------------------------------- ### conftest.py with two named factories Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/run_test_with_specific_loop_factories.rst.txt Defines two named event loop factories, 'my_loop_factory' and 'another_loop_factory', for pytest-asyncio to use. ```python import pytest @pytest.fixture def my_loop_factory(): """A simple event loop factory.""" return asyncio.new_event_loop() @pytest.fixture def another_loop_factory(): """Another simple event loop factory.""" return asyncio.new_event_loop() ``` -------------------------------- ### Define custom event loop factories in conftest.py Source: https://pytest-asyncio.readthedocs.io/en/stable/how-to-guides/run_test_with_specific_loop_factories.html This snippet shows how to define custom event loop factories in your `conftest.py` file. It includes a custom event loop class and a `pytest_asyncio_loop_factories` hook that returns two named factories: 'default' and 'custom'. ```python import asyncio class CustomEventLoop(asyncio.SelectorEventLoop): pass def pytest_asyncio_loop_factories(config, item): return { "default": asyncio.new_event_loop, "custom": CustomEventLoop, } ``` -------------------------------- ### Sequential Async Tests with Sleep Source: https://pytest-asyncio.readthedocs.io/en/stable/concepts.html Two asynchronous tests that demonstrate sequential execution by including `asyncio.sleep`. Each test runs in its own event loop, and they execute one after the other. ```python import asyncio import pytest @pytest.mark.asyncio async def test_first(): await asyncio.sleep(2) # Takes 2 seconds @pytest.mark.asyncio async def test_second(): await asyncio.sleep(2) # Takes 2 seconds ``` -------------------------------- ### Sequential Execution of Async Tests Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/concepts.rst.txt Demonstrates that pytest-asyncio runs async tests sequentially within their assigned event loops, similar to how pytest handles synchronous tests. Each test completes before the next begins. ```python async def test_one(): await asyncio.sleep(0.1) assert True async def test_two(): await asyncio.sleep(0.1) assert True ``` -------------------------------- ### Configure pyproject.toml for Session-Scoped Loop Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/change_default_fixture_loop.rst.txt This snippet configures pytest to use a session-scoped event loop for all fixtures by default, using the pyproject.toml file. Ensure this is placed within the [tool.pytest.ini_options] section. ```toml [tool.pytest.ini_options] asyncio_default_fixture_loop_scope = "session" ``` -------------------------------- ### Marking a Module for Module-Scoped Event Loop Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/run_module_tests_in_same_loop.rst.txt Add this `pytestmark` statement to the top of your test module to run all async tests within it in the same event loop. This is useful for tests that need to share state or for performance optimization. ```python import pytest pytestmark = pytest.mark.asyncio(loop_scope="module") async def test_one(): pass async def test_two(): pass ``` -------------------------------- ### Module-Scoped Event Loop for Tests Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/concepts.rst.txt Configures two tests to share the event loop provided by the Module collector using the 'asyncio' mark with loop_scope='module'. This is recommended for neighboring tests. ```python @pytest.mark.asyncio(loop_scope='module') async def test_runs_in_module_loop_one(): await asyncio.sleep(0.1) assert True @pytest.mark.asyncio(loop_scope='module') async def test_runs_in_module_loop_two(): await asyncio.sleep(0.1) assert True ``` -------------------------------- ### Module-Scoped Event Loop Fixture Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/change_fixture_loop.rst.txt This fixture is configured to run within a module-scoped event loop. Use `loop_scope='module'` to achieve this. ```python import pytest @pytest.fixture(scope='module', loop_scope='module') async def module_scoped_fixture(): return 42 ``` -------------------------------- ### Define Custom Event Loop Factory Based on Item Fixtures Source: https://pytest-asyncio.readthedocs.io/en/stable/how-to-guides/configure_loop_factories_per_test.html This snippet shows how to implement the `pytest_asyncio_loop_factories` hook in `conftest.py`. It inspects the test item's fixture names to decide which event loop factories to provide. If the 'requires_custom_loop' fixture is present, it offers a 'custom' factory using `CustomEventLoop`; otherwise, it defaults to 'default' using `asyncio.new_event_loop`. ```python import asyncio import pytest class CustomEventLoop(asyncio.SelectorEventLoop): pass @pytest.fixture def requires_custom_loop(): pass def pytest_asyncio_loop_factories(config, item): if "requires_custom_loop" in item.fixturenames: return {"custom": CustomEventLoop} return {"default": asyncio.new_event_loop} ``` -------------------------------- ### Pytest Configuration for Strict Mode Source: https://pytest-asyncio.readthedocs.io/en/stable/concepts.html Configuring pytest-asyncio to use 'strict' mode via `pytest.ini`. In strict mode, only tests explicitly marked with `@pytest.mark.asyncio` are run. ```ini [tool.pytest.ini_options] asyncio_mode = "strict" ``` -------------------------------- ### Set asyncio mode in pytest.ini Source: https://pytest-asyncio.readthedocs.io/en/stable/reference/configuration.html Configure the `asyncio_mode` in your `pytest.ini` file. The default is `strict` if not specified. ```ini # pytest.ini [pytest] asyncio_mode = auto ``` -------------------------------- ### Module-scoped event loop fixture Source: https://pytest-asyncio.readthedocs.io/en/stable/how-to-guides/change_fixture_loop.html This fixture is configured to run within a module-scoped event loop. It retrieves and returns the currently running event loop. ```python import asyncio import pytest import pytest_asyncio @pytest_asyncio.fixture(loop_scope="module") async def current_loop(): return asyncio.get_running_loop() @pytest.mark.asyncio(loop_scope="module") async def test_runs_in_module_loop(current_loop): assert current_loop is asyncio.get_running_loop() ``` -------------------------------- ### Pytest Configuration for Auto Mode Source: https://pytest-asyncio.readthedocs.io/en/stable/concepts.html Configuring pytest-asyncio to use 'auto' mode via `pytest.ini`. In auto mode, all async test functions are automatically marked and async fixtures are handled. ```ini [tool.pytest.ini_options] asyncio_mode = "auto" ``` -------------------------------- ### Asyncio Test Function with pytest-asyncio Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/index.rst.txt This snippet demonstrates how to mark an asynchronous function as a test using the @pytest.mark.asyncio decorator. It shows a typical pattern for awaiting an asynchronous operation within a test and asserting its result. ```python @pytest.mark.asyncio async def test_some_asyncio_code(): res = await library.do_something() assert b"expected result" == res ``` -------------------------------- ### Mark Async Test with Loop Scope Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/migrate_from_0_21.rst.txt Use this marker to configure the loop scope for an individual asynchronous test. This ensures the test uses a loop with the specified scope. ```python import pytest @pytest.mark.asyncio(loop_scope="session") async def test_my_async_function(): pass ``` -------------------------------- ### Parametrize an Asynchronous Test Function Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/parametrize_with_asyncio.rst.txt Apply both pytest.mark.asyncio and pytest.mark.parametrize to an asynchronous test function. Each test case will run sequentially. ```python import pytest @pytest.mark.asyncio @pytest.mark.parametrize("input, expected", [(1, 2), (2, 3), (3, 4)]) async def test_example(input, expected): assert input + 1 == expected ``` -------------------------------- ### Using ``pytest.mark.asyncio`` as a decorator Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/markers/index.rst.txt Apply the ``pytest.mark.asyncio`` decorator directly above an async test function to mark it for execution within an asyncio event loop. ```python import pytest @pytest.mark.asyncio async def test_example(): assert True ``` -------------------------------- ### Basic Async Test Function Source: https://pytest-asyncio.readthedocs.io/en/stable/concepts.html A simple asynchronous test function that asserts the presence of a running event loop. This requires the `@pytest.mark.asyncio` marker. ```python import asyncio import pytest @pytest.mark.asyncio async def test_runs_in_a_loop(): assert asyncio.get_running_loop() ``` -------------------------------- ### Configure default loop scope Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/migrate_from_0_23.rst.txt Set the `asyncio_default_fixture_loop_scope` configuration option in `pytest.ini` or `pyproject.toml` to a specific loop scope (e.g., 'function') if you haven't explicitly set `loop_scope` for individual fixtures. This addresses deprecation warnings. ```ini [pytest] asyncio_default_fixture_loop_scope = function ``` -------------------------------- ### Mark Async Fixture with Loop Scope Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/migrate_from_0_21.rst.txt Use this decorator to configure the loop scope for an individual asynchronous fixture. This allows fine-grained control over the event loop's lifecycle for fixtures. ```python import pytest_asyncio @pytest_asyncio.fixture(loop_scope="session") async def my_async_fixture(): pass ``` -------------------------------- ### Configure pytest.ini for Session-Scoped Loop Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/change_default_fixture_loop.rst.txt Use this snippet in your pytest.ini file to set all fixtures to use a session-scoped event loop by default. This is useful for managing the lifecycle of the event loop across an entire test session. ```ini [pytest] asyncio_default_fixture_loop_scope = session ``` -------------------------------- ### Set asyncio mode in pytest.ini Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/configuration.rst.txt Configure the 'asyncio_mode' in your pytest.ini file. The 'auto' mode is shown here. ```ini # pytest.ini [pytest] asyncio_mode = auto ``` -------------------------------- ### Set loop_scope for async fixtures Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/migrate_from_0_23.rst.txt Replace existing fixture decorators with `pytest_asyncio.fixture` and specify the `loop_scope` to match the desired scope. This ensures proper event loop management for async fixtures. ```python import pytest_asyncio @pytest_asyncio.fixture(loop_scope="session", scope="session") async def my_async_fixture(): pass ``` -------------------------------- ### Mark all async tests in a module Source: https://pytest-asyncio.readthedocs.io/en/stable/reference/markers/index.html Set `pytestmark = pytest.mark.asyncio` at the module level to automatically mark all async test functions within that module. ```python import asyncio import pytest # Marks all test coroutines in this module pytestmark = pytest.mark.asyncio async def test_runs_in_asyncio_event_loop(): assert asyncio.get_running_loop() ``` -------------------------------- ### Configure Session-Scoped Loop in pytest.ini Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/change_default_test_loop.rst.txt Sets the default event loop scope to 'session' for all tests when using pytest.ini. ```ini [pytest] asyncio_default_test_loop_scope = session ``` -------------------------------- ### Shared event loop for tests in a module Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/markers/index.rst.txt Use ``loop_scope='module'`` with the ``pytest.mark.asyncio`` marker to provide a single asyncio event loop for all async tests defined within the same module. ```python import pytest @pytest.mark.asyncio(loop_scope='module') async def test_one(): assert True async def test_two(): assert True ``` -------------------------------- ### Override event_loop_policy for Custom Event Loop Source: https://pytest-asyncio.readthedocs.io/en/stable/reference/fixtures/index.html This snippet demonstrates how to override the default event_loop_policy fixture to use a custom event loop policy. It's useful when specific event loop configurations are needed for tests. Note the deprecation warning and the recommended use of hooks. ```python import asyncio import warnings with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) from asyncio import DefaultEventLoopPolicy import pytest class CustomEventLoopPolicy(DefaultEventLoopPolicy): pass @pytest.fixture(scope="module") def event_loop_policy(request): return CustomEventLoopPolicy() @pytest.mark.asyncio(loop_scope="module") @pytest.mark.filterwarnings("ignore::DeprecationWarning") async def test_uses_custom_event_loop_policy(): assert isinstance(asyncio.get_event_loop_policy(), CustomEventLoopPolicy) ``` -------------------------------- ### Shared event loop for tests across packages (session scope) Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/markers/index.rst.txt Set ``loop_scope='session'`` on the ``pytest.mark.asyncio`` marker to enable sharing of a single asyncio event loop across all async tests, regardless of their package or module. ```python import pytest @pytest.mark.asyncio(loop_scope='session') async def test_session_scoped_one(): assert True async def test_session_scoped_two(): assert True ``` -------------------------------- ### Shared event loop for tests in a class Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/markers/index.rst.txt Configure the ``pytest.mark.asyncio`` marker with ``loop_scope='class'`` to ensure all async tests within a single class share the same asyncio event loop. ```python import pytest @pytest.mark.asyncio(loop_scope='class') class TestClassScopedLoop: async def test_one(self): assert True async def test_two(self): assert True ``` -------------------------------- ### Enable asyncio debug mode in pytest.ini Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/reference/configuration.rst.txt Set the 'asyncio_debug' option to 'true' in your pytest.ini file to enable asyncio debug mode for the default event loop. ```ini # pytest.ini [pytest] asyncio_debug = true ``` -------------------------------- ### Update pytest.mark.asyncio marker Source: https://pytest-asyncio.readthedocs.io/en/stable/_sources/how-to-guides/migrate_from_0_23.rst.txt Change the `scope` argument in `pytest.mark.asyncio` to `loop_scope` to align with the updated API. This resolves deprecation warnings related to the marker's arguments. ```python import pytest @pytest.mark.asyncio(loop_scope="session") async def test_something(): pass ```