Debian Codegraph @

src/trio/_core/_tests/test_windows.py

raw
1 from __future__ import annotations
2
3 import os
4 import sys
5 import tempfile
6 from contextlib import contextmanager
7 from typing import TYPE_CHECKING
8 from unittest.mock import create_autospec
9
10 import pytest
11
12 on_windows = os.name == "nt"
13 # Mark all the tests in this file as being windows-only
14 pytestmark = pytest.mark.skipif(not on_windows, reason="windows only")
15
16 assert (
17 sys.platform == "win32" or not TYPE_CHECKING
18 ) # Skip type checking when not on Windows
19
20 from ... import _core, sleep
21 from ...testing import wait_all_tasks_blocked
22 from .tutil import gc_collect_harder, restore_unraisablehook, slow
23
24 if TYPE_CHECKING:
25 from collections.abc import Generator
26 from io import BufferedWriter
27
28 if on_windows:
29 from .._windows_cffi import (
30 INVALID_HANDLE_VALUE,
31 FileFlags,
32 Handle,
33 ffi,
34 kernel32,
35 raise_winerror,
36 )
37
38
39 def test_winerror(monkeypatch: pytest.MonkeyPatch) -> None:
40 # this is unfortunately needed as the generated ffi is read-only
41 class FFIWrapper:
42 def getwinerror(self) -> None:
43 raise NotImplementedError("this is a fake implementation")
44
45 mock = create_autospec(ffi.getwinerror)
46 monkeypatch.setattr("trio._core._windows_cffi.ffi", FFIWrapper)
47 monkeypatch.setattr("trio._core._windows_cffi.ffi.getwinerror", mock)
48
49 # Returning none = no error, should not happen.
50 mock.return_value = None
51 with pytest.raises(RuntimeError, match=r"^No error set\?$"):
52 raise_winerror()
53 mock.assert_called_once_with()
54 mock.reset_mock()
55
56 with pytest.raises(RuntimeError, match=r"^No error set\?$"):
57 raise_winerror(38)
58 mock.assert_called_once_with(38)
59 mock.reset_mock()
60
61 mock.return_value = (12, "test error")
62 with pytest.raises(
63 OSError,
64 match=r"^\[WinError 12\] test error: 'file_1' -> 'file_2'$",
65 ) as exc:
66 raise_winerror(filename="file_1", filename2="file_2")
67 mock.assert_called_once_with()
68 mock.reset_mock()
69 assert exc.value.winerror == 12
70 assert exc.value.strerror == "test error"
71 assert exc.value.filename == "file_1"
72 assert exc.value.filename2 == "file_2"
73
74 # With an explicit number passed in, it overrides what getwinerror() returns.
75 with pytest.raises(
76 OSError,
77 match=r"^\[WinError 18\] test error: 'a/file' -> 'b/file'$",
78 ) as exc:
79 raise_winerror(18, filename="a/file", filename2="b/file")
80 mock.assert_called_once_with(18)
81 mock.reset_mock()
82 assert exc.value.winerror == 18
83 assert exc.value.strerror == "test error"
84 assert exc.value.filename == "a/file"
85 assert exc.value.filename2 == "b/file"
86
87
88 # The undocumented API that this is testing should be changed to stop using
89 # UnboundedQueue (or just removed until we have time to redo it), but until
90 # then we filter out the warning.
91 @pytest.mark.filterwarnings("ignore:.*UnboundedQueue:trio.TrioDeprecationWarning")
92 async def test_completion_key_listen() -> None:
93 from .. import _io_windows
94
95 async def post(key: int) -> None:
96 iocp = Handle(ffi.cast("HANDLE", _core.current_iocp()))
97 for i in range(10):
98 print("post", i)
99 if i % 3 == 0:
100 await _core.checkpoint()
101 success = kernel32.PostQueuedCompletionStatus(iocp, i, key, ffi.NULL)
102 assert success
103
104 with _core.monitor_completion_key() as (key, queue):
105 async with _core.open_nursery() as nursery:
106 nursery.start_soon(post, key)
107 i = 0
108 print("loop")
109 async for batch in queue: # pragma: no branch
110 print("got some", batch)
111 for info in batch:
112 assert isinstance(info, _io_windows.CompletionKeyEventInfo)
113 assert info.lpOverlapped == 0
114 assert info.dwNumberOfBytesTransferred == i
115 i += 1
116 if i == 10:
117 break
118 print("end loop")
119
120
121 async def test_readinto_overlapped() -> None:
122 data = b"1" * 1024 + b"2" * 1024 + b"3" * 1024 + b"4" * 1024
123 buffer = bytearray(len(data))
124
125 with tempfile.TemporaryDirectory() as tdir:
126 tfile = os.path.join(tdir, "numbers.txt")
127 with open( # noqa: ASYNC230 # This is a test, synchronous is ok
128 tfile,
129 "wb",
130 ) as fp:
131 fp.write(data)
132 fp.flush()
133
134 rawname = tfile.encode("utf-16le") + b"\0\0"
135 rawname_buf = ffi.from_buffer(rawname)
136 handle = kernel32.CreateFileW(
137 ffi.cast("LPCWSTR", rawname_buf),
138 FileFlags.GENERIC_READ,
139 FileFlags.FILE_SHARE_READ,
140 ffi.NULL, # no security attributes
141 FileFlags.OPEN_EXISTING,
142 FileFlags.FILE_FLAG_OVERLAPPED,
143 ffi.NULL, # no template file
144 )
145 if handle == INVALID_HANDLE_VALUE: # pragma: no cover
146 raise_winerror()
147
148 try:
149 with memoryview(buffer) as buffer_view:
150
151 async def read_region(start: int, end: int) -> None:
152 await _core.readinto_overlapped(
153 handle,
154 buffer_view[start:end],
155 start,
156 )
157
158 _core.register_with_iocp(handle)
159 async with _core.open_nursery() as nursery:
160 for start in range(0, 4096, 512):
161 nursery.start_soon(read_region, start, start + 512)
162
163 assert buffer == data
164
165 with pytest.raises((BufferError, TypeError)):
166 await _core.readinto_overlapped(handle, b"immutable")
167 finally:
168 kernel32.CloseHandle(handle)
169
170
171 @contextmanager
172 def pipe_with_overlapped_read() -> Generator[tuple[BufferedWriter, int], None, None]:
173 import msvcrt
174 from asyncio.windows_utils import pipe
175
176 read_handle, write_handle = pipe(overlapped=(True, False))
177 try:
178 write_fd = msvcrt.open_osfhandle(write_handle, 0)
179 yield os.fdopen(write_fd, "wb", closefd=False), read_handle
180 finally:
181 kernel32.CloseHandle(Handle(ffi.cast("HANDLE", read_handle)))
182 kernel32.CloseHandle(Handle(ffi.cast("HANDLE", write_handle)))
183
184
185 @restore_unraisablehook()
186 def test_forgot_to_register_with_iocp() -> None:
187 with pipe_with_overlapped_read() as (write_fp, read_handle):
188 with write_fp:
189 write_fp.write(b"test\n")
190
191 left_run_yet = False
192
193 async def main() -> None:
194 target = bytearray(1)
195 try:
196 async with _core.open_nursery() as nursery:
197 nursery.start_soon(
198 _core.readinto_overlapped,
199 read_handle,
200 target,
201 name="xyz",
202 )
203 await wait_all_tasks_blocked()
204 nursery.cancel_scope.cancel()
205 finally:
206 # Run loop is exited without unwinding running tasks, so
207 # we don't get here until the main() coroutine is GC'ed
208 assert left_run_yet
209
210 with pytest.raises(_core.TrioInternalError) as exc_info:
211 _core.run(main)
212 left_run_yet = True
213 assert "Failed to cancel overlapped I/O in xyz " in str(exc_info.value)
214 assert "forget to call register_with_iocp()?" in str(exc_info.value)
215
216 # Make sure the Nursery.__del__ assertion about dangling children
217 # gets put with the correct test
218 del exc_info
219 gc_collect_harder()
220
221
222 @slow
223 async def test_too_late_to_cancel() -> None:
224 import time
225
226 with pipe_with_overlapped_read() as (write_fp, read_handle):
227 _core.register_with_iocp(read_handle)
228 target = bytearray(6)
229 async with _core.open_nursery() as nursery:
230 # Start an async read in the background
231 nursery.start_soon(_core.readinto_overlapped, read_handle, target)
232 await wait_all_tasks_blocked()
233
234 # Synchronous write to the other end of the pipe
235 with write_fp:
236 write_fp.write(b"test1\ntest2\n")
237
238 # Note: not trio.sleep! We're making sure the OS level
239 # ReadFile completes, before Trio has a chance to execute
240 # another checkpoint and notice it completed.
241 time.sleep(1) # noqa: ASYNC251
242 nursery.cancel_scope.cancel()
243 assert target[:6] == b"test1\n"
244
245 # Do another I/O to make sure we've actually processed the
246 # fallback completion that was posted when CancelIoEx failed.
247 assert await _core.readinto_overlapped(read_handle, target) == 6
248 assert target[:6] == b"test2\n"
249
250
251 def test_lsp_that_hooks_select_gives_good_error(
252 monkeypatch: pytest.MonkeyPatch,
253 ) -> None:
254 from .. import _io_windows
255 from .._windows_cffi import CData, WSAIoctls, _handle
256
257 def patched_get_underlying(
258 sock: int | CData,
259 *,
260 which: int = WSAIoctls.SIO_BASE_HANDLE,
261 ) -> CData:
262 if hasattr(sock, "fileno"): # pragma: no branch
263 sock = sock.fileno()
264 if which == WSAIoctls.SIO_BSP_HANDLE_SELECT:
265 return _handle(sock + 1)
266 else:
267 return _handle(sock)
268
269 monkeypatch.setattr(_io_windows, "_get_underlying_socket", patched_get_underlying)
270 with pytest.raises(
271 RuntimeError,
272 match="SIO_BASE_HANDLE and SIO_BSP_HANDLE_SELECT differ",
273 ):
274 _core.run(sleep, 0)
275
276
277 def test_lsp_that_completely_hides_base_socket_gives_good_error(
278 monkeypatch: pytest.MonkeyPatch,
279 ) -> None:
280 # This tests behavior with an LSP that fails SIO_BASE_HANDLE and returns
281 # self for SIO_BSP_HANDLE_SELECT (like Komodia), but also returns
282 # self for SIO_BSP_HANDLE_POLL. No known LSP does this, but we want to
283 # make sure we get an error rather than an infinite loop.
284
285 from .. import _io_windows
286 from .._windows_cffi import CData, WSAIoctls, _handle
287
288 def patched_get_underlying(
289 sock: int | CData,
290 *,
291 which: int = WSAIoctls.SIO_BASE_HANDLE,
292 ) -> CData:
293 if hasattr(sock, "fileno"): # pragma: no branch
294 sock = sock.fileno()
295 if which == WSAIoctls.SIO_BASE_HANDLE:
296 raise OSError("nope")
297 else:
298 return _handle(sock)
299
300 monkeypatch.setattr(_io_windows, "_get_underlying_socket", patched_get_underlying)
301 with pytest.raises(
302 RuntimeError,
303 match="SIO_BASE_HANDLE failed and SIO_BSP_HANDLE_POLL didn't return a diff",
304 ):
305 _core.run(sleep, 0)