Debian Codegraph @

src/trio/_tests/test_util.py

raw
1 from __future__ import annotations
2
3 import sys
4 import types
5 from typing import TYPE_CHECKING, TypeVar
6
7 if TYPE_CHECKING:
8 from collections.abc import AsyncGenerator, Coroutine, Generator
9 import pytest
10
11 import trio
12 from trio.testing import _Matcher as Matcher, _RaisesGroup as RaisesGroup
13
14 from .. import _core
15 from .._core._tests.tutil import (
16 create_asyncio_future_in_new_loop,
17 ignore_coroutine_never_awaited_warnings,
18 )
19 from .._util import (
20 ConflictDetector,
21 MultipleExceptionError,
22 NoPublicConstructor,
23 coroutine_or_error,
24 final,
25 fixup_module_metadata,
26 is_main_thread,
27 raise_single_exception_from_group,
28 )
29 from ..testing import wait_all_tasks_blocked
30
31 if sys.version_info < (3, 11):
32 from exceptiongroup import BaseExceptionGroup, ExceptionGroup
33
34 if TYPE_CHECKING:
35 from collections.abc import AsyncGenerator
36
37 T = TypeVar("T")
38
39
40 async def test_ConflictDetector() -> None:
41 ul1 = ConflictDetector("ul1")
42 ul2 = ConflictDetector("ul2")
43
44 with ul1:
45 with ul2:
46 print("ok")
47
48 with pytest.raises(_core.BusyResourceError, match="ul1"):
49 with ul1:
50 with ul1:
51 pass # pragma: no cover
52
53 async def wait_with_ul1() -> None:
54 with ul1:
55 await wait_all_tasks_blocked()
56
57 with RaisesGroup(Matcher(_core.BusyResourceError, "ul1")):
58 async with _core.open_nursery() as nursery:
59 nursery.start_soon(wait_with_ul1)
60 nursery.start_soon(wait_with_ul1)
61
62
63 def test_module_metadata_is_fixed_up() -> None:
64 import trio
65 import trio.testing
66
67 assert trio.Cancelled.__module__ == "trio"
68 assert trio.open_nursery.__module__ == "trio"
69 assert trio.abc.Stream.__module__ == "trio.abc"
70 assert trio.lowlevel.wait_task_rescheduled.__module__ == "trio.lowlevel"
71 assert trio.testing.trio_test.__module__ == "trio.testing"
72
73 # Also check methods
74 assert trio.lowlevel.ParkingLot.__init__.__module__ == "trio.lowlevel"
75 assert trio.abc.Stream.send_all.__module__ == "trio.abc"
76
77 # And names
78 assert trio.Cancelled.__name__ == "Cancelled"
79 assert trio.Cancelled.__qualname__ == "Cancelled"
80 assert trio.abc.SendStream.send_all.__name__ == "send_all"
81 assert trio.abc.SendStream.send_all.__qualname__ == "SendStream.send_all"
82 assert trio.to_thread.__name__ == "trio.to_thread"
83 assert trio.to_thread.run_sync.__name__ == "run_sync"
84 assert trio.to_thread.run_sync.__qualname__ == "run_sync"
85
86
87 async def test_is_main_thread() -> None:
88 assert is_main_thread()
89
90 def not_main_thread() -> None:
91 assert not is_main_thread()
92
93 await trio.to_thread.run_sync(not_main_thread)
94
95
96 # @coroutine is deprecated since python 3.8, which is fine with us.
97 @pytest.mark.filterwarnings("ignore:.*@coroutine.*:DeprecationWarning")
98 def test_coroutine_or_error() -> None:
99 class Deferred:
100 "Just kidding"
101
102 with ignore_coroutine_never_awaited_warnings():
103
104 async def f() -> None: # pragma: no cover
105 pass
106
107 with pytest.raises(TypeError) as excinfo:
108 coroutine_or_error(f()) # type: ignore[arg-type, unused-coroutine]
109 assert "expecting an async function" in str(excinfo.value)
110
111 import asyncio
112
113 if sys.version_info < (3, 11):
114
115 @asyncio.coroutine
116 def generator_based_coro() -> (
117 Generator[Coroutine[None, None, None], None, None]
118 ): # pragma: no cover
119 yield from asyncio.sleep(1)
120
121 with pytest.raises(TypeError) as excinfo:
122 coroutine_or_error(generator_based_coro()) # type: ignore[arg-type, unused-coroutine]
123 assert "asyncio" in str(excinfo.value)
124
125 with pytest.raises(TypeError) as excinfo:
126 coroutine_or_error(create_asyncio_future_in_new_loop()) # type: ignore[arg-type, unused-coroutine]
127 assert "asyncio" in str(excinfo.value)
128
129 # does not raise arg-type error
130 with pytest.raises(TypeError) as excinfo:
131 coroutine_or_error(create_asyncio_future_in_new_loop) # type: ignore[unused-coroutine]
132 assert "asyncio" in str(excinfo.value)
133
134 with pytest.raises(TypeError) as excinfo:
135 coroutine_or_error(Deferred()) # type: ignore[arg-type, unused-coroutine]
136 assert "twisted" in str(excinfo.value)
137
138 with pytest.raises(TypeError) as excinfo:
139 coroutine_or_error(lambda: Deferred()) # type: ignore[arg-type, unused-coroutine, return-value]
140 assert "twisted" in str(excinfo.value)
141
142 with pytest.raises(TypeError) as excinfo:
143 coroutine_or_error(len, [[1, 2, 3]]) # type: ignore[arg-type, unused-coroutine]
144
145 assert "appears to be synchronous" in str(excinfo.value)
146
147 async def async_gen(
148 _: object,
149 ) -> AsyncGenerator[None, None]: # pragma: no cover
150 yield
151
152 with pytest.raises(TypeError) as excinfo:
153 coroutine_or_error(async_gen, [0]) # type: ignore[arg-type,unused-coroutine]
154 msg = "expected an async function but got an async generator"
155 assert msg in str(excinfo.value)
156
157 # Make sure no references are kept around to keep anything alive
158 del excinfo
159
160
161 def test_final_decorator() -> None:
162 """Test that subclassing a @final-annotated class is not allowed.
163
164 This checks both runtime results, and verifies that type checkers detect
165 the error statically through the type-ignore comment.
166 """
167
168 @final
169 class FinalClass:
170 pass
171
172 with pytest.raises(TypeError):
173
174 class SubClass(FinalClass): # type: ignore[misc]
175 pass
176
177
178 def test_no_public_constructor_metaclass() -> None:
179 """The NoPublicConstructor metaclass prevents calling the constructor directly."""
180
181 class SpecialClass(metaclass=NoPublicConstructor):
182 def __init__(self, a: int, b: float) -> None:
183 """Check arguments can be passed to __init__."""
184 assert a == 8
185 assert b == 3.15
186
187 with pytest.raises(TypeError):
188 SpecialClass(8, 3.15)
189
190 # Private constructor should not raise, and passes args to __init__.
191 assert isinstance(SpecialClass._create(8, b=3.15), SpecialClass)
192
193
194 def test_fixup_module_metadata() -> None:
195 # Ignores modules not in the trio.X tree.
196 non_trio_module = types.ModuleType("not_trio")
197 non_trio_module.some_func = lambda: None # type: ignore[attr-defined]
198 non_trio_module.some_func.__name__ = "some_func"
199 non_trio_module.some_func.__qualname__ = "some_func"
200
201 fixup_module_metadata(non_trio_module.__name__, vars(non_trio_module))
202
203 assert non_trio_module.some_func.__name__ == "some_func"
204 assert non_trio_module.some_func.__qualname__ == "some_func"
205
206 # Bulild up a fake module to test. Just use lambdas since all we care about is the names.
207 mod = types.ModuleType("trio._somemodule_impl")
208 mod.some_func = lambda: None # type: ignore[attr-defined]
209 mod.some_func.__name__ = "_something_else"
210 mod.some_func.__qualname__ = "_something_else"
211
212 # No __module__ means it's unchanged.
213 mod.not_funclike = types.SimpleNamespace() # type: ignore[attr-defined]
214 mod.not_funclike.__name__ = "not_funclike"
215
216 # Check __qualname__ being absent works.
217 mod.only_has_name = types.SimpleNamespace() # type: ignore[attr-defined]
218 mod.only_has_name.__module__ = "trio._somemodule_impl"
219 mod.only_has_name.__name__ = "only_name"
220
221 # Underscored names are unchanged.
222 mod._private = lambda: None # type: ignore[attr-defined]
223 mod._private.__module__ = "trio._somemodule_impl"
224 mod._private.__name__ = mod._private.__qualname__ = "_private"
225
226 # We recurse into classes.
227 mod.SomeClass = type( # type: ignore[attr-defined]
228 "SomeClass",
229 (),
230 {
231 "__init__": lambda self: None,
232 "method": lambda self: None,
233 },
234 )
235 # Reference loop is fine.
236 mod.SomeClass.recursion = mod.SomeClass
237
238 fixup_module_metadata("trio.somemodule", vars(mod))
239 assert mod.some_func.__name__ == "some_func"
240 assert mod.some_func.__module__ == "trio.somemodule"
241 assert mod.some_func.__qualname__ == "some_func"
242
243 assert mod.not_funclike.__name__ == "not_funclike"
244 assert mod._private.__name__ == "_private"
245 assert mod._private.__module__ == "trio._somemodule_impl"
246 assert mod._private.__qualname__ == "_private"
247
248 assert mod.only_has_name.__name__ == "only_has_name"
249 assert mod.only_has_name.__module__ == "trio.somemodule"
250 assert not hasattr(mod.only_has_name, "__qualname__")
251
252 assert mod.SomeClass.method.__name__ == "method"
253 assert mod.SomeClass.method.__module__ == "trio.somemodule"
254 assert mod.SomeClass.method.__qualname__ == "SomeClass.method"
255 # Make coverage happy.
256 non_trio_module.some_func()
257 mod.some_func()
258 mod._private()
259 mod.SomeClass().method()
260
261
262 async def test_raise_single_exception_from_group() -> None:
263 excinfo: pytest.ExceptionInfo[BaseException]
264
265 exc = ValueError("foo")
266 cause = SyntaxError("cause")
267 context = TypeError("context")
268 exc.__cause__ = cause
269 exc.__context__ = context
270 cancelled = trio.Cancelled._create(source="deadline")
271
272 with pytest.raises(ValueError, match="foo") as excinfo:
273 raise_single_exception_from_group(ExceptionGroup("", [exc]))
274 assert excinfo.value.__cause__ == cause
275 assert excinfo.value.__context__ == context
276
277 # only unwraps one layer of exceptiongroup
278 inner_eg = ExceptionGroup("inner eg", [exc])
279 inner_cause = SyntaxError("inner eg cause")
280 inner_context = TypeError("inner eg context")
281 inner_eg.__cause__ = inner_cause
282 inner_eg.__context__ = inner_context
283 with RaisesGroup(Matcher(ValueError, match="^foo$"), match="^inner eg$") as eginfo:
284 raise_single_exception_from_group(ExceptionGroup("", [inner_eg]))
285 assert eginfo.value.__cause__ == inner_cause
286 assert eginfo.value.__context__ == inner_context
287
288 with pytest.raises(ValueError, match="foo") as excinfo:
289 raise_single_exception_from_group(
290 BaseExceptionGroup("", [cancelled, cancelled, exc])
291 )
292 assert excinfo.value.__cause__ == cause
293 assert excinfo.value.__context__ == context
294
295 # multiple non-cancelled
296 eg = ExceptionGroup("", [ValueError("foo"), ValueError("bar")])
297 with pytest.raises(
298 MultipleExceptionError,
299 match=r"^Attempted to unwrap exceptiongroup with multiple non-cancelled exceptions. This is often caused by a bug in the caller.$",
300 ) as excinfo:
301 raise_single_exception_from_group(eg)
302 assert excinfo.value.__cause__ is eg
303 assert excinfo.value.__context__ is None
304
305 # keyboardinterrupt overrides everything
306 eg_ki = BaseExceptionGroup(
307 "",
308 [
309 ValueError("foo"),
310 ValueError("bar"),
311 KeyboardInterrupt("preserve error msg"),
312 ],
313 )
314 with pytest.raises(
315 KeyboardInterrupt,
316 match=r"^preserve error msg$",
317 ) as excinfo:
318 raise_single_exception_from_group(eg_ki)
319
320 assert excinfo.value.__cause__ is eg_ki
321 assert excinfo.value.__context__ is None
322
323 # and same for SystemExit but verify code too
324 systemexit_ki = BaseExceptionGroup(
325 "",
326 [
327 ValueError("foo"),
328 ValueError("bar"),
329 SystemExit(2),
330 ],
331 )
332
333 with pytest.raises(SystemExit) as excinfo:
334 raise_single_exception_from_group(systemexit_ki)
335
336 assert excinfo.value.code == 2
337 assert excinfo.value.__cause__ is systemexit_ki
338 assert excinfo.value.__context__ is None
339
340 # if we only got cancelled, first one is reraised
341 with pytest.raises(trio.Cancelled, match=r"^cancelled due to deadline$") as excinfo:
342 raise_single_exception_from_group(
343 BaseExceptionGroup(
344 "", [cancelled, trio.Cancelled._create(source="explicit")]
345 )
346 )
347 assert excinfo.value is cancelled
348 assert excinfo.value.__cause__ is None
349 assert excinfo.value.__context__ is None