Package: pytest-twisted
Authors:Ralf Schmitt, Kyle Altendorf, Victor TitorVersion:1.14.0Date:2022-10-16Download:https://pypi.python.org/pypi/pytest-twisted#downloadsCode:https://github.com/pytest-dev/pytest-twistedpytest-twisted is a plugin for pytest, which allows to test code,
which uses the twisted framework. test functions can return Deferred
objects and pytest will wait for their completion with this plugin.NOTICE: Python 3.8 with asyncio supportIn Python 3.8, asyncio changed the default loop implementation to use
their proactor.  The proactor does not implement some methods used by
Twisted’s asyncio support.  The result is aNotImplementedErrorexception such as below.<snip>File"c:\projects\pytest-twisted\.tox\py38-asyncioreactor\lib\site-packages\twisted\internet\asyncioreactor.py", line320, ininstallreactor=AsyncioSelectorReactor(eventloop)File"c:\projects\pytest-twisted\.tox\py38-asyncioreactor\lib\site-packages\twisted\internet\asyncioreactor.py", line69, in__init__super().__init__()File"c:\projects\pytest-twisted\.tox\py38-asyncioreactor\lib\site-packages\twisted\internet\base.py", line571, in__init__self.installWaker()File"c:\projects\pytest-twisted\.tox\py38-asyncioreactor\lib\site-packages\twisted\internet\posixbase.py", line286, ininstallWakerself.addReader(self.waker)File"c:\projects\pytest-twisted\.tox\py38-asyncioreactor\lib\site-packages\twisted\internet\asyncioreactor.py", line151, inaddReaderself._asyncioEventloop.add_reader(fd,callWithLogger,reader,File"C:\Python38-x64\Lib\asyncio\events.py", line501, inadd_readerraiseNotImplementedErrorNotImplementedErrorThe previous default, the selector loop, still works but you have to
explicitly set it and do so early. The followingconftest.pyis provided
for reference.importsysimportpytestimportpytest_twisted@pytest.hookimpl(tryfirst=True)defpytest_configure(config):# https://twistedmatrix.com/trac/ticket/9766# https://github.com/pytest-dev/pytest-twisted/issues/80if(config.getoption("reactor","default")=="asyncio"andsys.platform=='win32'andsys.version_info>=(3,8)):importasyncioselector_policy=asyncio.WindowsSelectorEventLoopPolicy()asyncio.set_event_loop_policy(selector_policy)Python 2 support plansAt some point it may become impractical to retain Python 2 support.
Given the small size and very low amount of development it seems
likely that this will not be a near term issue.  While I personally
have no need for Python 2 support I try to err on the side of being
helpful so support will not be explicitly removed just to not have to
think about it.  If major issues are reported and neither myself nor
the community have time to resolve them then options will be
considered.InstallationInstall the plugin as below.pipinstallpytest-twistedUsing the pluginThe plugin is available after installation and can be disabled using-pno:twisted.By defaulttwisted.internet.defaultis used to install the reactor.
This creates the same reactor thatimport twisted.internet.reactorwould.  Alternative reactors can be specified using the--reactoroption.  This presently supportsqt5reactorfor use withpyqt5andpytest-qtas well asasyncio. Thisguidedescribes how to add
support for a new reactor.The reactor is automatically created prior to the first test but can
be explicitly installed earlier by callingpytest_twisted.init_default_reactor()or the corresponding function
for the desired alternate reactor.inlineCallbacksUsingtwisted.internet.defer.inlineCallbacksas a decorator for test
functions, which use fixtures, does not work. Please usepytest_twisted.inlineCallbacksinstead.@pytest_twisted.inlineCallbacksdeftest_some_stuff(tmpdir):res=yieldthreads.deferToThread(os.listdir,tmpdir.strpath)assertres==[]ensureDeferredUsingtwisted.internet.defer.ensureDeferredas a decorator for test
functions, which use fixtures, does not work. Please usepytest_twisted.ensureDeferredinstead.@pytest_twisted.ensureDeferredasyncdeftest_some_stuff(tmpdir):res=awaitthreads.deferToThread(os.listdir,tmpdir.strpath)assertres==[]Waiting for deferreds in fixturespytest_twisted.blockonallows fixtures to wait for deferreds.@pytest.fixturedefval():d=defer.Deferred()reactor.callLater(1.0,d.callback,10)returnpytest_twisted.blockon(d)async/await fixturesasync/awaitfixtures can be used along withyieldfor normal
pytest fixture semantics of setup, value, and teardown.  At present only
function and module scope are supported.# No yield (coroutine function)#   -> use pytest_twisted.async_fixture()@pytest_twisted.async_fixture()asyncdeffoo():d=defer.Deferred()reactor.callLater(0.01,d.callback,42)value=awaitdreturnvalue# With yield (asynchronous generator)#   -> use pytest_twisted.async_yield_fixture()@pytest_twisted.async_yield_fixture()asyncdeffoo_with_teardown():d1,d2=defer.Deferred(),defer.Deferred()reactor.callLater(0.01,d1.callback,42)reactor.callLater(0.02,d2.callback,37)value=awaitd1yieldvalueawaitd2Hypothesispytest-twisted can be used with Hypothesis.@hypothesis.given(x=hypothesis.strategies.integers())@pytest_twisted.ensureDeferredasyncdeftest_async(x):assertisinstance(x,int)The twisted greenletSome libraries (e.g. corotwine) need to know the greenlet, which is
running the twisted reactor. It’s available from thetwisted_greenletfixture. The following code can be used to make
corotwine work with pytest-twisted.@pytest.fixture(scope="session",autouse=True)defset_MAIN(request,twisted_greenlet):fromcorotwineimportprotocolprotocol.MAIN=twisted_greenletThat’s (almost) all.Deprecationsv1.9pytest.blockonUsepytest_twisted.blockonpytest.inlineCallbacksUsepytest_twisted.inlineCallbacks