Debian Codegraph @

tests/test_python_io.py

raw
1 from __future__ import annotations
2
3 import functools
4 import io
5 import types
6 from io import BytesIO
7 from re import escape
8 from typing import TYPE_CHECKING
9
10 import pytest
11
12 import av
13
14 from .common import TestCase, fate_png, fate_suite, has_pillow
15 from .test_encode import assert_rgb_rotate, write_rgb_rotate
16
17 if TYPE_CHECKING:
18 from collections.abc import Callable
19
20
21 class MethodLogger:
22 def __init__(self, obj: object) -> None:
23 self._obj = obj
24 self._log: list[tuple[str, object]] = []
25
26 def __getattr__(self, name: str) -> object:
27 def _method(name: str, meth: Callable, *args, **kwargs) -> object:
28 self._log.append((name, args))
29 return meth(*args, **kwargs)
30
31 value = getattr(self._obj, name)
32 if isinstance(
33 value,
34 (
35 types.MethodType,
36 types.FunctionType,
37 types.BuiltinFunctionType,
38 types.BuiltinMethodType,
39 ),
40 ):
41 return functools.partial(_method, name, value)
42 else:
43 self._log.append(("__getattr__", (name,)))
44 return value
45
46 def _filter(self, type_: str) -> list[tuple[str, object]]:
47 return [log for log in self._log if log[0] == type_]
48
49
50 class BrokenBuffer(BytesIO):
51 """
52 Buffer which can be "broken" to simulate an I/O error.
53 """
54
55 broken = False
56
57 def write(self, data):
58 if self.broken:
59 raise OSError("It's broken")
60 else:
61 return super().write(data)
62
63
64 class ReadOnlyBuffer:
65 """
66 Minimal buffer which *only* implements the read() method.
67 """
68
69 def __init__(self, data) -> None:
70 self.data = data
71
72 def read(self, n):
73 data = self.data[0:n]
74 self.data = self.data[n:]
75 return data
76
77
78 class ReadOnlyPipe(BytesIO):
79 """
80 Buffer which behaves like a readable pipe.
81 """
82
83 @property
84 def name(self) -> int:
85 return 123
86
87 def seekable(self) -> bool:
88 return False
89
90 def writable(self) -> bool:
91 return False
92
93
94 class WriteOnlyPipe(BytesIO):
95 """
96 Buffer which behaves like a writable pipe.
97 """
98
99 @property
100 def name(self) -> int:
101 return 123
102
103 def readable(self) -> bool:
104 return False
105
106 def seekable(self) -> bool:
107 return False
108
109
110 def read(
111 fh: io.BufferedReader | BytesIO | ReadOnlyBuffer, seekable: bool = True
112 ) -> None:
113 wrapped = MethodLogger(fh)
114
115 with av.open(wrapped, "r") as container:
116 assert container.format.name == "mpegts"
117 assert container.format.long_name == "MPEG-TS (MPEG-2 Transport Stream)"
118 assert len(container.streams) == 1
119 if seekable:
120 assert container.size == 800000
121 assert container.metadata == {}
122
123 # Check method calls.
124 assert wrapped._filter("read")
125 if seekable:
126 assert wrapped._filter("seek")
127
128
129 def write(fh: io.BufferedWriter | BytesIO) -> None:
130 wrapped = MethodLogger(fh)
131
132 with av.open(wrapped, "w", "mp4") as container:
133 write_rgb_rotate(container)
134
135 # Check method calls.
136 assert wrapped._filter("write")
137 assert wrapped._filter("seek")
138
139
140 # Using a custom protocol will avoid the DASH muxer detecting or defaulting to a
141 # file: protocol and enabling the use of temporary files and renaming.
142 CUSTOM_IO_PROTOCOL = "pyavtest://"
143
144
145 class CustomIOLogger:
146 """Log calls to open a file as well as method calls on the files"""
147
148 def __init__(self) -> None:
149 self._log: list[tuple[object, dict]] = []
150 self._method_log: list[MethodLogger] = []
151
152 def __call__(self, *args, **kwargs) -> MethodLogger:
153 self._log.append((args, kwargs))
154 self._method_log.append(self.io_open(*args, **kwargs))
155 return self._method_log[-1]
156
157 def io_open(self, url: str, flags, options: object) -> MethodLogger:
158 # Remove the protocol prefix to reveal the local filename
159 if CUSTOM_IO_PROTOCOL in url:
160 url = url.split(CUSTOM_IO_PROTOCOL, 1)[1]
161
162 if (flags & 3) == 3:
163 mode = "r+b"
164 elif (flags & 1) == 1:
165 mode = "rb"
166 elif (flags & 2) == 2:
167 mode = "wb"
168 else:
169 raise RuntimeError(f"Unsupported io open mode {flags}")
170
171 return MethodLogger(open(url, mode))
172
173
174 class TestPythonIO(TestCase):
175 def test_basic_errors(self) -> None:
176 self.assertRaises(Exception, av.open, None)
177 self.assertRaises(Exception, av.open, None, "w")
178
179 def test_reading_from_buffer(self) -> None:
180 with open(fate_suite("mpeg2/mpeg2_field_encoding.ts"), "rb") as fh:
181 buf = BytesIO(fh.read())
182 read(buf, seekable=True)
183
184 def test_reading_from_buffer_no_seek(self) -> None:
185 with open(fate_suite("mpeg2/mpeg2_field_encoding.ts"), "rb") as fh:
186 buf = ReadOnlyBuffer(fh.read())
187 read(buf, seekable=False)
188
189 def test_reading_from_file(self) -> None:
190 with open(fate_suite("mpeg2/mpeg2_field_encoding.ts"), "rb") as fh:
191 read(fh, seekable=True)
192
193 def test_reading_from_pipe_readonly(self) -> None:
194 with open(fate_suite("mpeg2/mpeg2_field_encoding.ts"), "rb") as fh:
195 buf = ReadOnlyPipe(fh.read())
196 read(buf, seekable=False)
197
198 def test_reading_from_write_readonly(self) -> None:
199 with open(fate_suite("mpeg2/mpeg2_field_encoding.ts"), "rb") as fh:
200 buf = WriteOnlyPipe(fh.read())
201
202 msg = escape("File object has no read() method, or readable() returned False.")
203 with pytest.raises(ValueError, match=msg):
204 read(buf, seekable=False)
205
206 def test_writing_to_buffer(self) -> None:
207 buf = BytesIO()
208
209 write(buf)
210
211 # Check contents.
212 assert buf.tell()
213 buf.seek(0)
214 with av.open(buf, "r") as container:
215 assert_rgb_rotate(self, container)
216
217 def test_writing_to_buffer_broken(self) -> None:
218 buf = BrokenBuffer()
219
220 with pytest.raises(OSError):
221 with av.open(buf, "w", "mp4") as container:
222 write_rgb_rotate(container)
223
224 # break I/O
225 buf.broken = True
226
227 def test_writing_to_buffer_broken_with_close(self) -> None:
228 buf = BrokenBuffer()
229
230 with av.open(buf, "w", "mp4") as container:
231 write_rgb_rotate(container)
232
233 # break I/O
234 buf.broken = True
235
236 # try to close file
237 with pytest.raises(OSError):
238 container.close()
239
240 def test_writing_to_custom_io_image2(self) -> None:
241 if not has_pillow:
242 pytest.skip()
243
244 import PIL.Image as Image
245
246 # Custom I/O that opens file and logs calls
247 wrapped_custom_io = CustomIOLogger()
248
249 image = Image.open(fate_png())
250 input_frame = av.VideoFrame.from_image(image)
251
252 frame_count = 10
253 sequence_filename = self.sandboxed("test%d.png")
254 width = 160
255 height = 90
256
257 # Write a PNG image sequence using the custom IO
258 with av.open(
259 sequence_filename, "w", "image2", io_open=wrapped_custom_io
260 ) as output:
261 stream = output.add_stream("png")
262 stream.width = width
263 stream.height = height
264 stream.pix_fmt = "rgb24"
265
266 for _ in range(frame_count):
267 for packet in stream.encode(input_frame):
268 output.mux(packet)
269
270 # Check that "frame_count" files were opened using the custom IO
271 assert len(wrapped_custom_io._log) == frame_count
272 assert len(wrapped_custom_io._method_log) == frame_count
273
274 # Check that all files were written to
275 all_write = all(
276 method_log._filter("write") for method_log in wrapped_custom_io._method_log
277 )
278 assert all_write
279
280 # Check that all files were closed
281 all_closed = all(
282 method_log._filter("close") for method_log in wrapped_custom_io._method_log
283 )
284 assert all_closed
285
286 # Check contents.
287 with av.open(sequence_filename, "r", "image2") as container:
288 assert len(container.streams) == 1
289 assert isinstance(container.streams[0], av.video.stream.VideoStream)
290
291 stream = container.streams[0]
292 assert stream.duration == frame_count
293 assert stream.type == "video"
294
295 # codec context properties
296 assert stream.codec.name == "png"
297 assert stream.format.name == "rgb24"
298 assert stream.format.width == width
299 assert stream.format.height == height
300
301 def test_writing_to_file(self) -> None:
302 path = self.sandboxed("writing.mp4")
303
304 with open(path, "wb") as fh:
305 write(fh)
306
307 # Check contents.
308 with av.open(path) as container:
309 assert_rgb_rotate(self, container)
310
311 def test_writing_to_pipe_readonly(self) -> None:
312 buf = ReadOnlyPipe()
313 with pytest.raises(
314 ValueError,
315 match=escape(
316 "File object has no write() method, or writable() returned False."
317 ),
318 ) as cm:
319 write(buf)
320
321 def test_writing_to_pipe_writeonly(self) -> None:
322 av.logging.set_level(av.logging.VERBOSE)
323
324 buf = WriteOnlyPipe()
325 with pytest.raises(
326 av.ArgumentError,
327 match=escape("[mp4] muxer does not support non seekable output"),
328 ):
329 write(buf)
330
331 av.logging.set_level(None)