Debian Codegraph @

src/trio/_tests/test_scheduler_determinism.py

raw
1 from __future__ import annotations
2
3 from typing import TYPE_CHECKING
4
5 import trio
6
7 if TYPE_CHECKING:
8 import pytest
9
10
11 async def scheduler_trace() -> tuple[tuple[str, int], ...]:
12 """Returns a scheduler-dependent value we can use to check determinism."""
13 trace = []
14
15 async def tracer(name: str) -> None:
16 for i in range(50):
17 trace.append((name, i))
18 await trio.lowlevel.checkpoint()
19
20 async with trio.open_nursery() as nursery:
21 for i in range(5):
22 nursery.start_soon(tracer, str(i))
23
24 return tuple(trace)
25
26
27 def test_the_trio_scheduler_is_not_deterministic() -> None:
28 # At least, not yet. See https://github.com/python-trio/trio/issues/32
29 traces = [trio.run(scheduler_trace) for _ in range(10)]
30 assert len(set(traces)) == len(traces)
31
32
33 def test_the_trio_scheduler_is_deterministic_if_seeded(
34 monkeypatch: pytest.MonkeyPatch,
35 ) -> None:
36 monkeypatch.setattr(trio._core._run, "_ALLOW_DETERMINISTIC_SCHEDULING", True)
37 traces = []
38 for _ in range(10):
39 state = trio._core._run._r.getstate()
40 try:
41 trio._core._run._r.seed(0)
42 traces.append(trio.run(scheduler_trace))
43 finally:
44 trio._core._run._r.setstate(state)
45
46 assert len(traces) == 10
47 assert len(set(traces)) == 1