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?
Cheers
Mark