|
1 | 1 | from __future__ import unicode_literals |
2 | 2 |
|
| 3 | +import posixpath |
3 | 4 | import unittest |
4 | 5 |
|
5 | 6 | from fs import memoryfs |
6 | 7 | from fs.test import FSTestCases |
| 8 | +from fs.test import UNICODE_TEXT |
| 9 | + |
| 10 | +try: |
| 11 | + # Only supported on Python 3.4+ |
| 12 | + import tracemalloc |
| 13 | +except ImportError: |
| 14 | + tracemalloc = None |
7 | 15 |
|
8 | 16 |
|
9 | 17 | class TestMemoryFS(FSTestCases, unittest.TestCase): |
10 | 18 | """Test OSFS implementation.""" |
11 | 19 |
|
12 | 20 | def make_fs(self): |
13 | 21 | return memoryfs.MemoryFS() |
| 22 | + |
| 23 | + def _create_many_files(self): |
| 24 | + for parent_dir in {"/", "/one", "/one/two", "/one/other-two/three"}: |
| 25 | + self.fs.makedirs(parent_dir, recreate=True) |
| 26 | + for file_id in range(50): |
| 27 | + self.fs.writetext( |
| 28 | + posixpath.join(parent_dir, str(file_id)), UNICODE_TEXT |
| 29 | + ) |
| 30 | + |
| 31 | + @unittest.skipIf( |
| 32 | + not tracemalloc, "`tracemalloc` isn't supported on this Python version." |
| 33 | + ) |
| 34 | + def test_close_mem_free(self): |
| 35 | + """Ensure all file memory is freed when calling close(). |
| 36 | +
|
| 37 | + Prevents regression against issue #308. |
| 38 | + """ |
| 39 | + trace_filters = [tracemalloc.Filter(True, "*/memoryfs.py")] |
| 40 | + tracemalloc.start() |
| 41 | + |
| 42 | + before = tracemalloc.take_snapshot().filter_traces(trace_filters) |
| 43 | + self._create_many_files() |
| 44 | + after_create = tracemalloc.take_snapshot().filter_traces(trace_filters) |
| 45 | + |
| 46 | + self.fs.close() |
| 47 | + after_close = tracemalloc.take_snapshot().filter_traces(trace_filters) |
| 48 | + tracemalloc.stop() |
| 49 | + |
| 50 | + [diff_create] = after_create.compare_to( |
| 51 | + before, key_type="filename", cumulative=True |
| 52 | + ) |
| 53 | + self.assertGreater( |
| 54 | + diff_create.size_diff, |
| 55 | + 0, |
| 56 | + "Memory usage didn't increase after creating files; diff is %0.2f KiB." |
| 57 | + % (diff_create.size_diff / 1024.0), |
| 58 | + ) |
| 59 | + |
| 60 | + [diff_close] = after_close.compare_to( |
| 61 | + after_create, key_type="filename", cumulative=True |
| 62 | + ) |
| 63 | + self.assertLess( |
| 64 | + diff_close.size_diff, |
| 65 | + 0, |
| 66 | + "Memory usage increased after closing the file system; diff is %0.2f KiB." |
| 67 | + % (diff_close.size_diff / 1024.0), |
| 68 | + ) |
0 commit comments