Debian Codegraph @

src/trio/_tests/test_abc.py

raw
1 from __future__ import annotations
2
3 import attrs
4 import pytest
5
6 from .. import abc as tabc
7 from ..lowlevel import Task
8
9
10 def test_instrument_implements_hook_methods() -> None:
11 attrs = {
12 "before_run": (),
13 "after_run": (),
14 "task_spawned": (Task,),
15 "task_scheduled": (Task,),
16 "before_task_step": (Task,),
17 "after_task_step": (Task,),
18 "task_exited": (Task,),
19 "before_io_wait": (3.3,),
20 "after_io_wait": (3.3,),
21 }
22
23 mayonnaise = tabc.Instrument()
24
25 for method_name, args in attrs.items():
26 assert hasattr(mayonnaise, method_name)
27 method = getattr(mayonnaise, method_name)
28 assert callable(method)
29 method(*args)
30
31
32 async def test_AsyncResource_defaults() -> None:
33 @attrs.define(slots=False)
34 class MyAR(tabc.AsyncResource):
35 record: list[str] = attrs.Factory(list)
36
37 async def aclose(self) -> None:
38 self.record.append("ac")
39
40 async with MyAR() as myar:
41 assert isinstance(myar, MyAR)
42 assert myar.record == []
43
44 assert myar.record == ["ac"]
45
46
47 def test_abc_generics() -> None:
48 # Pythons below 3.5.2 had a typing.Generic that would throw
49 # errors when instantiating or subclassing a parameterized
50 # version of a class with any __slots__. This is why RunVar
51 # (which has slots) is not generic. This tests that
52 # the generic ABCs are fine, because while they are slotted
53 # they don't actually define any slots.
54
55 class SlottedChannel(tabc.SendChannel[tabc.Stream]):
56 __slots__ = ("x",)
57
58 def send_nowait(self, value: object) -> None:
59 raise RuntimeError
60
61 async def send(self, value: object) -> None:
62 raise RuntimeError # pragma: no cover
63
64 def clone(self) -> None:
65 raise RuntimeError # pragma: no cover
66
67 async def aclose(self) -> None:
68 pass # pragma: no cover
69
70 channel = SlottedChannel()
71 with pytest.raises(RuntimeError):
72 channel.send_nowait(None)