Debian Codegraph @

tests/test_iochannel.py

raw
1 import os
2 import unittest
3 import tempfile
4 import os.path
5 import shutil
6 import warnings
7
8 try:
9 import fcntl
10 except ImportError:
11 fcntl = None
12
13 from gi.repository import GLib
14 from gi import PyGIDeprecationWarning
15
16
17 class IOChannel(unittest.TestCase):
18 def setUp(self):
19 self.workdir = tempfile.mkdtemp()
20
21 self.testutf8 = os.path.join(self.workdir, "testutf8.txt")
22 with open(self.testutf8, "wb") as f:
23 f.write(
24 """hello ♥ world
25 second line
26
27 À demain!""".encode()
28 )
29
30 self.testlatin1 = os.path.join(self.workdir, "testlatin1.txt")
31 with open(self.testlatin1, "wb") as f:
32 f.write(b"""hell\xf8 world
33 second line
34
35 \xc0 demain!""")
36
37 self.testout = os.path.join(self.workdir, "testout.txt")
38
39 def tearDown(self):
40 shutil.rmtree(self.workdir)
41
42 def test_file_readline_utf8(self):
43 ch = GLib.IOChannel(filename=self.testutf8)
44 self.assertEqual(ch.get_encoding(), "UTF-8")
45 self.assertTrue(ch.get_close_on_unref())
46 self.assertEqual(ch.readline(), "hello ♥ world\n")
47 self.assertEqual(ch.get_buffer_condition(), GLib.IOCondition.IN)
48 self.assertEqual(ch.readline(), "second line\n")
49 self.assertEqual(ch.readline(), "\n")
50 self.assertEqual(ch.readline(), "À demain!")
51 self.assertEqual(ch.get_buffer_condition(), 0)
52 self.assertEqual(ch.readline(), "")
53 ch.shutdown(True)
54
55 def test_file_readline_latin1(self):
56 ch = GLib.IOChannel(filename=self.testlatin1, mode="r")
57 ch.set_encoding("latin1")
58 self.assertEqual(ch.get_encoding(), "latin1")
59 self.assertEqual(ch.readline(), "hellø world\n")
60 self.assertEqual(ch.readline(), "second line\n")
61 self.assertEqual(ch.readline(), "\n")
62 self.assertEqual(ch.readline(), "À demain!")
63 ch.shutdown(True)
64
65 def test_file_iter(self):
66 items = []
67 ch = GLib.IOChannel(filename=self.testutf8)
68 for item in ch:
69 items.append(item) # noqa: PERF402
70 self.assertEqual(len(items), 4)
71 self.assertEqual(items[0], "hello ♥ world\n")
72 ch.shutdown(True)
73
74 def test_file_readlines(self):
75 ch = GLib.IOChannel(filename=self.testutf8)
76 lines = ch.readlines()
77 # Note, this really ought to be 4, but the static bindings add an extra
78 # empty one
79 self.assertGreaterEqual(len(lines), 4)
80 self.assertLessEqual(len(lines), 5)
81 self.assertEqual(lines[0], "hello ♥ world\n")
82 self.assertEqual(lines[3], "À demain!")
83 if len(lines) == 4:
84 self.assertEqual(lines[4], "")
85
86 def test_file_read(self):
87 ch = GLib.IOChannel(filename=self.testutf8)
88 with open(self.testutf8, "rb") as f:
89 self.assertEqual(ch.read(), f.read())
90
91 ch = GLib.IOChannel(filename=self.testutf8)
92 with open(self.testutf8, "rb") as f:
93 self.assertEqual(ch.read(10), f.read(10))
94
95 ch = GLib.IOChannel(filename=self.testutf8)
96 with open(self.testutf8, "rb") as f:
97 self.assertEqual(ch.read(max_count=15), f.read(15))
98
99 def test_file_read_chars(self):
100 ch = GLib.IOChannel(filename=self.testutf8)
101 with open(self.testutf8, "rb") as f:
102 self.assertEqual(ch.read_chars(), f.read())
103
104 def test_seek(self):
105 ch = GLib.IOChannel(filename=self.testutf8)
106 ch.seek(2)
107 self.assertEqual(ch.read(3), b"llo")
108
109 ch.seek(2, 0) # SEEK_SET
110 self.assertEqual(ch.read(3), b"llo")
111
112 ch.seek(1, 1) # SEEK_CUR, skip the space
113 self.assertEqual(ch.read(3), b"\xe2\x99\xa5")
114
115 ch.seek(2, 2) # SEEK_END
116 # FIXME: does not work currently
117 # self.assertEqual(ch.read(2), b'n!')
118
119 # invalid whence value
120 self.assertRaises(ValueError, ch.seek, 0, 3)
121 ch.shutdown(True)
122
123 def test_file_write(self):
124 ch = GLib.IOChannel(filename=self.testout, mode="w")
125 ch.set_encoding("latin1")
126 ch.write("hellø world\n")
127 ch.shutdown(True)
128 ch = GLib.IOChannel(filename=self.testout, mode="a")
129 ch.set_encoding("latin1")
130 ch.write("À demain!")
131 ch.shutdown(True)
132
133 with open(self.testout, "rb") as f:
134 self.assertEqual(f.read().decode("latin1"), "hellø world\nÀ demain!")
135
136 def test_file_writelines(self):
137 ch = GLib.IOChannel(filename=self.testout, mode="w")
138 ch.writelines(["foo", "bar\n", "baz\n", "end"])
139 ch.shutdown(True)
140
141 with open(self.testout) as f:
142 self.assertEqual(f.read(), "foobar\nbaz\nend")
143
144 def test_buffering(self):
145 writer = GLib.IOChannel(filename=self.testout, mode="w")
146 writer.set_encoding(None)
147 self.assertTrue(writer.get_buffered())
148 self.assertGreater(writer.get_buffer_size(), 10)
149
150 reader = GLib.IOChannel(filename=self.testout, mode="r")
151
152 # does not get written immediately on buffering
153 writer.write("abc")
154 self.assertEqual(reader.read(), b"")
155 writer.flush()
156 self.assertEqual(reader.read(), b"abc")
157
158 # does get written immediately without buffering
159 writer.set_buffered(False)
160 writer.write("def")
161 self.assertEqual(reader.read(), b"def")
162
163 # writes after buffer overflow
164 writer.set_buffer_size(10)
165 writer.write("0123456789012")
166 self.assertTrue(reader.read().startswith(b"012"))
167 writer.flush()
168 reader.read() # ignore bits written after flushing
169
170 # closing flushes
171 writer.set_buffered(True)
172 writer.write("ghi")
173 writer.shutdown(True)
174 self.assertEqual(reader.read(), b"ghi")
175 reader.shutdown(True)
176
177 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
178 def test_fd_read(self):
179 (r, w) = os.pipe()
180
181 ch = GLib.IOChannel(filedes=r)
182 ch.set_encoding(None)
183 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
184 self.assertNotEqual(ch.get_flags() | GLib.IOFlags.NONBLOCK, 0)
185 self.assertEqual(ch.read(), b"")
186 os.write(w, b"\x01\x02")
187 self.assertEqual(ch.read(), b"\x01\x02")
188
189 # now test blocking case, after closing the write end
190 ch.set_flags(GLib.IOFlags(ch.get_flags() & ~GLib.IOFlags.NONBLOCK))
191 os.write(w, b"\x03\x04")
192 os.close(w)
193 self.assertEqual(ch.read(), b"\x03\x04")
194
195 ch.shutdown(True)
196
197 @unittest.skipUnless(fcntl, "no fcntl")
198 def test_fd_write(self):
199 (r, w) = os.pipe()
200 fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) | os.O_NONBLOCK)
201
202 ch = GLib.IOChannel(filedes=w, mode="w")
203 ch.set_encoding(None)
204 ch.set_buffered(False)
205 ch.write(b"\x01\x02")
206 self.assertEqual(os.read(r, 10), b"\x01\x02")
207
208 # now test blocking case, after closing the write end
209 fcntl.fcntl(r, fcntl.F_SETFL, fcntl.fcntl(r, fcntl.F_GETFL) & ~os.O_NONBLOCK)
210 ch.write(b"\x03\x04")
211 ch.shutdown(True)
212 self.assertEqual(os.read(r, 10), b"\x03\x04")
213 os.close(r)
214
215 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
216 def test_deprecated_method_add_watch_no_data(self):
217 (r, w) = os.pipe()
218
219 ch = GLib.IOChannel(filedes=r)
220 ch.set_encoding(None)
221 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
222
223 cb_reads = []
224
225 def cb(channel, condition):
226 self.assertEqual(channel, ch)
227 self.assertEqual(condition, GLib.IOCondition.IN)
228 cb_reads.append(channel.read())
229 if len(cb_reads) == 2:
230 ml.quit()
231 return True
232
233 # io_add_watch() method is deprecated, use GLib.io_add_watch
234 with warnings.catch_warnings(record=True) as warn:
235 warnings.simplefilter("always")
236 ch.add_watch(GLib.IOCondition.IN, cb, priority=GLib.PRIORITY_HIGH)
237 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
238
239 def write():
240 os.write(w, b"a")
241 GLib.idle_add(lambda: os.write(w, b"b") and False)
242
243 ml = GLib.MainLoop()
244 GLib.idle_add(write)
245 GLib.timeout_add(2000, ml.quit)
246 ml.run()
247
248 self.assertEqual(cb_reads, [b"a", b"b"])
249
250 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
251 def test_deprecated_method_add_watch_data_priority(self):
252 (r, w) = os.pipe()
253
254 ch = GLib.IOChannel(filedes=r)
255 ch.set_encoding(None)
256 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
257
258 cb_reads = []
259
260 def cb(channel, condition, data):
261 self.assertEqual(channel, ch)
262 self.assertEqual(condition, GLib.IOCondition.IN)
263 self.assertEqual(data, "hello")
264 cb_reads.append(channel.read())
265 if len(cb_reads) == 2:
266 ml.quit()
267 return True
268
269 ml = GLib.MainLoop()
270 # io_add_watch() method is deprecated, use GLib.io_add_watch
271 with warnings.catch_warnings(record=True) as warn:
272 warnings.simplefilter("always")
273 id = ch.add_watch(
274 GLib.IOCondition.IN, cb, "hello", priority=GLib.PRIORITY_HIGH
275 )
276 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
277
278 self.assertEqual(
279 ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH
280 )
281
282 def write():
283 os.write(w, b"a")
284 GLib.idle_add(lambda: os.write(w, b"b") and False)
285
286 GLib.idle_add(write)
287 GLib.timeout_add(2000, ml.quit)
288 ml.run()
289
290 self.assertEqual(cb_reads, [b"a", b"b"])
291
292 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
293 def test_add_watch_no_data(self):
294 (r, w) = os.pipe()
295
296 ch = GLib.IOChannel(filedes=r)
297 ch.set_encoding(None)
298 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
299
300 cb_reads = []
301
302 def cb(channel, condition):
303 self.assertEqual(channel, ch)
304 self.assertEqual(condition, GLib.IOCondition.IN)
305 cb_reads.append(channel.read())
306 if len(cb_reads) == 2:
307 ml.quit()
308 return True
309
310 id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb)
311
312 ml = GLib.MainLoop()
313 self.assertEqual(
314 ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH
315 )
316
317 def write():
318 os.write(w, b"a")
319 GLib.idle_add(lambda: os.write(w, b"b") and False)
320
321 GLib.idle_add(write)
322 GLib.timeout_add(2000, ml.quit)
323 ml.run()
324
325 self.assertEqual(cb_reads, [b"a", b"b"])
326
327 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
328 def test_add_watch_with_data(self):
329 (r, w) = os.pipe()
330
331 ch = GLib.IOChannel(filedes=r)
332 ch.set_encoding(None)
333 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
334
335 cb_reads = []
336
337 def cb(channel, condition, data):
338 self.assertEqual(channel, ch)
339 self.assertEqual(condition, GLib.IOCondition.IN)
340 self.assertEqual(data, "hello")
341 cb_reads.append(channel.read())
342 if len(cb_reads) == 2:
343 ml.quit()
344 return True
345
346 id = GLib.io_add_watch(ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb, "hello")
347
348 ml = GLib.MainLoop()
349 self.assertEqual(
350 ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH
351 )
352
353 def write():
354 os.write(w, b"a")
355 GLib.idle_add(lambda: os.write(w, b"b") and False)
356
357 GLib.idle_add(write)
358 GLib.timeout_add(2000, ml.quit)
359 ml.run()
360
361 self.assertEqual(cb_reads, [b"a", b"b"])
362
363 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
364 def test_add_watch_with_multi_data(self):
365 (r, w) = os.pipe()
366
367 ch = GLib.IOChannel(filedes=r)
368 ch.set_encoding(None)
369 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
370
371 cb_reads = []
372
373 def cb(channel, condition, data1, data2, data3):
374 self.assertEqual(channel, ch)
375 self.assertEqual(condition, GLib.IOCondition.IN)
376 self.assertEqual(data1, "a")
377 self.assertEqual(data2, "b")
378 self.assertEqual(data3, "c")
379 cb_reads.append(channel.read())
380 if len(cb_reads) == 2:
381 ml.quit()
382 return True
383
384 id = GLib.io_add_watch(
385 ch, GLib.PRIORITY_HIGH, GLib.IOCondition.IN, cb, "a", "b", "c"
386 )
387
388 ml = GLib.MainLoop()
389 self.assertEqual(
390 ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH
391 )
392
393 def write():
394 os.write(w, b"a")
395 GLib.idle_add(lambda: os.write(w, b"b") and False)
396
397 GLib.idle_add(write)
398 GLib.timeout_add(2000, ml.quit)
399 ml.run()
400
401 self.assertEqual(cb_reads, [b"a", b"b"])
402
403 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
404 def test_deprecated_add_watch_no_data(self):
405 (r, w) = os.pipe()
406
407 ch = GLib.IOChannel(filedes=r)
408 ch.set_encoding(None)
409 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
410
411 cb_reads = []
412
413 def cb(channel, condition):
414 self.assertEqual(channel, ch)
415 self.assertEqual(condition, GLib.IOCondition.IN)
416 cb_reads.append(channel.read())
417 if len(cb_reads) == 2:
418 ml.quit()
419 return True
420
421 with warnings.catch_warnings(record=True) as warn:
422 warnings.simplefilter("always")
423 id = GLib.io_add_watch(
424 ch, GLib.IOCondition.IN, cb, priority=GLib.PRIORITY_HIGH
425 )
426 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
427
428 ml = GLib.MainLoop()
429 self.assertEqual(
430 ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH
431 )
432
433 def write():
434 os.write(w, b"a")
435 GLib.idle_add(lambda: os.write(w, b"b") and False)
436
437 GLib.idle_add(write)
438 GLib.timeout_add(2000, ml.quit)
439 ml.run()
440
441 self.assertEqual(cb_reads, [b"a", b"b"])
442
443 @unittest.skipIf(os.name == "nt", "NONBLOCK not implemented on Windows")
444 def test_deprecated_add_watch_with_data(self):
445 (r, w) = os.pipe()
446
447 ch = GLib.IOChannel(filedes=r)
448 ch.set_encoding(None)
449 ch.set_flags(ch.get_flags() | GLib.IOFlags.NONBLOCK)
450
451 cb_reads = []
452
453 def cb(channel, condition, data):
454 self.assertEqual(channel, ch)
455 self.assertEqual(condition, GLib.IOCondition.IN)
456 self.assertEqual(data, "hello")
457 cb_reads.append(channel.read())
458 if len(cb_reads) == 2:
459 ml.quit()
460 return True
461
462 with warnings.catch_warnings(record=True) as warn:
463 warnings.simplefilter("always")
464 id = GLib.io_add_watch(
465 ch, GLib.IOCondition.IN, cb, "hello", priority=GLib.PRIORITY_HIGH
466 )
467 self.assertTrue(issubclass(warn[0].category, PyGIDeprecationWarning))
468
469 ml = GLib.MainLoop()
470 self.assertEqual(
471 ml.get_context().find_source_by_id(id).priority, GLib.PRIORITY_HIGH
472 )
473
474 def write():
475 os.write(w, b"a")
476 GLib.idle_add(lambda: os.write(w, b"b") and False)
477
478 GLib.idle_add(write)
479
480 GLib.timeout_add(2000, ml.quit)
481 ml.run()
482
483 self.assertEqual(cb_reads, [b"a", b"b"])
484
485 def test_backwards_compat_flags(self):
486 with warnings.catch_warnings():
487 warnings.simplefilter("ignore", PyGIDeprecationWarning)
488
489 self.assertEqual(GLib.IOCondition.IN, GLib.IO_IN)
490 self.assertEqual(GLib.IOFlags.NONBLOCK, GLib.IO_FLAG_NONBLOCK)
491 self.assertEqual(GLib.IOFlags.IS_SEEKABLE, GLib.IO_FLAG_IS_SEEKABLE)
492 self.assertEqual(GLib.IOStatus.NORMAL, GLib.IO_STATUS_NORMAL)