Debian Codegraph @

src/trio/_tests/test_file_io.py

raw
1 from __future__ import annotations
2
3 import importlib
4 import io
5 import os
6 import re
7 from typing import TYPE_CHECKING
8 from unittest import mock
9 from unittest.mock import sentinel
10
11 import pytest
12
13 import trio
14 from trio import _core, _file_io
15 from trio._file_io import _FILE_ASYNC_METHODS, _FILE_SYNC_ATTRS, AsyncIOWrapper
16
17 if TYPE_CHECKING:
18 import pathlib
19
20
21 @pytest.fixture
22 def path(tmp_path: pathlib.Path) -> str:
23 return os.fspath(tmp_path / "test")
24
25
26 @pytest.fixture
27 def wrapped() -> mock.Mock:
28 return mock.Mock(spec_set=io.StringIO)
29
30
31 @pytest.fixture
32 def async_file(wrapped: mock.Mock) -> AsyncIOWrapper[mock.Mock]:
33 return trio.wrap_file(wrapped)
34
35
36 def test_wrap_invalid() -> None:
37 with pytest.raises(TypeError):
38 trio.wrap_file("")
39
40
41 def test_wrap_non_iobase() -> None:
42 class FakeFile:
43 def close(self) -> None: # pragma: no cover
44 pass
45
46 def write(self) -> None: # pragma: no cover
47 pass
48
49 wrapped = FakeFile()
50 assert not isinstance(wrapped, io.IOBase)
51
52 async_file = trio.wrap_file(wrapped)
53 assert isinstance(async_file, AsyncIOWrapper)
54
55 del FakeFile.write
56
57 with pytest.raises(TypeError):
58 trio.wrap_file(FakeFile())
59
60
61 def test_wrapped_property(
62 async_file: AsyncIOWrapper[mock.Mock],
63 wrapped: mock.Mock,
64 ) -> None:
65 assert async_file.wrapped is wrapped
66
67
68 def test_dir_matches_wrapped(
69 async_file: AsyncIOWrapper[mock.Mock],
70 wrapped: mock.Mock,
71 ) -> None:
72 attrs = _FILE_SYNC_ATTRS.union(_FILE_ASYNC_METHODS)
73
74 # all supported attrs in wrapped should be available in async_file
75 assert all(attr in dir(async_file) for attr in attrs if attr in dir(wrapped))
76 # all supported attrs not in wrapped should not be available in async_file
77 assert not any(
78 attr in dir(async_file) for attr in attrs if attr not in dir(wrapped)
79 )
80
81
82 def test_unsupported_not_forwarded() -> None:
83 class FakeFile(io.RawIOBase):
84 def unsupported_attr(self) -> None: # pragma: no cover
85 pass
86
87 async_file = trio.wrap_file(FakeFile())
88
89 assert hasattr(async_file.wrapped, "unsupported_attr")
90
91 with pytest.raises(AttributeError):
92 # B018 "useless expression"
93 async_file.unsupported_attr # type: ignore[attr-defined] # noqa: B018
94
95
96 def test_type_stubs_match_lists() -> None:
97 """Check the manual stubs match the list of wrapped methods."""
98 # Fetch the module's source code.
99 assert _file_io.__spec__ is not None
100 loader = _file_io.__spec__.loader
101 assert isinstance(loader, importlib.abc.SourceLoader)
102 source = io.StringIO(loader.get_source("trio._file_io"))
103
104 # Find the class, then find the TYPE_CHECKING block.
105 for line in source:
106 if "class AsyncIOWrapper" in line:
107 break
108 else: # pragma: no cover - should always find this
109 pytest.fail("No class definition line?")
110
111 for line in source:
112 if "if TYPE_CHECKING" in line:
113 break
114 else: # pragma: no cover - should always find this
115 pytest.fail("No TYPE CHECKING line?")
116
117 # Now we should be at the type checking block.
118 found: list[tuple[str, str]] = []
119 for line in source: # pragma: no branch - expected to break early
120 if line.strip() and not line.startswith(" " * 8):
121 break # Dedented out of the if TYPE_CHECKING block.
122 match = re.match(r"\s*(async )?def ([a-zA-Z0-9_]+)\(", line)
123 if match is not None:
124 kind = "async" if match.group(1) is not None else "sync"
125 found.append((match.group(2), kind))
126
127 # Compare two lists so that we can easily see duplicates, and see what is different overall.
128 expected = [(fname, "async") for fname in _FILE_ASYNC_METHODS]
129 expected += [(fname, "sync") for fname in _FILE_SYNC_ATTRS]
130 # Ignore order, error if duplicates are present.
131 found.sort()
132 expected.sort()
133 assert found == expected
134
135
136 def test_sync_attrs_forwarded(
137 async_file: AsyncIOWrapper[mock.Mock],
138 wrapped: mock.Mock,
139 ) -> None:
140 for attr_name in _FILE_SYNC_ATTRS:
141 if attr_name not in dir(async_file):
142 continue
143
144 assert getattr(async_file, attr_name) is getattr(wrapped, attr_name)
145
146
147 def test_sync_attrs_match_wrapper(
148 async_file: AsyncIOWrapper[mock.Mock],
149 wrapped: mock.Mock,
150 ) -> None:
151 for attr_name in _FILE_SYNC_ATTRS:
152 if attr_name in dir(async_file):
153 continue
154
155 with pytest.raises(AttributeError):
156 getattr(async_file, attr_name)
157
158 with pytest.raises(AttributeError):
159 getattr(wrapped, attr_name)
160
161
162 def test_async_methods_generated_once(async_file: AsyncIOWrapper[mock.Mock]) -> None:
163 for meth_name in _FILE_ASYNC_METHODS:
164 if meth_name not in dir(async_file):
165 continue
166
167 assert getattr(async_file, meth_name) is getattr(async_file, meth_name)
168
169
170 # I gave up on typing this one
171 def test_async_methods_signature(async_file: AsyncIOWrapper[mock.Mock]) -> None:
172 # use read as a representative of all async methods
173 assert async_file.read.__name__ == "read"
174 assert async_file.read.__qualname__ == "AsyncIOWrapper.read"
175
176 assert async_file.read.__doc__ is not None
177 assert "io.StringIO.read" in async_file.read.__doc__
178
179
180 async def test_async_methods_wrap(
181 async_file: AsyncIOWrapper[mock.Mock],
182 wrapped: mock.Mock,
183 ) -> None:
184 for meth_name in _FILE_ASYNC_METHODS:
185 if meth_name not in dir(async_file):
186 continue
187
188 meth = getattr(async_file, meth_name)
189 wrapped_meth = getattr(wrapped, meth_name)
190
191 value = await meth(sentinel.argument, keyword=sentinel.keyword)
192
193 wrapped_meth.assert_called_once_with(
194 sentinel.argument,
195 keyword=sentinel.keyword,
196 )
197 assert value == wrapped_meth()
198
199 wrapped.reset_mock()
200
201
202 def test_async_methods_match_wrapper(
203 async_file: AsyncIOWrapper[mock.Mock],
204 wrapped: mock.Mock,
205 ) -> None:
206 for meth_name in _FILE_ASYNC_METHODS:
207 if meth_name in dir(async_file):
208 continue
209
210 with pytest.raises(AttributeError):
211 getattr(async_file, meth_name)
212
213 with pytest.raises(AttributeError):
214 getattr(wrapped, meth_name)
215
216
217 async def test_open(path: pathlib.Path) -> None:
218 f = await trio.open_file(path, "w")
219
220 assert isinstance(f, AsyncIOWrapper)
221
222 await f.aclose()
223
224
225 async def test_open_context_manager(path: pathlib.Path) -> None:
226 async with await trio.open_file(path, "w") as f:
227 assert isinstance(f, AsyncIOWrapper)
228 assert not f.closed
229
230 assert f.closed
231
232
233 async def test_async_iter() -> None:
234 async_file = trio.wrap_file(io.StringIO("test\nfoo\nbar"))
235 expected = list(async_file.wrapped)
236 async_file.wrapped.seek(0)
237
238 result = [line async for line in async_file]
239
240 assert result == expected
241
242
243 async def test_aclose_cancelled(path: pathlib.Path) -> None:
244 with _core.CancelScope() as cscope:
245 f = await trio.open_file(path, "w")
246 cscope.cancel()
247
248 with pytest.raises(_core.Cancelled):
249 await f.write("a")
250
251 with pytest.raises(_core.Cancelled):
252 await f.aclose()
253
254 assert f.closed
255
256
257 async def test_detach_rewraps_asynciobase(tmp_path: pathlib.Path) -> None:
258 tmp_file = tmp_path / "filename"
259 tmp_file.touch()
260 # flake8-async does not like opening files in async mode
261 with open(tmp_file, mode="rb", buffering=0) as raw: # noqa: ASYNC230
262 buffered = io.BufferedReader(raw)
263
264 async_file = trio.wrap_file(buffered)
265
266 detached = await async_file.detach()
267
268 assert isinstance(detached, AsyncIOWrapper)
269 assert detached.wrapped is raw