|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
import io |
|
|
import os |
|
|
import unittest |
|
|
|
|
|
from jsonslicer import JsonSlicer |
|
|
|
|
|
if os.environ.get('TRACEMALLOC'): |
|
|
import gc |
|
|
import tracemalloc |
|
|
|
|
|
|
|
|
gen_index = 0 |
|
|
|
|
|
|
|
|
def gen_bytes(): |
|
|
global gen_index |
|
|
gen_index += 1 |
|
|
return ('gen_' + str(gen_index)).encode('utf-8') |
|
|
|
|
|
|
|
|
@unittest.skipIf(not os.environ.get('TRACEMALLOC'), 'TRACEMALLOC not set') |
|
|
class TestJsonSlicer(unittest.TestCase): |
|
|
def assertNoLeaks(self, func): |
|
|
tracemalloc.start(25) |
|
|
|
|
|
|
|
|
func() |
|
|
|
|
|
gc.collect() |
|
|
snapshot1 = tracemalloc.take_snapshot() |
|
|
|
|
|
|
|
|
func() |
|
|
|
|
|
gc.collect() |
|
|
snapshot2 = tracemalloc.take_snapshot() |
|
|
tracemalloc.stop() |
|
|
|
|
|
filters = ( |
|
|
tracemalloc.Filter(False, tracemalloc.__file__), |
|
|
) |
|
|
snapshot1 = snapshot1.filter_traces(filters) |
|
|
snapshot2 = snapshot2.filter_traces(filters) |
|
|
|
|
|
leak_message = '' |
|
|
for stat in snapshot2.compare_to(snapshot1, 'lineno'): |
|
|
if stat.size_diff != 0: |
|
|
leak_message += 'tracemalloc: possible leak: {} bytes, {} allocations\n'.format(stat.size_diff, stat.count_diff) |
|
|
for line in stat.traceback.format(): |
|
|
leak_message += line + '\n' |
|
|
|
|
|
if leak_message: |
|
|
self.fail('Memory leaks detected\n' + leak_message) |
|
|
|
|
|
def test_leaks_construct(self): |
|
|
def wrapper(): |
|
|
JsonSlicer(io.BytesIO(b'0'), ()) |
|
|
|
|
|
self.assertNoLeaks(wrapper) |
|
|
|
|
|
def test_leaks_construct_with_path(self): |
|
|
def wrapper(): |
|
|
JsonSlicer(io.BytesIO(b'0'), (gen_bytes(), gen_bytes())) |
|
|
|
|
|
self.assertNoLeaks(wrapper) |
|
|
|
|
|
def test_leaks_reinit(self): |
|
|
def wrapper(): |
|
|
js = JsonSlicer(io.BytesIO(b'0'), (gen_bytes(), gen_bytes())) |
|
|
js.__init__(io.BytesIO(b'0'), (gen_bytes(), gen_bytes())) |
|
|
|
|
|
self.assertNoLeaks(wrapper) |
|
|
|
|
|
def test_leaks_iterate(self): |
|
|
def wrapper(): |
|
|
js = JsonSlicer(io.BytesIO(b'[0,1,2]'), (None,)) |
|
|
next(js) |
|
|
|
|
|
self.assertNoLeaks(wrapper) |
|
|
|
|
|
|
|
|
if __name__ == '__main__': |
|
|
unittest.main() |
|
|
|