pytest-twisted

1.14.3 · active · verified Thu Apr 16

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import pytest
from twisted.internet.defer import Deferred
from pytest_twisted import inlineCallbacks

@inlineCallbacks
def test_deferred_returns_value():
    d = Deferred()
    d.callback('hello')
    result = yield d
    assert result == 'hello'

@pytest.mark.reactor_default # Or specify --reactor=asyncio in pytest command
@inlineCallbacks
def test_reactor_is_running():
    from twisted.internet import reactor
    assert reactor.running

# To run this, save as test_example.py and run: pytest test_example.py

view raw JSON →