Skip to content

Commit 50983ee

Browse files
committed
use pytest's request.addfinalizer() to schedule async yield fixture teardown
1 parent 94fb2a3 commit 50983ee

File tree

1 file changed

+9
-32
lines changed

1 file changed

+9
-32
lines changed

pytest_twisted.py

Lines changed: 9 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,6 @@ class _instances:
4949
reactor = None
5050

5151

52-
class _tracking:
53-
async_yield_fixture_cache = {}
54-
to_be_torn_down = []
55-
56-
5752
def _deprecate(deprecated, recommended):
5853
def decorator(f):
5954
@functools.wraps(f)
@@ -243,8 +238,13 @@ def _async_pytest_fixture_setup(fixturedef, request, mark):
243238
)
244239
elif mark == 'async_yield_fixture':
245240
coroutine = fixture_function(**kwargs)
246-
# TODO: use request.addfinalizer() instead?
247-
_tracking.async_yield_fixture_cache[request.param_index] = coroutine
241+
242+
finalizer = functools.partial(
243+
_async_pytest_fixture_finalizer,
244+
coroutine=coroutine,
245+
)
246+
request.addfinalizer(finalizer)
247+
248248
arg_value = yield defer.ensureDeferred(
249249
coroutine.__anext__(),
250250
)
@@ -256,22 +256,9 @@ def _async_pytest_fixture_setup(fixturedef, request, mark):
256256
defer.returnValue(arg_value)
257257

258258

259-
# TODO: but don't we want to do the finalizer? not wait until post it?
260-
def pytest_fixture_post_finalizer(fixturedef, request):
261-
"""Collect async yield fixture teardown requests for later handling."""
262-
maybe_coroutine = _tracking.async_yield_fixture_cache.pop(
263-
request.param_index,
264-
None,
265-
)
266-
267-
if maybe_coroutine is None:
268-
return None
269-
270-
coroutine = maybe_coroutine
271-
259+
def _async_pytest_fixture_finalizer(coroutine):
272260
deferred = defer.ensureDeferred(coroutine.__anext__())
273-
_tracking.to_be_torn_down.append(deferred)
274-
return None
261+
_run_inline_callbacks(tear_it_down, deferred)
275262

276263

277264
@defer.inlineCallbacks
@@ -310,16 +297,6 @@ def in_reactor(d, f, *args):
310297
blockingCallFromThread(_instances.reactor, f, *args)
311298

312299

313-
@pytest.hookimpl(hookwrapper=True)
314-
def pytest_runtest_teardown(item):
315-
"""Tear down collected async yield fixtures."""
316-
yield
317-
318-
while len(_tracking.to_be_torn_down) > 0:
319-
deferred = _tracking.to_be_torn_down.pop(0)
320-
_run_inline_callbacks(tear_it_down, deferred)
321-
322-
323300
def pytest_pyfunc_call(pyfuncitem):
324301
"""Interface to async test call handler."""
325302
# TODO: only handle 'our' tests? what is the point of handling others?

0 commit comments

Comments
 (0)