pytest-twisted is a plugin for the pytest testing framework that facilitates testing code built with the Twisted asynchronous networking framework. It allows pytest test functions to return Twisted Deferred objects, ensuring that tests wait for asynchronous operations to complete, and manages the Twisted reactor lifecycle within the test suite. The library is actively maintained, with its current version being 1.14.3.
pip install pytest-twistedVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to write a basic test using `pytest-twisted`. It shows a test function decorated with `pytest_twisted.inlineCallbacks` that yields a Twisted Deferred and asserts its result. A second example checks if the Twisted reactor is running within the test context. You can specify a reactor type using `--reactor` (e.g., `--reactor=asyncio`) when running pytest.
Replace `returnValue(value)` with `return value` in `inlineCallbacks`-decorated functions and generators. Ensure `except:` clauses are changed to `except Exception:` to avoid catching `returnValue`'s internal `BaseException` subclass.
Explicitly set the `asyncio` event loop policy to `asyncio.WindowsSelectorEventLoopPolicy` early in your test suite, typically in a `conftest.py` file, to use the selector loop.
Example `conftest.py` snippet:
```python
import sys
import pytest
import asyncio
@pytest.hookimpl(tryfirst=True)
def pytest_configure(config):
if (config.getoption("reactor", "default") == "asyncio" and sys.platform == 'win32' and sys.version_info >= (3, 8)):
selector_policy = asyncio.WindowsSelectorEventLoopPolicy()
asyncio.set_event_loop_policy(selector_policy)
```Always use the `inlineCallbacks` and `ensureDeferred` decorators provided by `pytest_twisted` (i.e., `from pytest_twisted import inlineCallbacks`) when writing tests with fixtures.
It is generally recommended to separate tests written for `twisted.trial` from `pytest`-style tests that leverage `pytest-twisted`, or to ensure that trial tests do not attempt to manage the reactor in a way that conflicts with `pytest-twisted`'s reactor management. `pytest-twisted` is primarily designed for native `pytest` functions returning `Deferreds`.
Ensure `pytest-twisted` is updated to the latest version (1.14.2 or higher) to ensure compatibility with `pytest` 8.2.0 and later.
Upgrade `pytest` to at least 8.4.1, which includes fixes for compatibility with Twisted 25+.