-
Notifications
You must be signed in to change notification settings - Fork 144
/
test_django_whitenoise.py
232 lines (167 loc) · 7.62 KB
/
test_django_whitenoise.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
from __future__ import annotations
import shutil
import tempfile
from contextlib import closing
from pathlib import Path
from urllib.parse import urljoin, urlparse
import django
import pytest
from django.conf import settings
from django.contrib.staticfiles import finders, storage
from django.core.management import call_command
from django.core.wsgi import get_wsgi_application
from django.test.utils import override_settings
from django.utils.functional import empty
from whitenoise.middleware import WhiteNoiseFileResponse, WhiteNoiseMiddleware
from whitenoise.responders import MissingFileError
from .utils import AppServer, Files
def reset_lazy_object(obj):
obj._wrapped = empty
def get_url_path(base, url):
return urlparse(urljoin(base, url)).path
@pytest.fixture()
def static_files():
files = Files("static", js="app.js", nonascii="nonascii\u2713.txt")
with override_settings(STATICFILES_DIRS=[files.directory]):
yield files
@pytest.fixture()
def root_files():
files = Files("root", robots="robots.txt")
with override_settings(WHITENOISE_ROOT=files.directory):
yield files
@pytest.fixture()
def tmp():
tmp_dir = tempfile.mkdtemp()
with override_settings(STATIC_ROOT=tmp_dir):
yield tmp_dir
shutil.rmtree(tmp_dir)
@pytest.fixture()
def _collect_static(static_files, root_files, tmp):
reset_lazy_object(storage.staticfiles_storage)
call_command("collectstatic", verbosity=0, interactive=False)
@pytest.fixture()
def application(_collect_static):
return get_wsgi_application()
@pytest.fixture()
def server(application):
app_server = AppServer(application)
with closing(app_server):
yield app_server
def test_get_root_file(server, root_files, _collect_static):
response = server.get(root_files.robots_url)
assert response.content == root_files.robots_content
def test_versioned_file_cached_forever(server, static_files, _collect_static):
url = storage.staticfiles_storage.url(static_files.js_path)
response = server.get(url)
assert response.content == static_files.js_content
assert (
response.headers.get("Cache-Control")
== f"max-age={WhiteNoiseMiddleware.FOREVER}, public, immutable"
)
def test_unversioned_file_not_cached_forever(server, static_files, _collect_static):
url = settings.STATIC_URL + static_files.js_path
response = server.get(url)
assert response.content == static_files.js_content
assert response.headers.get("Cache-Control") == "max-age={}, public".format(
WhiteNoiseMiddleware.max_age
)
def test_get_gzip(server, static_files, _collect_static):
url = storage.staticfiles_storage.url(static_files.js_path)
response = server.get(url, headers={"Accept-Encoding": "gzip"})
assert response.content == static_files.js_content
assert response.headers["Content-Encoding"] == "gzip"
assert response.headers["Vary"] == "Accept-Encoding"
def test_get_brotli(server, static_files, _collect_static):
url = storage.staticfiles_storage.url(static_files.js_path)
response = server.get(url, headers={"Accept-Encoding": "gzip, br"})
assert response.content == static_files.js_content
assert response.headers["Content-Encoding"] == "br"
assert response.headers["Vary"] == "Accept-Encoding"
def test_no_content_type_when_not_modified(server, static_files, _collect_static):
last_mod = "Fri, 11 Apr 2100 11:47:06 GMT"
url = settings.STATIC_URL + static_files.js_path
response = server.get(url, headers={"If-Modified-Since": last_mod})
assert "Content-Type" not in response.headers
def test_get_nonascii_file(server, static_files, _collect_static):
url = settings.STATIC_URL + static_files.nonascii_path
response = server.get(url)
assert response.content == static_files.nonascii_content
@pytest.fixture(params=[True, False])
def finder_static_files(request):
files = Files("static", js="app.js", index="with-index/index.html")
with override_settings(
STATICFILES_DIRS=[files.directory],
WHITENOISE_USE_FINDERS=True,
WHITENOISE_AUTOREFRESH=request.param,
WHITENOISE_INDEX_FILE=True,
STATIC_ROOT=None,
):
finders.get_finder.cache_clear()
yield files
def test_no_content_disposition_header(server, static_files, _collect_static):
url = settings.STATIC_URL + static_files.js_path
response = server.get(url)
assert response.headers.get("content-disposition") is None
@pytest.fixture()
def finder_application(finder_static_files):
return get_wsgi_application()
@pytest.fixture()
def finder_server(finder_application):
app_server = AppServer(finder_application)
with closing(app_server):
yield app_server
def test_file_served_from_static_dir(finder_static_files, finder_server):
url = settings.STATIC_URL + finder_static_files.js_path
response = finder_server.get(url)
assert response.content == finder_static_files.js_content
def test_non_ascii_requests_safely_ignored(finder_server):
response = finder_server.get(settings.STATIC_URL + "test\u263A")
assert 404 == response.status_code
def test_requests_for_directory_safely_ignored(finder_server):
url = settings.STATIC_URL + "directory"
response = finder_server.get(url)
assert 404 == response.status_code
def test_index_file_served_at_directory_path(finder_static_files, finder_server):
path = finder_static_files.index_path.rpartition("/")[0] + "/"
response = finder_server.get(settings.STATIC_URL + path)
assert response.content == finder_static_files.index_content
def test_index_file_path_redirected(finder_static_files, finder_server):
directory_path = finder_static_files.index_path.rpartition("/")[0] + "/"
index_url = settings.STATIC_URL + finder_static_files.index_path
response = finder_server.get(index_url, allow_redirects=False)
location = get_url_path(response.url, response.headers["Location"])
assert response.status_code == 302
assert location == settings.STATIC_URL + directory_path
def test_directory_path_without_trailing_slash_redirected(
finder_static_files, finder_server
):
directory_path = finder_static_files.index_path.rpartition("/")[0] + "/"
directory_url = settings.STATIC_URL + directory_path.rstrip("/")
response = finder_server.get(directory_url, allow_redirects=False)
location = get_url_path(response.url, response.headers["Location"])
assert response.status_code == 302
assert location == settings.STATIC_URL + directory_path
def test_whitenoise_file_response_has_only_one_header():
response = WhiteNoiseFileResponse(open(__file__, "rb"))
response.close()
headers = {key.lower() for key, value in response.items()}
# This subclass should have none of the default headers that FileReponse
# sets
assert headers == {"content-type"}
@pytest.mark.skipif(django.VERSION[:2] < (3, 1), reason="feature added in Django 3.1")
def test_relative_static_url(server, static_files, _collect_static):
with override_settings(STATIC_URL="static/"):
url = storage.staticfiles_storage.url(static_files.js_path)
response = server.get(url)
assert response.content == static_files.js_content
def test_404_in_prod(server):
response = server.get(settings.STATIC_URL + 'garbage')
assert response.status_code == 404
@override_settings(DEBUG=True)
def test_error_message(server):
response = server.get(settings.STATIC_URL + 'garbage')
print(response.content.decode())
app_dirs = Path(__file__).parent / 'test_files' / 'static'
expected = f"""{settings.STATIC_URL + 'garbage'} not found. Searched these paths:
{app_dirs}"""
assert expected in str(response.content.decode())