Debian Codegraph @

Lib/test/test_android.py

raw
1 import io
2 import platform
3 import queue
4 import re
5 import subprocess
6 import sys
7 import unittest
8 from _android_support import TextLogStream
9 from array import array
10 from contextlib import ExitStack, contextmanager
11 from threading import Thread
12 from test.support import LOOPBACK_TIMEOUT
13 from time import time
14 from unittest.mock import patch
15
16
17 if sys.platform != "android":
18 raise unittest.SkipTest("Android-specific")
19
20 api_level = platform.android_ver().api_level
21
22 # (name, level, fileno)
23 STREAM_INFO = [("stdout", "I", 1), ("stderr", "W", 2)]
24
25
26 # Test redirection of stdout and stderr to the Android log.
27 @unittest.skipIf(
28 api_level < 23 and platform.machine() == "aarch64",
29 "SELinux blocks reading logs on older ARM64 emulators"
30 )
31 class TestAndroidOutput(unittest.TestCase):
32 maxDiff = None
33
34 def setUp(self):
35 self.logcat_process = subprocess.Popen(
36 ["logcat", "-v", "tag"], stdout=subprocess.PIPE,
37 errors="backslashreplace"
38 )
39 self.logcat_queue = queue.Queue()
40
41 def logcat_thread():
42 for line in self.logcat_process.stdout:
43 self.logcat_queue.put(line.rstrip("\n"))
44 self.logcat_process.stdout.close()
45
46 self.logcat_thread = Thread(target=logcat_thread)
47 self.logcat_thread.start()
48
49 try:
50 from ctypes import CDLL, c_char_p, c_int
51 android_log_write = getattr(CDLL("liblog.so"), "__android_log_write")
52 android_log_write.argtypes = (c_int, c_char_p, c_char_p)
53 ANDROID_LOG_INFO = 4
54
55 # Separate tests using a marker line with a different tag.
56 tag, message = "python.test", f"{self.id()} {time()}"
57 android_log_write(
58 ANDROID_LOG_INFO, tag.encode("UTF-8"), message.encode("UTF-8"))
59 self.assert_log("I", tag, message, skip=True)
60 except:
61 # If setUp throws an exception, tearDown is not automatically
62 # called. Avoid leaving a dangling thread which would keep the
63 # Python process alive indefinitely.
64 self.tearDown()
65 raise
66
67 def assert_logs(self, level, tag, expected, **kwargs):
68 for line in expected:
69 self.assert_log(level, tag, line, **kwargs)
70
71 def assert_log(self, level, tag, expected, *, skip=False):
72 deadline = time() + LOOPBACK_TIMEOUT
73 while True:
74 try:
75 line = self.logcat_queue.get(timeout=(deadline - time()))
76 except queue.Empty:
77 raise self.failureException(
78 f"line not found: {expected!r}"
79 ) from None
80 if match := re.fullmatch(fr"(.)/{tag}: (.*)", line):
81 try:
82 self.assertEqual(level, match[1])
83 self.assertEqual(expected, match[2])
84 break
85 except AssertionError:
86 if not skip:
87 raise
88
89 def tearDown(self):
90 self.logcat_process.terminate()
91 self.logcat_process.wait(LOOPBACK_TIMEOUT)
92 self.logcat_thread.join(LOOPBACK_TIMEOUT)
93
94 # Avoid an irrelevant warning about threading._dangling.
95 self.logcat_thread = None
96
97 @contextmanager
98 def reconfigure(self, stream, **settings):
99 original_settings = {key: getattr(stream, key, None) for key in settings.keys()}
100 stream.reconfigure(**settings)
101 try:
102 yield
103 finally:
104 stream.reconfigure(**original_settings)
105
106 def stream_context(self, stream_name, level):
107 stack = ExitStack()
108 stack.enter_context(self.subTest(stream_name))
109
110 # In --verbose3 mode, sys.stdout and sys.stderr are captured, so we can't
111 # test them directly. Detect this mode and use some temporary streams with
112 # the same properties.
113 stream = getattr(sys, stream_name)
114 native_stream = getattr(sys, f"__{stream_name}__")
115 if isinstance(stream, io.StringIO):
116 # https://developer.android.com/ndk/reference/group/logging
117 prio = {"I": 4, "W": 5}[level]
118 stack.enter_context(
119 patch(
120 f"sys.{stream_name}",
121 stream := TextLogStream(
122 prio, f"python.{stream_name}", native_stream,
123 ),
124 )
125 )
126
127 # The tests assume the stream is initially buffered.
128 stack.enter_context(self.reconfigure(stream, write_through=False))
129
130 return stack
131
132 def test_str(self):
133 for stream_name, level, fileno in STREAM_INFO:
134 with self.stream_context(stream_name, level):
135 stream = getattr(sys, stream_name)
136 tag = f"python.{stream_name}"
137 self.assertEqual(f"<TextLogStream '{tag}'>", repr(stream))
138
139 self.assertIs(stream.writable(), True)
140 self.assertIs(stream.readable(), False)
141 self.assertEqual(stream.fileno(), fileno)
142 self.assertEqual("UTF-8", stream.encoding)
143 self.assertEqual("backslashreplace", stream.errors)
144 self.assertIs(stream.line_buffering, True)
145 self.assertIs(stream.write_through, False)
146
147 def write(s, lines=None, *, write_len=None):
148 if write_len is None:
149 write_len = len(s)
150 self.assertEqual(write_len, stream.write(s))
151 if lines is None:
152 lines = [s]
153 self.assert_logs(level, tag, lines)
154
155 # Single-line messages,
156 with self.reconfigure(stream, write_through=True):
157 write("", [])
158
159 write("a")
160 write("Hello")
161 write("Hello world")
162 write(" ")
163 write(" ")
164
165 # Non-ASCII text
166 write("ol\u00e9") # Spanish
167 write("\u4e2d\u6587") # Chinese
168
169 # Non-BMP emoji
170 write("\U0001f600")
171
172 # Non-encodable surrogates
173 write("\ud800\udc00", [r"\ud800\udc00"])
174
175 # Code used by surrogateescape (which isn't enabled here)
176 write("\udc80", [r"\udc80"])
177
178 # Null characters are logged using "modified UTF-8".
179 write("\u0000", [r"\xc0\x80"])
180 write("a\u0000", [r"a\xc0\x80"])
181 write("\u0000b", [r"\xc0\x80b"])
182 write("a\u0000b", [r"a\xc0\x80b"])
183
184 # Multi-line messages. Avoid identical consecutive lines, as
185 # they may activate "chatty" filtering and break the tests.
186 #
187 # Additional spaces will appear in the output where necessary to
188 # protect leading newlines.
189 write("\nx", [" "])
190 write("\na\n", ["x", "a"])
191 write("\n", [" "])
192 write("\n\n", [" ", " "])
193 write("b\n", ["b"])
194 write("c\n\n", ["c", " "])
195 write("d\ne", ["d"])
196 write("xx", [])
197 write("f\n\ng", ["exxf", " "])
198 write("\n", ["g"])
199
200 # Since this is a line-based logging system, line buffering
201 # cannot be turned off, i.e. a newline always causes a flush.
202 stream.reconfigure(line_buffering=False)
203 self.assertIs(stream.line_buffering, True)
204
205 # However, buffering can be turned off completely if you want a
206 # flush after every write.
207 with self.reconfigure(stream, write_through=True):
208 write("\nx", [" ", "x"])
209 write("\na\n", [" ", "a"])
210 write("\n", [" "])
211 write("\n\n", [" ", " "])
212 write("b\n", ["b"])
213 write("c\n\n", ["c", " "])
214 write("d\ne", ["d", "e"])
215 write("xx", ["xx"])
216 write("f\n\ng", ["f", " ", "g"])
217 write("\n", [" "])
218
219 # "\r\n" should be translated into "\n".
220 write("hello\r\n", ["hello"])
221 write("hello\r\nworld\r\n", ["hello", "world"])
222 write("\r\n", [""])
223
224 # Non-standard line separators should be preserved.
225 write("before form feed\x0cafter form feed\n",
226 ["before form feed\x0cafter form feed"])
227 write("before line separator\u2028after line separator\n",
228 ["before line separator\u2028after line separator"])
229
230 # String subclasses are accepted, but they should be converted
231 # to a standard str without calling any of their methods.
232 class CustomStr(str):
233 def splitlines(self, *args, **kwargs):
234 raise AssertionError()
235
236 def __len__(self):
237 raise AssertionError()
238
239 def __str__(self):
240 raise AssertionError()
241
242 write(CustomStr("custom\n"), ["custom"], write_len=7)
243
244 # Non-string classes are not accepted.
245 for obj in [b"", b"hello", None, 42]:
246 with self.subTest(obj=obj):
247 with self.assertRaisesRegex(
248 TypeError,
249 fr"write\(\) argument must be str, not "
250 fr"{type(obj).__name__}"
251 ):
252 stream.write(obj)
253
254 # Manual flushing is supported.
255 write("hello", [])
256 stream.flush()
257 self.assert_log(level, tag, "hello")
258 write("hello", [])
259 write("world", [])
260 stream.flush()
261 self.assert_log(level, tag, "helloworld")
262
263 # Long lines are split into blocks of 1000 characters
264 # (MAX_CHARS_PER_WRITE in _android_support.py), but
265 # TextIOWrapper should then join them back together as much as
266 # possible without exceeding 4000 UTF-8 bytes
267 # (MAX_BYTES_PER_WRITE).
268 #
269 # ASCII (1 byte per character)
270 write(("foobar" * 700) + "\n", # 4200 bytes in
271 [("foobar" * 666) + "foob", # 4000 bytes out
272 "ar" + ("foobar" * 33)]) # 200 bytes out
273
274 # "Full-width" digits 0-9 (3 bytes per character)
275 s = "\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19"
276 write((s * 150) + "\n", # 4500 bytes in
277 [s * 100, # 3000 bytes out
278 s * 50]) # 1500 bytes out
279
280 s = "0123456789"
281 write(s * 200, []) # 2000 bytes in
282 write(s * 150, []) # 1500 bytes in
283 write(s * 51, [s * 350]) # 510 bytes in, 3500 bytes out
284 write("\n", [s * 51]) # 0 bytes in, 510 bytes out
285
286 def test_bytes(self):
287 for stream_name, level, fileno in STREAM_INFO:
288 with self.stream_context(stream_name, level):
289 stream = getattr(sys, stream_name).buffer
290 tag = f"python.{stream_name}"
291 self.assertEqual(f"<BinaryLogStream '{tag}'>", repr(stream))
292 self.assertIs(stream.writable(), True)
293 self.assertIs(stream.readable(), False)
294 self.assertEqual(stream.fileno(), fileno)
295
296 def write(b, lines=None, *, write_len=None):
297 if write_len is None:
298 write_len = len(b)
299 self.assertEqual(write_len, stream.write(b))
300 if lines is None:
301 lines = [b.decode()]
302 self.assert_logs(level, tag, lines)
303
304 # Single-line messages,
305 write(b"", [])
306
307 write(b"a")
308 write(b"Hello")
309 write(b"Hello world")
310 write(b" ")
311 write(b" ")
312
313 # Non-ASCII text
314 write(b"ol\xc3\xa9") # Spanish
315 write(b"\xe4\xb8\xad\xe6\x96\x87") # Chinese
316
317 # Non-BMP emoji
318 write(b"\xf0\x9f\x98\x80")
319
320 # Null bytes are logged using "modified UTF-8".
321 write(b"\x00", [r"\xc0\x80"])
322 write(b"a\x00", [r"a\xc0\x80"])
323 write(b"\x00b", [r"\xc0\x80b"])
324 write(b"a\x00b", [r"a\xc0\x80b"])
325
326 # Invalid UTF-8
327 write(b"\xff", [r"\xff"])
328 write(b"a\xff", [r"a\xff"])
329 write(b"\xffb", [r"\xffb"])
330 write(b"a\xffb", [r"a\xffb"])
331
332 # Log entries containing newlines are shown differently by
333 # `logcat -v tag`, `logcat -v long`, and Android Studio. We
334 # currently use `logcat -v tag`, which shows each line as if it
335 # was a separate log entry, but strips a single trailing
336 # newline.
337 write(b"\nx", [" ", "x"])
338 write(b"\na\n", [" ", "a"])
339 write(b"\n", [" "])
340 write(b"\n\n", [" ", ""])
341 write(b"b\n", ["b"])
342 write(b"c\n\n", ["c", ""])
343 write(b"d\ne", ["d", "e"])
344 write(b"xx", ["xx"])
345 write(b"f\n\ng", ["f", "", "g"])
346 write(b"\n", [" "])
347
348 # "\r\n" should be translated into "\n".
349 write(b"hello\r\n", ["hello"])
350 write(b"hello\r\nworld\r\n", ["hello", "world"])
351 write(b"\r\n", [""])
352
353 # Other bytes-like objects are accepted.
354 write(bytearray(b"bytearray"))
355
356 mv = memoryview(b"memoryview")
357 write(mv, ["memoryview"]) # Continuous
358 write(mv[::2], ["mmrve"]) # Discontinuous
359
360 write(
361 # Android only supports little-endian architectures, so the
362 # bytes representation is as follows:
363 array("H", [
364 0, # 00 00
365 1, # 01 00
366 65534, # FE FF
367 65535, # FF FF
368 ]),
369
370 # After encoding null bytes with modified UTF-8, the only
371 # valid UTF-8 sequence is \x01. All other bytes are handled
372 # by backslashreplace.
373 ["\\xc0\\x80\\xc0\\x80"
374 "\x01\\xc0\\x80"
375 "\\xfe\\xff"
376 "\\xff\\xff"],
377 write_len=8,
378 )
379
380 # Non-bytes-like classes are not accepted.
381 for obj in ["", "hello", None, 42]:
382 with self.subTest(obj=obj):
383 with self.assertRaisesRegex(
384 TypeError,
385 fr"write\(\) argument must be bytes-like, not "
386 fr"{type(obj).__name__}"
387 ):
388 stream.write(obj)
389
390
391 class TestAndroidRateLimit(unittest.TestCase):
392 def test_rate_limit(self):
393 # https://cs.android.com/android/platform/superproject/+/android-14.0.0_r1:system/logging/liblog/include/log/log_read.h;l=39
394 PER_MESSAGE_OVERHEAD = 28
395
396 # https://developer.android.com/ndk/reference/group/logging
397 ANDROID_LOG_DEBUG = 3
398
399 # To avoid flooding the test script output, use a different tag rather
400 # than stdout or stderr.
401 tag = "python.rate_limit"
402 stream = TextLogStream(ANDROID_LOG_DEBUG, tag)
403
404 # Make a test message which consumes 1 KB of the logcat buffer.
405 message = "Line {:03d} "
406 message += "." * (
407 1024 - PER_MESSAGE_OVERHEAD - len(tag) - len(message.format(0))
408 ) + "\n"
409
410 # To avoid depending on the performance of the test device, we mock the
411 # passage of time.
412 mock_now = time()
413
414 def mock_time():
415 # Avoid division by zero by simulating a small delay.
416 mock_sleep(0.0001)
417 return mock_now
418
419 def mock_sleep(duration):
420 nonlocal mock_now
421 mock_now += duration
422
423 # See _android_support.py. The default values of these parameters work
424 # well across a wide range of devices, but we'll use smaller values to
425 # ensure a quick and reliable test that doesn't flood the log too much.
426 MAX_KB_PER_SECOND = 100
427 BUCKET_KB = 10
428 with (
429 patch("_android_support.MAX_BYTES_PER_SECOND", MAX_KB_PER_SECOND * 1024),
430 patch("_android_support.BUCKET_SIZE", BUCKET_KB * 1024),
431 patch("_android_support.sleep", mock_sleep),
432 patch("_android_support.time", mock_time),
433 ):
434 # Make sure the token bucket is full.
435 stream.write("Initial message to reset _prev_write_time")
436 mock_sleep(BUCKET_KB / MAX_KB_PER_SECOND)
437 line_num = 0
438
439 # Write BUCKET_KB messages, and return the rate at which they were
440 # accepted in KB per second.
441 def write_bucketful():
442 nonlocal line_num
443 start = mock_time()
444 max_line_num = line_num + BUCKET_KB
445 while line_num < max_line_num:
446 stream.write(message.format(line_num))
447 line_num += 1
448 return BUCKET_KB / (mock_time() - start)
449
450 # The first bucketful should be written with minimal delay. The
451 # factor of 2 here is not arbitrary: it verifies that the system can
452 # write fast enough to empty the bucket within two bucketfuls, which
453 # the next part of the test depends on.
454 self.assertGreater(write_bucketful(), MAX_KB_PER_SECOND * 2)
455
456 # Write another bucketful to empty the token bucket completely.
457 write_bucketful()
458
459 # The next bucketful should be written at the rate limit.
460 self.assertAlmostEqual(
461 write_bucketful(), MAX_KB_PER_SECOND,
462 delta=MAX_KB_PER_SECOND * 0.1
463 )
464
465 # Once the token bucket refills, we should go back to full speed.
466 mock_sleep(BUCKET_KB / MAX_KB_PER_SECOND)
467 self.assertGreater(write_bucketful(), MAX_KB_PER_SECOND * 2)