-
Notifications
You must be signed in to change notification settings - Fork 95
Description
Describe the bug
In the test suite of a django project, memory seems to not always be freed after each test execution. I expect the memory occupied by the fake file system to go down drastically during each teardown. If this is wrong, I'm looking forward to learn the correct behavior.
I use docker container stats to check my container's memory requirements. I know this isn't a proper benchmark, but the results are easy to see. During the test suite, the memory fills up and the container crashes. I narrowed this down to the behavior in the following example.
On my machine, it quickly reaches 3+ GiB of memory. I recommend stopping the execution before it fills, as this produces a long and annoying freeze on my computer. When I manually run garbace collection though (see commented code), the memory usage jumps between 1-2 GiB and goes back to near 0 after each test. Note that you might have to play around with NUM_TESTS and FILE_SIZE.
I also tried running the same example without fake filesystem and the memory usage is negligible.
How To Reproduce
import random
import uuid
import pytest
import os
PATH = os.path.dirname(os.path.abspath(__file__))
NUM_TESTS = 10
FILE_SIZE = int(10e6)
@pytest.fixture()
def use_fake_fs(fs):
fs.add_real_directory(PATH)
yield
# uncomment the following to reduce memory requirements
# fs.reset() # Clear filesystem contents (FakeFile/FakeDirectory objects)
# import linecache
# linecache.clearcache() # Clear cached source code for tracebacks
# import gc
# gc.collect() # Force cyclic GC to reclaim circular references
@pytest.mark.parametrize("counter", range(NUM_TESTS))
def test_fake_fs(use_fake_fs, counter):
content = ''.join([str(random.randint(0, 10))] * FILE_SIZE)
for _ in range(100):
unique_file_path = f"{PATH}/file_{uuid.uuid4()}.txt"
with open(unique_file_path, "w") as fh:
fh.write(content)
with open(unique_file_path, "r") as fh:
assert fh.read() == content
Your environment
Linux-6.12.54-linuxkit-x86_64-with-glibc2.41
Python 3.12.12 (main, Dec 30 2025, 00:43:35) [GCC 14.2.0]
pyfakefs 6.0.0
pytest 9.0.2
requirements.txt:
django==6.0
pytest-django==4.11.1
pyfakefs==6.0.0
Note that django might not be relevant to the problem. it was just easy for me to reproduce it inside a docker container which uses django.