|
1 | 1 | import pytest |
| 2 | +import trio |
2 | 3 | from hypothesis import given, settings, strategies as st |
3 | 4 |
|
| 5 | +from pytest_trio.plugin import _trio_test_runner_factory |
| 6 | + |
4 | 7 | # deadline=None avoids unpredictable warnings/errors when CI happens to be |
5 | 8 | # slow (example: https://travis-ci.org/python-trio/pytest-trio/jobs/406738296) |
6 | 9 | # max_examples=5 speeds things up a bit |
@@ -28,3 +31,47 @@ async def test_mark_outer(n): |
28 | 31 | async def test_mark_and_parametrize(x, y): |
29 | 32 | assert x is None |
30 | 33 | assert y in (1, 2) |
| 34 | + |
| 35 | + |
| 36 | +async def scheduler_trace(): |
| 37 | + """Returns a scheduler-dependent value we can use to check determinism.""" |
| 38 | + trace = [] |
| 39 | + |
| 40 | + async def tracer(name): |
| 41 | + for i in range(10): |
| 42 | + trace.append((name, i)) |
| 43 | + await trio.sleep(0) |
| 44 | + |
| 45 | + async with trio.open_nursery() as nursery: |
| 46 | + for i in range(5): |
| 47 | + nursery.start_soon(tracer, i) |
| 48 | + |
| 49 | + return tuple(trace) |
| 50 | + |
| 51 | + |
| 52 | +def test_the_trio_scheduler_is_not_deterministic(): |
| 53 | + # At least, not yet. See https://github.com/python-trio/trio/issues/32 |
| 54 | + traces = [] |
| 55 | + for _ in range(10): |
| 56 | + traces.append(trio.run(scheduler_trace)) |
| 57 | + assert len(set(traces)) == len(traces) |
| 58 | + |
| 59 | + |
| 60 | +def test_the_trio_scheduler_is_deterministic_under_hypothesis(): |
| 61 | + traces = [] |
| 62 | + |
| 63 | + @our_settings |
| 64 | + @given(st.integers()) |
| 65 | + @pytest.mark.trio |
| 66 | + async def inner(_): |
| 67 | + traces.append(await scheduler_trace()) |
| 68 | + |
| 69 | + # The pytest.mark.trio doesn't do it's magic thing to |
| 70 | + # inner functions, so we invoke it explicitly here. |
| 71 | + inner.hypothesis.inner_test = _trio_test_runner_factory( |
| 72 | + None, inner.hypothesis.inner_test |
| 73 | + ) |
| 74 | + inner() # Tada, now it's a sync function! |
| 75 | + |
| 76 | + assert len(traces) >= 5 |
| 77 | + assert len(set(traces)) == 1 |
0 commit comments