-
Notifications
You must be signed in to change notification settings - Fork 152
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make sure SlicedFile is closed properly (#612)
Fixes #556 --------- Co-authored-by: Adam Johnson <me@adamj.eu>
- Loading branch information
1 parent
f8dff50
commit c42e93c
Showing
3 changed files
with
47 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -64,6 +64,7 @@ def read(self, size=-1): | |
return data | ||
|
||
def close(self): | ||
super().close() | ||
self.fileobj.close() | ||
|
||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
from __future__ import annotations | ||
|
||
from io import BytesIO | ||
|
||
from django.test import SimpleTestCase | ||
|
||
from whitenoise.responders import SlicedFile | ||
|
||
|
||
class SlicedFileTests(SimpleTestCase): | ||
def test_close_does_not_rerun_on_del(self): | ||
""" | ||
Regression test for the subtle close() behaviour of SlicedFile that | ||
could lead to database connection errors. | ||
https://github.com/evansd/whitenoise/pull/612 | ||
""" | ||
file = BytesIO(b"1234567890") | ||
sliced_file = SlicedFile(file, 1, 2) | ||
|
||
# Emulate how Django patches the file object's close() method to be | ||
# response.close() and count the calls. | ||
# https://github.com/django/django/blob/345a6652e6a15febbf4f68351dcea5dd674ea324/django/core/handlers/wsgi.py#L137-L140 | ||
calls = 0 | ||
|
||
file_close = sliced_file.close | ||
|
||
def closer(): | ||
nonlocal calls, file_close | ||
calls += 1 | ||
if file_close is not None: | ||
file_close() | ||
file_close = None | ||
|
||
sliced_file.close = closer | ||
|
||
sliced_file.close() | ||
assert calls == 1 | ||
|
||
# Deleting the sliced file should not call close again. | ||
del sliced_file | ||
assert calls == 1 |