send_file closes the file which it opens
https://github.com/pallets/flask/blob/0.12.2/flask/helpers.py#L549
File is not closed.
Tests are yelling:
tests2.py:14: ResourceWarning: unclosed file <_io.BufferedReader name='path/tests2.py'>
> python3 tests2.py
tests2.py:14: ResourceWarning: unclosed file <_io.BufferedReader name='path/tests2.py'>
self.client.get('/')
.
----------------------------------------------------------------------
Ran 1 test in 0.012s
OK
> cat tests2.py
import unittest
from flask import Flask
from flask import current_app, send_from_directory
app = Flask(__name__)
@app.route("/")
def hello():
return send_from_directory('.', __file__)
class TestCase(unittest.TestCase):
def test_x(self):
self.client = app.test_client()
self.client.get('/')
if __name__ == '__main__':
unittest.main()
I tried your test on my local python2 (OS X 10.11.6 / Python 2.7.13) and in docker on your version (3.5.3) and both worked without issue.
# docker run --rm -v `pwd`:/tmp/ python:3.5.3 /bin/bash -c "pip install flask && python3 /tmp/tests2.py"
.
----------------------------------------------------------------------
Ran 1 test in 0.014s
OK
People misunderstand the fact that send_file opens the file but doesn't close it. Other parts of the WSGI flow will close files after the response is built, so that things like streaming work.
There are some cases where tests will raise this warning because other tests failed, but it's not really an issue because tests end, the file doesn't stay open. As far as I can tell, the test suite has cases for this already and passes.
I found that closing the response from the test client addressed the ResourceWarning: unclosed file <_io.BufferedReader I was getting:
response = self.client.get('/')
self.assertEqual(response.status_code, 200)
response.close()
Most helpful comment
I found that closing the response from the test client addressed the
ResourceWarning: unclosed file <_io.BufferedReaderI was getting: