MCPcopy Index your code
hub / github.com/RustPython/RustPython / test_rate_limit

Method test_rate_limit

Lib/test/test_android.py:373–448  ·  view source on GitHub ↗
(self)

Source from the content-addressed store, hash-verified

371
372class TestAndroidRateLimit(unittest.TestCase):
373 def test_rate_limit(self):
374 # https://cs.android.com/android/platform/superproject/+/android-14.0.0_r1:system/logging/liblog/include/log/log_read.h;l=39
375 PER_MESSAGE_OVERHEAD = 28
376
377 # https://developer.android.com/ndk/reference/group/logging
378 ANDROID_LOG_DEBUG = 3
379
380 # To avoid flooding the test script output, use a different tag rather
381 # than stdout or stderr.
382 tag = "python.rate_limit"
383 stream = TextLogStream(ANDROID_LOG_DEBUG, tag)
384
385 # Make a test message which consumes 1 KB of the logcat buffer.
386 message = "Line {:03d} "
387 message += "." * (
388 1024 - PER_MESSAGE_OVERHEAD - len(tag) - len(message.format(0))
389 ) + "\n"
390
391 # To avoid depending on the performance of the test device, we mock the
392 # passage of time.
393 mock_now = time()
394
395 def mock_time():
396 # Avoid division by zero by simulating a small delay.
397 mock_sleep(0.0001)
398 return mock_now
399
400 def mock_sleep(duration):
401 nonlocal mock_now
402 mock_now += duration
403
404 # See _android_support.py. The default values of these parameters work
405 # well across a wide range of devices, but we'll use smaller values to
406 # ensure a quick and reliable test that doesn't flood the log too much.
407 MAX_KB_PER_SECOND = 100
408 BUCKET_KB = 10
409 with (
410 patch("_android_support.MAX_BYTES_PER_SECOND", MAX_KB_PER_SECOND * 1024),
411 patch("_android_support.BUCKET_SIZE", BUCKET_KB * 1024),
412 patch("_android_support.sleep", mock_sleep),
413 patch("_android_support.time", mock_time),
414 ):
415 # Make sure the token bucket is full.
416 stream.write("Initial message to reset _prev_write_time")
417 mock_sleep(BUCKET_KB / MAX_KB_PER_SECOND)
418 line_num = 0
419
420 # Write BUCKET_KB messages, and return the rate at which they were
421 # accepted in KB per second.
422 def write_bucketful():
423 nonlocal line_num
424 start = mock_time()
425 max_line_num = line_num + BUCKET_KB
426 while line_num < max_line_num:
427 stream.write(message.format(line_num))
428 line_num += 1
429 return BUCKET_KB / (mock_time() - start)
430

Callers

nothing calls this directly

Calls 8

writeMethod · 0.95
TextLogStreamClass · 0.90
timeClass · 0.90
patchFunction · 0.90
lenFunction · 0.85
assertGreaterMethod · 0.80
formatMethod · 0.45
assertAlmostEqualMethod · 0.45

Tested by

no test coverage detected