{"id":8544,"library":"pytest-twisted","title":"pytest-twisted","description":"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.","status":"active","version":"1.14.3","language":"en","source_language":"en","source_url":"https://github.com/pytest-dev/pytest-twisted","tags":["pytest","twisted","testing","async","deferred","asynchronous"],"install":[{"cmd":"pip install pytest-twisted","lang":"bash","label":"Install stable release"}],"dependencies":[{"reason":"Core testing framework that pytest-twisted extends.","package":"pytest","optional":false},{"reason":"The asynchronous networking framework that pytest-twisted provides testing utilities for.","package":"Twisted","optional":false},{"reason":"Required by pytest-twisted for managing greenlets within Twisted's cooperative multitasking model.","package":"greenlet","optional":false}],"imports":[{"note":"When using `inlineCallbacks` in pytest test functions, especially with fixtures, use the version provided by `pytest-twisted` to ensure proper integration with pytest's test collection and fixture management.","wrong":"from twisted.internet.defer import inlineCallbacks","symbol":"inlineCallbacks","correct":"from pytest_twisted import inlineCallbacks"},{"note":"Similar to `inlineCallbacks`, if you are decorating pytest test functions with `ensureDeferred`, use the version from `pytest_twisted` for correct behavior with fixtures.","wrong":"from twisted.internet.defer import ensureDeferred","symbol":"ensureDeferred","correct":"from pytest_twisted import ensureDeferred"},{"note":"The main module, often used for configuring the reactor or accessing utility functions if needed explicitly in `conftest.py` or setup code.","symbol":"pytest_twisted","correct":"import pytest_twisted"}],"quickstart":{"code":"import pytest\nfrom twisted.internet.defer import Deferred\nfrom pytest_twisted import inlineCallbacks\n\n@inlineCallbacks\ndef test_deferred_returns_value():\n    d = Deferred()\n    d.callback('hello')\n    result = yield d\n    assert result == 'hello'\n\n@pytest.mark.reactor_default # Or specify --reactor=asyncio in pytest command\n@inlineCallbacks\ndef test_reactor_is_running():\n    from twisted.internet import reactor\n    assert reactor.running\n\n# To run this, save as test_example.py and run: pytest test_example.py","lang":"python","description":"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."},"warnings":[{"fix":"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.","message":"`twisted.internet.defer.returnValue` is deprecated since Twisted 24.7.0. Users should migrate to using standard Python `return` statements in `inlineCallbacks` generators.","severity":"deprecated","affected_versions":"Twisted >= 24.7.0, pytest-twisted < 1.14.3 (though 1.14.3 updated for it, user code might still use old pattern)"},{"fix":"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.\n\nExample `conftest.py` snippet:\n```python\nimport sys\nimport pytest\nimport asyncio\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_configure(config):\n    if (config.getoption(\"reactor\", \"default\") == \"asyncio\" and sys.platform == 'win32' and sys.version_info >= (3, 8)):\n        selector_policy = asyncio.WindowsSelectorEventLoopPolicy()\n        asyncio.set_event_loop_policy(selector_policy)\n```","message":"On Windows with Python 3.8+ and the `asyncio` reactor, you might encounter a `NotImplementedError` due to asyncio's default proactor loop not fully supporting Twisted's `asyncio` integration.","severity":"gotcha","affected_versions":"Python >= 3.8 on Windows with `--reactor=asyncio`"},{"fix":"Always use the `inlineCallbacks` and `ensureDeferred` decorators provided by `pytest_twisted` (i.e., `from pytest_twisted import inlineCallbacks`) when writing tests with fixtures.","message":"Directly using `twisted.internet.defer.inlineCallbacks` or `twisted.internet.defer.ensureDeferred` as decorators for pytest test functions that rely on fixtures can lead to unexpected behavior or failures.","severity":"gotcha","affected_versions":"All versions"},{"fix":"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`.","message":"Mixing `pytest` tests with `twisted.trial.unittest.TestCase` in the same test run, especially when using the `--reactor=asyncio` option, can result in a `RuntimeError: This event loop is already running`.","severity":"gotcha","affected_versions":"All versions, particularly when using `--reactor=asyncio`"},{"fix":"Ensure `pytest-twisted` is updated to the latest version (1.14.2 or higher) to ensure compatibility with `pytest` 8.2.0 and later.","message":"Older versions of `pytest-twisted` might have compatibility issues with newer `pytest` releases (e.g., `pytest` 8.2.0+).","severity":"breaking","affected_versions":"pytest-twisted < 1.14.2 with pytest >= 8.2.0"},{"fix":"Upgrade `pytest` to at least 8.4.1, which includes fixes for compatibility with Twisted 25+.","message":"The behavior of `pytest.skip()` in `twisted.trial` unittests changed with Twisted 25.5.0, potentially causing unhandled exceptions when `pytest-twisted` is used.","severity":"breaking","affected_versions":"Twisted >= 25.5.0 with pytest-twisted (specifically, older pytest versions with this Twisted version)"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Isolate `twisted.trial` tests from `pytest-twisted` tests or avoid using `asyncio` reactor when running mixed tests. `pytest-twisted` is optimized for `pytest`-style tests returning `Deferreds`.","cause":"Attempting to run `twisted.trial.unittest.TestCase` tests alongside standard `pytest-twisted` tests, particularly when the `asyncio` reactor is enabled, leading to conflicting event loop management.","error":"RuntimeError: This event loop is already running"},{"fix":"Force the use of the `asyncio.WindowsSelectorEventLoopPolicy` in a `conftest.py` file to ensure the selector loop is used. Refer to the 'Gotcha' warning for a code example.","cause":"The default `asyncio` proactor event loop on Windows in Python 3.8+ is not fully compatible with Twisted's `asyncio` reactor implementation.","error":"NotImplementedError (typically on Windows with Python 3.8+ and asyncio reactor)"},{"fix":"Ensure all `Deferred` objects have appropriate `addErrback` handlers to catch and log exceptions. Use Twisted's debugging tools (like `Deferred.debug(True)`) during development to identify unhandled errors.","cause":"An unhandled exception within a `Deferred` chain (e.g., a missing `errback` handler) can prevent the Deferred from firing, causing `pytest-twisted` to wait indefinitely.","error":"Tests hang indefinitely without error output."},{"fix":"Replace all instances of `returnValue(value)` with `return value` in `inlineCallbacks`-decorated functions.","cause":"Using `twisted.internet.defer.returnValue()` within `inlineCallbacks` generators instead of a plain `return` statement, which is no longer recommended in recent Twisted versions.","error":"DeprecationWarning: returnValue was deprecated in Twisted 24.7.0; please use standard return statement instead."}]}