Debian Codegraph @

src/trio/_tests/test_unix_pipes.py

raw
1 from __future__ import annotations
2
3 import errno
4 import os
5 import select
6 import sys
7 from typing import TYPE_CHECKING
8
9 import pytest
10
11 from .. import _core
12 from .._core._tests.tutil import gc_collect_harder, skip_if_fbsd_pipes_broken
13 from ..testing import check_one_way_stream, wait_all_tasks_blocked
14
15 if TYPE_CHECKING:
16 from .._file_io import _HasFileNo
17
18 posix = os.name == "posix"
19 pytestmark = pytest.mark.skipif(not posix, reason="posix only")
20
21 assert not TYPE_CHECKING or sys.platform == "unix"
22
23 if posix:
24 from .._unix_pipes import FdStream
25
26
27 async def make_pipe() -> tuple[FdStream, FdStream]:
28 """Makes a new pair of pipes."""
29 r, w = os.pipe()
30 return FdStream(w), FdStream(r)
31
32
33 async def make_clogged_pipe() -> tuple[FdStream, FdStream]:
34 s, r = await make_pipe()
35 try:
36 while True:
37 # We want to totally fill up the pipe buffer.
38 # This requires working around a weird feature that POSIX pipes
39 # have.
40 # If you do a write of <= PIPE_BUF bytes, then it's guaranteed
41 # to either complete entirely, or not at all. So if we tried to
42 # write PIPE_BUF bytes, and the buffer's free space is only
43 # PIPE_BUF/2, then the write will raise BlockingIOError... even
44 # though a smaller write could still succeed! To avoid this,
45 # make sure to write >PIPE_BUF bytes each time, which disables
46 # the special behavior.
47 # For details, search for PIPE_BUF here:
48 # http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html
49
50 # for the getattr:
51 # https://bitbucket.org/pypy/pypy/issues/2876/selectpipe_buf-is-missing-on-pypy3
52 buf_size = getattr(select, "PIPE_BUF", 8192)
53 os.write(s.fileno(), b"x" * buf_size * 2)
54 except BlockingIOError:
55 pass
56 return s, r
57
58
59 async def test_send_pipe() -> None:
60 r, w = os.pipe()
61 async with FdStream(w) as send:
62 assert send.fileno() == w
63 await send.send_all(b"123")
64 assert (os.read(r, 8)) == b"123"
65
66 os.close(r)
67
68
69 async def test_receive_pipe() -> None:
70 r, w = os.pipe()
71 async with FdStream(r) as recv:
72 assert (recv.fileno()) == r
73 os.write(w, b"123")
74 assert (await recv.receive_some(8)) == b"123"
75
76 os.close(w)
77
78
79 async def test_pipes_combined() -> None:
80 write, read = await make_pipe()
81 count = 2**20
82
83 async def sender() -> None:
84 big = bytearray(count)
85 await write.send_all(big)
86
87 async def reader() -> None:
88 await wait_all_tasks_blocked()
89 received = 0
90 while received < count:
91 received += len(await read.receive_some(4096))
92
93 assert received == count
94
95 async with _core.open_nursery() as n:
96 n.start_soon(sender)
97 n.start_soon(reader)
98
99 await read.aclose()
100 await write.aclose()
101
102
103 async def test_pipe_errors() -> None:
104 with pytest.raises(TypeError):
105 FdStream(None)
106
107 r, w = os.pipe()
108 os.close(w)
109 async with FdStream(r) as s:
110 with pytest.raises(ValueError, match=r"^max_bytes must be integer >= 1$"):
111 await s.receive_some(0)
112
113
114 async def test_del() -> None:
115 w, r = await make_pipe()
116 f1, f2 = w.fileno(), r.fileno()
117 del w, r
118 gc_collect_harder()
119
120 with pytest.raises(OSError, match=r"Bad file descriptor$") as excinfo:
121 os.close(f1)
122 assert excinfo.value.errno == errno.EBADF
123
124 with pytest.raises(OSError, match=r"Bad file descriptor$") as excinfo:
125 os.close(f2)
126 assert excinfo.value.errno == errno.EBADF
127
128
129 async def test_async_with() -> None:
130 w, r = await make_pipe()
131 async with w, r:
132 pass
133
134 assert w.fileno() == -1
135 assert r.fileno() == -1
136
137 with pytest.raises(OSError, match=r"Bad file descriptor$") as excinfo:
138 os.close(w.fileno())
139 assert excinfo.value.errno == errno.EBADF
140
141 with pytest.raises(OSError, match=r"Bad file descriptor$") as excinfo:
142 os.close(r.fileno())
143 assert excinfo.value.errno == errno.EBADF
144
145
146 async def test_misdirected_aclose_regression() -> None:
147 # https://github.com/python-trio/trio/issues/661#issuecomment-456582356
148 w, r = await make_pipe()
149 old_r_fd = r.fileno()
150
151 # Close the original objects
152 await w.aclose()
153 await r.aclose()
154
155 # Do a little dance to get a new pipe whose receive handle matches the old
156 # receive handle.
157 r2_fd, w2_fd = os.pipe()
158 if r2_fd != old_r_fd: # pragma: no cover
159 os.dup2(r2_fd, old_r_fd)
160 os.close(r2_fd)
161 async with FdStream(old_r_fd) as r2:
162 assert r2.fileno() == old_r_fd
163
164 # And now set up a background task that's working on the new receive
165 # handle
166 async def expect_eof() -> None:
167 assert await r2.receive_some(10) == b""
168
169 async with _core.open_nursery() as nursery:
170 nursery.start_soon(expect_eof)
171 await wait_all_tasks_blocked()
172
173 # Here's the key test: does calling aclose() again on the *old*
174 # handle, cause the task blocked on the *new* handle to raise
175 # ClosedResourceError?
176 await r.aclose()
177 await wait_all_tasks_blocked()
178
179 # Guess we survived! Close the new write handle so that the task
180 # gets an EOF and can exit cleanly.
181 os.close(w2_fd)
182
183
184 async def test_close_at_bad_time_for_receive_some(
185 monkeypatch: pytest.MonkeyPatch,
186 ) -> None:
187 # We used to have race conditions where if one task was using the pipe,
188 # and another closed it at *just* the wrong moment, it would give an
189 # unexpected error instead of ClosedResourceError:
190 # https://github.com/python-trio/trio/issues/661
191 #
192 # This tests what happens if the pipe gets closed in the moment *between*
193 # when receive_some wakes up, and when it tries to call os.read
194 async def expect_closedresourceerror() -> None:
195 with pytest.raises(_core.ClosedResourceError):
196 await r.receive_some(10)
197
198 orig_wait_readable = _core._run.TheIOManager.wait_readable
199
200 async def patched_wait_readable(
201 self: _core._run.TheIOManager,
202 fd: int | _HasFileNo,
203 ) -> None:
204 await orig_wait_readable(self, fd)
205 await r.aclose()
206
207 monkeypatch.setattr(_core._run.TheIOManager, "wait_readable", patched_wait_readable)
208 s, r = await make_pipe()
209 async with s, r:
210 async with _core.open_nursery() as nursery:
211 nursery.start_soon(expect_closedresourceerror)
212 await wait_all_tasks_blocked()
213 # Trigger everything by waking up the receiver
214 await s.send_all(b"x")
215
216
217 async def test_close_at_bad_time_for_send_all(monkeypatch: pytest.MonkeyPatch) -> None:
218 # We used to have race conditions where if one task was using the pipe,
219 # and another closed it at *just* the wrong moment, it would give an
220 # unexpected error instead of ClosedResourceError:
221 # https://github.com/python-trio/trio/issues/661
222 #
223 # This tests what happens if the pipe gets closed in the moment *between*
224 # when send_all wakes up, and when it tries to call os.write
225 async def expect_closedresourceerror() -> None:
226 with pytest.raises(_core.ClosedResourceError):
227 await s.send_all(b"x" * 100)
228
229 orig_wait_writable = _core._run.TheIOManager.wait_writable
230
231 async def patched_wait_writable(
232 self: _core._run.TheIOManager,
233 fd: int | _HasFileNo,
234 ) -> None:
235 await orig_wait_writable(self, fd)
236 await s.aclose()
237
238 monkeypatch.setattr(_core._run.TheIOManager, "wait_writable", patched_wait_writable)
239 s, r = await make_clogged_pipe()
240 async with s, r:
241 async with _core.open_nursery() as nursery:
242 nursery.start_soon(expect_closedresourceerror)
243 await wait_all_tasks_blocked()
244 # Trigger everything by waking up the sender. On ppc64el, PIPE_BUF
245 # is 8192 but make_clogged_pipe() ends up writing a total of
246 # 1048576 bytes before the pipe is full, and then a subsequent
247 # receive_some(10000) isn't sufficient for orig_wait_writable() to
248 # return for our subsequent aclose() call. It's necessary to empty
249 # the pipe further before this happens. So we loop here until the
250 # pipe is empty to make sure that the sender wakes up even in this
251 # case. Otherwise patched_wait_writable() never gets to the
252 # aclose(), so expect_closedresourceerror() never returns, the
253 # nursery never finishes all tasks and this test hangs.
254 received_data = await r.receive_some(10000)
255 while received_data:
256 received_data = await r.receive_some(10000)
257
258
259 # On FreeBSD, directories are readable, and we haven't found any other trick
260 # for making an unreadable fd, so there's no way to run this test. Fortunately
261 # the logic this is testing doesn't depend on the platform, so testing on
262 # other platforms is probably good enough.
263 @pytest.mark.skipif(
264 sys.platform.startswith("freebsd"),
265 reason="no way to make read() return a bizarro error on FreeBSD",
266 )
267 async def test_bizarro_OSError_from_receive() -> None:
268 # Make sure that if the read syscall returns some bizarro error, then we
269 # get a BrokenResourceError. This is incredibly unlikely; there's almost
270 # no way to trigger a failure here intentionally (except for EBADF, but we
271 # exploit that to detect file closure, so it takes a different path). So
272 # we set up a strange scenario where the pipe fd somehow transmutes into a
273 # directory fd, causing os.read to raise IsADirectoryError (yes, that's a
274 # real built-in exception type).
275 s, r = await make_pipe()
276 async with s, r:
277 dir_fd = os.open("/", os.O_DIRECTORY, 0)
278 try:
279 os.dup2(dir_fd, r.fileno())
280 with pytest.raises(_core.BrokenResourceError):
281 await r.receive_some(10)
282 finally:
283 os.close(dir_fd)
284
285
286 @skip_if_fbsd_pipes_broken
287 async def test_pipe_fully() -> None:
288 await check_one_way_stream(make_pipe, make_clogged_pipe)