| 1 |
import pytest |
| 2 |
import gc |
| 3 |
import weakref |
| 4 |
|
| 5 |
def test_memory_doesnt_jump_during_sweeping(): |
| 6 |
memory = [] |
| 7 |
def on_gc_collect_step(stats): |
| 8 |
memory.append((stats.GC_STATES[stats.oldstate], gc.get_stats()._s.total_arena_memory)) |
| 9 |
|
| 10 |
gc.hooks.on_gc_collect_step = on_gc_collect_step |
| 11 |
|
| 12 |
l1 = [str(i) for i in range(100000)] |
| 13 |
l2 = [str(i) for i in range(100000)] |
| 14 |
l1[:] = [] |
| 15 |
memory[:] = [] |
| 16 |
for i in range(100): |
| 17 |
gc.collect_step() |
| 18 |
minimum = min(x[1] for x in memory) |
| 19 |
maximum = max(x[1] for x in memory) |
| 20 |
assert minimum != 0 |
| 21 |
assert minimum >= maximum // 3 |
| 22 |
|
| 23 |
gc.hooks.on_gc_collect_step = lambda stats: None |
| 24 |
|
| 25 |
def test_gc_stats_sum_is_correct(): |
| 26 |
def extract_mb(line): |
| 27 |
if '(' in line: |
| 28 |
line = line[:line.index('(')].strip() |
| 29 |
assert line.endswith("MB") |
| 30 |
return float(line[:-2].rsplit(' ', 1)[-1]) |
| 31 |
|
| 32 |
l1 = [str(i) for i in range(100000)] |
| 33 |
l2 = [str(i) for i in range(100000)] |
| 34 |
l1[:] = [] |
| 35 |
gc.collect() |
| 36 |
for with_memory_pressure in [0, 1]: |
| 37 |
stats = str(gc.get_stats(with_memory_pressure)) |
| 38 |
first_half, second_half = stats.split("Total memory allocated") |
| 39 |
for half in first_half, second_half: |
| 40 |
lines = half.splitlines() |
| 41 |
total = extract_mb(lines[1]) |
| 42 |
summed = extract_mb(lines[2]) + extract_mb(lines[3]) + extract_mb(lines[4]) |
| 43 |
assert 0.9 < summed / total < 1.1 |
| 44 |
|
| 45 |
def test_args_passed_are_eligible_for_gc(): |
| 46 |
class A: |
| 47 |
pass |
| 48 |
|
| 49 |
def other(a): |
| 50 |
|
| 51 |
a = weakref.ref(a) |
| 52 |
|
| 53 |
for _ in range(5): |
| 54 |
gc.collect() |
| 55 |
|
| 56 |
assert a() is None |
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
other(A()) |
| 61 |
|
| 62 |
other(a=A()) |
| 63 |
|
| 64 |
if __name__ == "__main__": |
| 65 |
sys.exit(main()) |