Debian Codegraph @

hypothesis-python/tests/cover/test_asyncio.py

raw
1 # This file is part of Hypothesis, which may be found at
2 # https://github.com/HypothesisWorks/hypothesis/
3 #
4 # Copyright the Hypothesis Authors.
5 # Individual contributors are listed in AUTHORS.rst and the git log.
6 #
7 # This Source Code Form is subject to the terms of the Mozilla Public License,
8 # v. 2.0. If a copy of the MPL was not distributed with this file, You can
9 # obtain one at https://mozilla.org/MPL/2.0/.
10
11 import asyncio
12 import warnings
13 from unittest import TestCase
14
15 import pytest
16
17 from hypothesis import assume, given, settings, strategies as st
18 from hypothesis.internal.compat import PYPY
19
20 from tests.common.utils import skipif_emscripten
21
22 pytestmark = pytest.mark.skipif(
23 settings.get_current_profile_name() == "threading",
24 reason="bad interactions when mixing threads and asyncio",
25 )
26
27
28 def coro_decorator(f):
29 with warnings.catch_warnings():
30 warnings.simplefilter(action="ignore", category=DeprecationWarning)
31 try:
32 return asyncio.coroutine(f)
33 except AttributeError:
34 pytest.skip("needs fixing for asyncio version", allow_module_level=True)
35
36
37 class TestAsyncio(TestCase):
38 timeout = 5
39
40 def setUp(self):
41 self.loop = asyncio.new_event_loop()
42 asyncio.set_event_loop(self.loop)
43
44 def tearDown(self):
45 self.loop.close()
46
47 def execute_example(self, f):
48 error = None
49
50 def g():
51 nonlocal error
52 try:
53 x = f()
54 if x is not None:
55 yield from x
56 except BaseException as e:
57 error = e
58
59 coro = coro_decorator(g)
60 future = asyncio.wait_for(coro(), timeout=self.timeout)
61 self.loop.run_until_complete(future)
62 if error is not None:
63 raise error
64
65 @pytest.mark.skipif(PYPY, reason="Error in asyncio.new_event_loop()")
66 @given(x=st.text())
67 @coro_decorator
68 def test_foo(self, x):
69 assume(x)
70 yield from asyncio.sleep(0.001)
71 assert x
72
73
74 class TestAsyncioRun(TestCase):
75 # In principle, these tests could indeed run on emscripten if we grab the existing
76 # event loop and run them there. However, that seems to have hit an infinite loop
77 # and so we're just skipping them for now and will revisit later.
78
79 def execute_example(self, f):
80 asyncio.run(f())
81
82 @skipif_emscripten
83 @given(x=st.text())
84 @coro_decorator
85 def test_foo_yield_from(self, x):
86 assume(x)
87 yield from asyncio.sleep(0.001)
88 assert x
89
90 @skipif_emscripten
91 @given(st.text())
92 async def test_foo_await(self, x):
93 assume(x)
94 await asyncio.sleep(0.001)
95 assert x