RequestFactory leaves files unclosed

I have a view test in a Django 2.2 (Python 3.8) project that is uploading a file using the RequestFactory. The test succeeds but Python warns that there is an unclosed file. Tracemalloc shows that it is a temporary file created by the TemporaryFileUploadHandler. The same test modified to use the Client test client doesn’t trigger the unclosed file warning.

This is the test:

def test_request_factory(self):
        with open("test.pdf", "rb") as attachment:
            request = RequestFactory().post(
                "/who/cares", data=dict(attachment=attachment)
            request.user = self.admin
            response = views.UploadView.as_view()(request, **self.view_kwargs())
        # various passing assertions ...

If I explicitly add a request.close() line after the post, the warning goes away.

Is not closing the temporary file the expected behaviour or have I done it wrong?


This sounds like a bug! Could you try reproducing this with a test in Django’s test suite? There’s a class called RequestFactoryTest in tests/test_client/ that may be the right place to put it. The first patch tutorial contains instructions for running the test suite.

Thanks Adam. I’ve created a test that reproduces it. Test that files are closed after post · MrkGrgsn/django@5baf00c · GitHub