Debian Codegraph @

src/pytest_twisted/__init__.py

raw symbols SCIP
1 import functools
2 import inspect
3 import itertools
4 import signal
5 import sys
6 import threading
7 import warnings
8
9 import decorator
10 import greenlet
11 import pytest
12
13 from twisted.internet import defer, error
14 from twisted.internet.threads import blockingCallFromThread
15 from twisted.python import failure
16
17 if sys.version_info[0] == 3:
18 from pytest_twisted.three import (
19 _async_pytest_fixture_setup,
20 _async_pytest_pyfunc_call,
21 )
22 elif sys.version_info[0] == 2:
23 from pytest_twisted.two import _async_pytest_pyfunc_call
24
25
26 class WrongReactorAlreadyInstalledError(Exception):
27 pass
28
29
30 class UnrecognizedCoroutineMarkError(Exception):
31 @classmethod
32 def from_mark(cls, mark):
33 return cls(
34 'Coroutine wrapper mark not recognized: {}'.format(repr(mark)),
35 )
36
37
38 class AsyncGeneratorFixtureDidNotStopError(Exception):
39 @classmethod
40 def from_generator(cls, generator):
41 return cls(
42 'async fixture did not stop: {}'.format(generator),
43 )
44
45
46 class AsyncFixtureUnsupportedScopeError(Exception):
47 @classmethod
48 def from_scope(cls, scope):
49 return cls(
50 'Unsupported scope {0!r} used for async fixture'.format(scope)
51 )
52
53
54 class _config:
55 external_reactor = False
56
57
58 class _instances:
59 gr_twisted = None
60 reactor = None
61
62
63 def _deprecate(deprecated, recommended):
64 def decorator(f):
65 @functools.wraps(f)
66 def wrapper(*args, **kwargs):
67 warnings.warn(
68 '{deprecated} has been deprecated, use {recommended}'.format(
69 deprecated=deprecated,
70 recommended=recommended,
71 ),
72 DeprecationWarning,
73 stacklevel=2,
74 )
75 return f(*args, **kwargs)
76
77 return wrapper
78
79 return decorator
80
81
82 def blockon(d):
83 if _config.external_reactor:
84 return block_from_thread(d)
85
86 return blockon_default(d)
87
88
89 def blockon_default(d):
90 current = greenlet.getcurrent()
91 assert (
92 current is not _instances.gr_twisted
93 ), "blockon cannot be called from the twisted greenlet"
94 result = []
95
96 def cb(r):
97 result.append(r)
98 if greenlet.getcurrent() is not current:
99 current.switch(result)
100
101 d.addCallbacks(cb, cb)
102 if not result:
103 _result = _instances.gr_twisted.switch()
104 assert _result is result, "illegal switch in blockon"
105
106 if isinstance(result[0], failure.Failure):
107 result[0].raiseException()
108
109 return result[0]
110
111
112 def block_from_thread(d):
113 return blockingCallFromThread(_instances.reactor, lambda x: x, d)
114
115
116 def decorator_apply(dec, func):
117 """
118 Decorate a function by preserving the signature even if dec
119 is not a signature-preserving decorator.
120
121 https://github.com/micheles/decorator/blob/55a68b5ef1951614c5c37a6d201b1f3b804dbce6/docs/documentation.md#dealing-with-third-party-decorators
122 """
123 return decorator.FunctionMaker.create(
124 func, 'return decfunc(%(signature)s)',
125 dict(decfunc=dec(func)), __wrapped__=func)
126
127
128 class DecoratorArgumentsError(Exception):
129 pass
130
131
132 def repr_args_kwargs(*args, **kwargs):
133 arguments = ', '.join(itertools.chain(
134 (repr(x) for x in args),
135 ('{}={}'.format(k, repr(v)) for k, v in kwargs.items())
136 ))
137
138 return '({})'.format(arguments)
139
140
141 def _positional_not_allowed_exception(*args, **kwargs):
142 arguments = repr_args_kwargs(*args, **kwargs)
143
144 return DecoratorArgumentsError(
145 'Positional decorator arguments not allowed: {}'.format(arguments),
146 )
147
148
149 def _optional_arguments():
150 def decorator_decorator(d):
151 # TODO: this should get the signature of d minus the f or something
152 def decorator_wrapper(*args, **decorator_arguments):
153 """this is decorator_wrapper"""
154 if len(args) > 1:
155 raise _positional_not_allowed_exception()
156
157 if len(args) == 1:
158 maybe_f = args[0]
159
160 if len(decorator_arguments) > 0 or not callable(maybe_f):
161 raise _positional_not_allowed_exception()
162
163 f = maybe_f
164 return d(f)
165
166 # TODO: this should get the signature of d minus the kwargs
167 def decorator_closure_on_arguments(f):
168 return d(f, **decorator_arguments)
169
170 return decorator_closure_on_arguments
171
172 return decorator_wrapper
173
174 return decorator_decorator
175
176
177 @_optional_arguments()
178 def inlineCallbacks(f):
179 """
180 Mark as inline callbacks test for pytest-twisted processing and apply
181 @inlineCallbacks.
182
183 Unlike @ensureDeferred, @inlineCallbacks can be applied here because it
184 does not call nor schedule the test function. Further, @inlineCallbacks
185 must be applied here otherwise pytest identifies the test as a 'yield test'
186 for which they dropped support in 4.0 and now they skip.
187 """
188 decorated = decorator_apply(defer.inlineCallbacks, f)
189 _set_mark(o=decorated, mark='inline_callbacks_test')
190
191 return decorated
192
193
194 @_optional_arguments()
195 def ensureDeferred(f):
196 """
197 Mark as async test for pytest-twisted processing.
198
199 Unlike @inlineCallbacks, @ensureDeferred must not be applied here since it
200 would call and schedule the test function.
201 """
202 _set_mark(o=f, mark='async_test')
203
204 return f
205
206
207 def init_twisted_greenlet():
208 if _instances.reactor is None or _instances.gr_twisted:
209 return
210
211 if not _instances.reactor.running:
212 if not isinstance(threading.current_thread(), threading._MainThread):
213 warnings.warn(
214 (
215 'Will not attempt to block Twisted signal configuration'
216 ' since we are not running in the main thread. See'
217 ' https://github.com/pytest-dev/pytest-twisted/issues/153.'
218 ),
219 RuntimeWarning,
220 )
221 elif signal.getsignal(signal.SIGINT) == signal.default_int_handler:
222 signal.signal(
223 signal.SIGINT,
224 functools.partial(signal.default_int_handler),
225 )
226 _instances.gr_twisted = greenlet.greenlet(_instances.reactor.run)
227 # give me better tracebacks:
228 failure.Failure.cleanFailure = lambda self: None
229 else:
230 _config.external_reactor = True
231
232
233 def stop_twisted_greenlet():
234 if _instances.gr_twisted:
235 try:
236 _instances.reactor.stop()
237 except error.ReactorNotRunning:
238 # Sometimes the reactor is stopped before we get here. For
239 # example, this can happen in response to a SIGINT in some cases.
240 pass
241 _instances.gr_twisted.switch()
242
243
244 def _get_mark(o, default=None):
245 """Get the pytest-twisted test or fixture mark."""
246 return getattr(o, _mark_attribute_name, default)
247
248
249 def _set_mark(o, mark):
250 """Set the pytest-twisted test or fixture mark."""
251 setattr(o, _mark_attribute_name, mark)
252
253
254 def _marked_async_fixture(mark):
255 @functools.wraps(pytest.fixture)
256 @_optional_arguments()
257 def fixture(f, *args, **kwargs):
258 try:
259 scope = args[0]
260 except IndexError:
261 scope = kwargs.get('scope', 'function')
262
263 if scope not in ['function', 'module']:
264 # TODO: handle...
265 # - class
266 # - package
267 # - session
268 # - dynamic
269 #
270 # https://docs.pytest.org/en/latest/reference.html#pytest-fixture-api
271 # then remove this and update docs, or maybe keep it around
272 # in case new options come in without support?
273 #
274 # https://github.com/pytest-dev/pytest-twisted/issues/56
275 raise AsyncFixtureUnsupportedScopeError.from_scope(scope=scope)
276
277 _set_mark(f, mark)
278 result = pytest.fixture(*args, **kwargs)(f)
279
280 return result
281
282 return fixture
283
284
285 _mark_attribute_name = '_pytest_twisted_mark'
286 async_fixture = _marked_async_fixture('async_fixture')
287 async_yield_fixture = _marked_async_fixture('async_yield_fixture')
288
289
290 def pytest_fixture_setup(fixturedef, request):
291 """Interface pytest to async for async and async yield fixtures."""
292 # TODO: what about _adding_ inlineCallbacks fixture support?
293 maybe_mark = _get_mark(fixturedef.func)
294 if maybe_mark is None:
295 return None
296
297 mark = maybe_mark
298
299 _run_inline_callbacks(
300 _async_pytest_fixture_setup,
301 fixturedef,
302 request,
303 mark,
304 )
305
306 return not None
307
308
309 def _create_async_yield_fixture_finalizer(coroutine):
310 def finalizer():
311 _run_inline_callbacks(
312 _tear_it_down,
313 defer.ensureDeferred(coroutine.__anext__()),
314 )
315
316 return finalizer
317
318
319 @defer.inlineCallbacks
320 def _tear_it_down(deferred):
321 """Tear down a specific async yield fixture."""
322 try:
323 yield deferred
324 except StopAsyncIteration:
325 return
326
327 # TODO: six.raise_from()
328 raise AsyncGeneratorFixtureDidNotStopError.from_generator(
329 generator=deferred,
330 )
331
332
333 def _run_inline_callbacks(f, *args):
334 """Interface into Twisted greenlet to run and wait for a deferred."""
335 if _instances.gr_twisted is not None:
336 if _instances.gr_twisted.dead:
337 raise RuntimeError("twisted reactor has stopped")
338
339 def in_reactor(d, f, *args):
340 return defer.maybeDeferred(f, *args).chainDeferred(d)
341
342 d = defer.Deferred()
343 _instances.reactor.callLater(0.0, in_reactor, d, f, *args)
344 blockon_default(d)
345 else:
346 if not _instances.reactor.running:
347 raise RuntimeError("twisted reactor is not running")
348 blockingCallFromThread(_instances.reactor, f, *args)
349
350
351 def pytest_pyfunc_call(pyfuncitem):
352 """Interface to async test call handler."""
353 # TODO: only handle 'our' tests? what is the point of handling others?
354 # well, because our interface allowed people to return deferreds
355 # from arbitrary tests so we kinda have to keep this up for now
356 maybe_hypothesis = getattr(pyfuncitem.obj, "hypothesis", None)
357 if maybe_hypothesis is None:
358 _run_inline_callbacks(
359 _async_pytest_pyfunc_call,
360 pyfuncitem,
361 pyfuncitem.obj,
362 {}
363 )
364 result = not None
365 else:
366 hypothesis = maybe_hypothesis
367 f = hypothesis.inner_test
368
369 def inner_test(**kwargs):
370 return _run_inline_callbacks(
371 _async_pytest_pyfunc_call,
372 pyfuncitem,
373 f,
374 kwargs,
375 )
376
377 pyfuncitem.obj.hypothesis.inner_test = inner_test
378 result = None
379
380 return result
381
382
383 @pytest.fixture(scope="session", autouse=True)
384 def twisted_greenlet():
385 """Provide the twisted greenlet in fixture form."""
386 return _instances.gr_twisted
387
388
389 def init_default_reactor():
390 """Install the default Twisted reactor."""
391 import twisted.internet.default
392
393 module = inspect.getmodule(twisted.internet.default.install)
394
395 module_name = module.__name__.split(".")[-1]
396 reactor_type_name, = (x for x in dir(module) if x.lower() == module_name)
397 reactor_type = getattr(module, reactor_type_name)
398
399 _install_reactor(
400 reactor_installer=twisted.internet.default.install,
401 reactor_type=reactor_type,
402 )
403
404
405 def init_qt5_reactor():
406 """Install the qt5reactor... reactor."""
407 import qt5reactor
408
409 _install_reactor(
410 reactor_installer=qt5reactor.install, reactor_type=qt5reactor.QtReactor
411 )
412
413
414 def init_asyncio_reactor():
415 """Install the Twisted reactor for asyncio."""
416 from twisted.internet import asyncioreactor
417
418 _install_reactor(
419 reactor_installer=asyncioreactor.install,
420 reactor_type=asyncioreactor.AsyncioSelectorReactor,
421 )
422
423
424 reactor_installers = {
425 "default": init_default_reactor,
426 "qt5reactor": init_qt5_reactor,
427 "asyncio": init_asyncio_reactor,
428 }
429
430
431 def _install_reactor(reactor_installer, reactor_type):
432 """Install the specified reactor and create the greenlet."""
433 try:
434 reactor_installer()
435 except error.ReactorAlreadyInstalledError:
436 import twisted.internet.reactor
437
438 if not isinstance(twisted.internet.reactor, reactor_type):
439 raise WrongReactorAlreadyInstalledError(
440 "expected {} but found {}".format(
441 reactor_type, type(twisted.internet.reactor)
442 )
443 )
444
445 import twisted.internet.reactor
446
447 _instances.reactor = twisted.internet.reactor
448 init_twisted_greenlet()
449
450
451 def pytest_addoption(parser):
452 """Add options into the pytest CLI."""
453 group = parser.getgroup("twisted")
454 group.addoption(
455 "--reactor",
456 default="default",
457 choices=tuple(reactor_installers.keys()),
458 )
459
460
461 def pytest_configure(config):
462 """Identify and install chosen reactor."""
463 pytest.inlineCallbacks = _deprecate(
464 deprecated='pytest.inlineCallbacks',
465 recommended='pytest_twisted.inlineCallbacks',
466 )(inlineCallbacks)
467 pytest.blockon = _deprecate(
468 deprecated='pytest.blockon',
469 recommended='pytest_twisted.blockon',
470 )(blockon)
471
472 reactor_installers[config.getoption("reactor")]()
473
474
475 def pytest_unconfigure(config):
476 """Stop the reactor greenlet."""
477 stop_twisted_greenlet()
478
479
480 def _use_asyncio_selector_if_required(config):
481 """Set asyncio selector event loop policy if needed."""
482 # https://twistedmatrix.com/trac/ticket/9766
483 # https://github.com/pytest-dev/pytest-twisted/issues/80
484
485 is_asyncio = config.getoption("reactor", "default") == "asyncio"
486
487 if is_asyncio and sys.platform == 'win32' and sys.version_info >= (3, 8):
488 import asyncio
489
490 selector_policy = asyncio.WindowsSelectorEventLoopPolicy()
491 asyncio.set_event_loop_policy(selector_policy)