Debian Codegraph @

tests/test_flask_compress.py

raw
1 import gzip
2 import os
3 import tempfile
4 import unittest
5 from collections.abc import Iterator
6
7 from flask import (
8 Flask,
9 Request,
10 Response,
11 make_response,
12 render_template,
13 request,
14 stream_with_context,
15 )
16 from flask_caching import Cache
17 from werkzeug.test import TestResponse
18
19 from flask_compress import Compress, DictCache
20 from flask_compress.flask_compress import _choose_algorithm, _uncompress_data
21
22 ALGORITHMS = ("gzip", "deflate", "br", "zstd")
23
24
25 class DefaultsTest(unittest.TestCase):
26 def setUp(self) -> None:
27 self.app = Flask(__name__)
28 self.app.testing = True
29
30 Compress(self.app)
31
32 def test_mimetypes_default(self) -> None:
33 """Tests COMPRESS_MIMETYPES default value is correctly set."""
34 defaults = [
35 "text/html",
36 "text/css",
37 "text/plain",
38 "text/xml",
39 "text/x-component",
40 "text/javascript", # Obsolete (RFC 9239)
41 "application/x-javascript",
42 "application/javascript",
43 "application/json",
44 "application/manifest+json",
45 "application/vnd.api+json",
46 "application/xml",
47 "application/xhtml+xml",
48 "application/rss+xml",
49 "application/atom+xml",
50 "application/vnd.ms-fontobject",
51 "application/x-font-ttf",
52 "application/x-font-opentype",
53 "application/x-font-truetype",
54 "image/svg+xml",
55 "image/x-icon",
56 "image/vnd.microsoft.icon",
57 "font/ttf",
58 "font/eot",
59 "font/otf",
60 "font/opentype",
61 ]
62 self.assertEqual(self.app.config["COMPRESS_MIMETYPES"], defaults)
63
64 def test_level_default(self) -> None:
65 """Tests COMPRESS_LEVEL default value is correctly set."""
66 self.assertEqual(self.app.config["COMPRESS_LEVEL"], 6)
67
68 def test_min_size_default(self) -> None:
69 """Tests COMPRESS_MIN_SIZE default value is correctly set."""
70 self.assertEqual(self.app.config["COMPRESS_MIN_SIZE"], 500)
71
72 def test_algorithm_default(self) -> None:
73 """Tests COMPRESS_ALGORITHM default value is correctly set."""
74 self.assertEqual(
75 self.app.config["COMPRESS_ALGORITHM"], ["zstd", "br", "gzip", "deflate"]
76 )
77
78 def test_algorithm_streaming(self) -> None:
79 """Tests COMPRESS_ALGORITHM_STREAMING default value is correctly set."""
80 self.assertEqual(
81 self.app.config["COMPRESS_ALGORITHM_STREAMING"], ["zstd", "br", "deflate"]
82 )
83
84 def test_default_deflate_settings(self) -> None:
85 """Tests COMPRESS_DELATE_LEVEL default value is correctly set."""
86 self.assertEqual(self.app.config["COMPRESS_DEFLATE_LEVEL"], -1)
87
88 def test_mode_default(self) -> None:
89 """Tests COMPRESS_BR_MODE default value is correctly set."""
90 self.assertEqual(self.app.config["COMPRESS_BR_MODE"], 0)
91
92 def test_quality_level_default(self) -> None:
93 """Tests COMPRESS_BR_LEVEL default value is correctly set."""
94 self.assertEqual(self.app.config["COMPRESS_BR_LEVEL"], 4)
95
96 def test_window_size_default(self) -> None:
97 """Tests COMPRESS_BR_WINDOW default value is correctly set."""
98 self.assertEqual(self.app.config["COMPRESS_BR_WINDOW"], 22)
99
100 def test_block_size_default(self) -> None:
101 """Tests COMPRESS_BR_BLOCK default value is correctly set."""
102 self.assertEqual(self.app.config["COMPRESS_BR_BLOCK"], 0)
103
104 def test_stream(self) -> None:
105 """Tests COMPRESS_STREAMS default value is correctly set."""
106 self.assertEqual(self.app.config["COMPRESS_STREAMS"], True)
107
108 def test_quality_level_default_zstd(self) -> None:
109 """Tests COMPRESS_ZSTD_LEVEL default value is correctly set."""
110 self.assertEqual(self.app.config["COMPRESS_ZSTD_LEVEL"], 3)
111
112 def test_evaluate_conditional_request(self) -> None:
113 """Tests COMPRESS_EVALUATE_CONDITIONAL_REQUEST default value
114 is correctly set."""
115 self.assertEqual(self.app.config["COMPRESS_EVALUATE_CONDITIONAL_REQUEST"], True)
116
117 def test_streaming_endpoint_conditional(self) -> None:
118 """Tests COMPRESS_STREAMING_ENDPOINT_CONDITIONAL default value
119 is correctly set."""
120 self.assertEqual(
121 self.app.config["COMPRESS_STREAMING_ENDPOINT_CONDITIONAL"], ["static"]
122 )
123
124
125 class InitTests(unittest.TestCase):
126 def setUp(self) -> None:
127 self.app = Flask(__name__)
128 self.app.testing = True
129
130 def test_constructor_init(self) -> None:
131 Compress(self.app)
132
133 def test_delayed_init(self) -> None:
134 compress = Compress()
135 compress.init_app(self.app)
136
137
138 class UrlTests(unittest.TestCase):
139 def setUp(self) -> None:
140 self.app = Flask(__name__)
141 self.app.testing = True
142
143 self.small_path = os.path.join(os.getcwd(), "tests", "templates", "small.html")
144 self.large_path = os.path.join(os.getcwd(), "tests", "templates", "large.html")
145
146 self.small_size = os.path.getsize(self.small_path) - 1
147 self.large_size = os.path.getsize(self.large_path) - 1
148
149 Compress(self.app)
150
151 @self.app.route("/small/")
152 def small() -> str:
153 return render_template("small.html")
154
155 @self.app.route("/large/")
156 def large() -> str:
157 return render_template("large.html")
158
159 def test_compressed_content(self) -> None:
160 client = self.app.test_client()
161 with open(self.large_path, "rb") as f:
162 original_data = f.read().rstrip() # flask strips trailing newline
163
164 for algorithm in ALGORITHMS:
165 headers = [("Accept-Encoding", algorithm)]
166 response = client.get("/large/", headers=headers)
167 self.assertIn("Content-Encoding", response.headers)
168 self.assertEqual(response.status_code, 200)
169 self.assertEqual(response.is_streamed, True)
170 self.assertGreater(self.large_size, len(response.data))
171 self.assertEqual(original_data, _uncompress_data(response.data, algorithm))
172
173 def client_get(self, ufs: str) -> TestResponse:
174 client = self.app.test_client()
175 response = client.get(ufs, headers=[("Accept-Encoding", "gzip")])
176 self.assertEqual(response.status_code, 200)
177 return response
178
179 def test_br_algorithm(self) -> None:
180 client = self.app.test_client()
181 headers = [("Accept-Encoding", "br")]
182
183 response = client.options("/small/", headers=headers)
184 self.assertEqual(response.status_code, 200)
185
186 response = client.options("/large/", headers=headers)
187 self.assertEqual(response.status_code, 200)
188
189 def test_zstd_algorithm(self) -> None:
190 client = self.app.test_client()
191 headers = [("Accept-Encoding", "zstd")]
192
193 response = client.options("/small/", headers=headers)
194 self.assertEqual(response.status_code, 200)
195
196 response = client.options("/large/", headers=headers)
197 self.assertEqual(response.status_code, 200)
198
199 def test_compress_min_size(self) -> None:
200 """Tests COMPRESS_MIN_SIZE correctly affects response data."""
201 response = self.client_get("/small/")
202 self.assertEqual(self.small_size, len(response.data))
203
204 response = self.client_get("/large/")
205 self.assertNotEqual(self.large_size, len(response.data))
206
207 def test_mimetype_mismatch(self) -> None:
208 """Tests if mimetype not in COMPRESS_MIMETYPES."""
209 response = self.client_get("/static/1.png")
210 self.assertEqual(response.mimetype, "image/png")
211
212 def test_content_length_options(self) -> None:
213 client = self.app.test_client()
214 headers = [("Accept-Encoding", "gzip")]
215 response = client.options("/small/", headers=headers)
216 self.assertEqual(response.status_code, 200)
217
218 def test_gzip_compression_level(self) -> None:
219 """Tests COMPRESS_LEVEL correctly affects response data."""
220 self.app.config["COMPRESS_LEVEL"] = 1
221 client = self.app.test_client()
222 response = client.get("/large/", headers=[("Accept-Encoding", "gzip")])
223 response1_size = len(response.data)
224
225 self.app.config["COMPRESS_LEVEL"] = 6
226 client = self.app.test_client()
227 response = client.get("/large/", headers=[("Accept-Encoding", "gzip")])
228 response6_size = len(response.data)
229
230 self.assertNotEqual(response1_size, response6_size)
231
232 def test_br_compression_level(self) -> None:
233 """Tests that COMPRESS_BR_LEVEL correctly affects response data."""
234 self.app.config["COMPRESS_BR_LEVEL"] = 4
235 client = self.app.test_client()
236 response = client.get("/large/", headers=[("Accept-Encoding", "br")])
237 response4_size = len(response.data)
238
239 self.app.config["COMPRESS_BR_LEVEL"] = 11
240 client = self.app.test_client()
241 response = client.get("/large/", headers=[("Accept-Encoding", "br")])
242 response11_size = len(response.data)
243
244 self.assertNotEqual(response4_size, response11_size)
245
246 def test_deflate_compression_level(self) -> None:
247 """Tests COMPRESS_DELATE_LEVEL correctly affects response data."""
248 self.app.config["COMPRESS_DEFLATE_LEVEL"] = -1
249 client = self.app.test_client()
250 response = client.get("/large/", headers=[("Accept-Encoding", "deflate")])
251 response_size = len(response.data)
252
253 self.app.config["COMPRESS_DEFLATE_LEVEL"] = 1
254 client = self.app.test_client()
255 response = client.get("/large/", headers=[("Accept-Encoding", "deflate")])
256 response1_size = len(response.data)
257
258 self.assertNotEqual(response_size, response1_size)
259
260 def test_zstd_compression_level(self) -> None:
261 """Tests that COMPRESS_ZSTD_LEVEL correctly affects response data."""
262 self.app.config["COMPRESS_ZSTD_LEVEL"] = 1
263 client = self.app.test_client()
264 response = client.get("/large/", headers=[("Accept-Encoding", "zstd")])
265 response1_size = len(response.data)
266
267 self.app.config["COMPRESS_ZSTD_LEVEL"] = 11
268 client = self.app.test_client()
269 response = client.get("/large/", headers=[("Accept-Encoding", "zstd")])
270 response11_size = len(response.data)
271
272 self.assertNotEqual(response1_size, response11_size)
273
274 def test_when_response_empty(self) -> None:
275 """Tests that after_request returns 204 when response is None."""
276 compress = Compress(self.app)
277 with self.app.app_context():
278 r1 = compress.after_request(None)
279 self.assertEqual(r1.status_code, 204)
280 self.assertEqual(r1.get_data(as_text=True), "")
281
282
283 class CompressionAlgoTests(unittest.TestCase):
284 """
285 Test different scenarios for compression algorithm negotiation between
286 client and server. Please note that algorithm names (even the "supported"
287 ones) in these tests **do not** indicate that all of these are actually
288 supported by this extension.
289 """
290
291 def setUp(self) -> None:
292 super().setUp()
293
294 # Create the app here but don't call `Compress()` on it just yet;
295 # we need to be able to modify the settings in various tests.
296 # Calling `Compress(self.app)` twice would result in
297 # two `@after_request` handlers, which would be bad.
298 self.app = Flask(__name__)
299 self.app.testing = True
300
301 small_path = os.path.join(os.getcwd(), "tests", "templates", "small.html")
302 self.small_size = os.path.getsize(small_path) - 1
303
304 @self.app.route("/small/")
305 def small() -> str:
306 return render_template("small.html")
307
308 def test_setting_compress_algorithm_simple_string(self) -> None:
309 """Test that a single entry in `COMPRESS_ALGORITHM` still works.
310
311 This is a backwards-compatibility test."""
312 self.app.config["COMPRESS_ALGORITHM"] = "gzip"
313 c = Compress(self.app)
314 self.assertTupleEqual(c.enabled_algorithms, ("gzip",))
315
316 def test_setting_compress_algorithm_cs_string(self) -> None:
317 """Test that `COMPRESS_ALGORITHM` can be a comma-separated string"""
318 self.app.config["COMPRESS_ALGORITHM"] = "gzip, br, zstd"
319 c = Compress(self.app)
320 self.assertTupleEqual(c.enabled_algorithms, ("gzip", "br", "zstd"))
321
322 def test_setting_compress_algorithm_list(self) -> None:
323 """Test that `COMPRESS_ALGORITHM` can be a list of strings"""
324 self.app.config["COMPRESS_ALGORITHM"] = ["gzip", "br", "deflate"]
325 c = Compress(self.app)
326 self.assertTupleEqual(c.enabled_algorithms, ("gzip", "br", "deflate"))
327
328 def test_one_algo_supported(self) -> None:
329 """Tests requesting a single supported compression algorithm"""
330 accept_encoding = "gzip"
331 self.app.config["COMPRESS_ALGORITHM"] = ["br", "gzip"]
332 c = Compress(self.app)
333 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
334 self.assertEqual(chosen_algorithm, "gzip")
335
336 def test_one_algo_unsupported(self) -> None:
337 """Tests requesting single unsupported compression algorithm"""
338 accept_encoding = "some-alien-algorithm"
339 self.app.config["COMPRESS_ALGORITHM"] = ["br", "gzip"]
340 c = Compress(self.app)
341 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
342 self.assertIsNone(chosen_algorithm)
343
344 def test_multiple_algos_supported(self) -> None:
345 """Tests requesting multiple supported compression algorithms"""
346 accept_encoding = "br, gzip, zstd"
347 self.app.config["COMPRESS_ALGORITHM"] = ["zstd", "br", "gzip"]
348 c = Compress(self.app)
349 # When the decision is tied, we expect the first server-configured algorithm
350 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
351 self.assertEqual(chosen_algorithm, "zstd")
352
353 def test_multiple_algos_unsupported(self) -> None:
354 """Tests requesting multiple unsupported compression algorithms"""
355 accept_encoding = "future-algo, alien-algo, forbidden-algo"
356 self.app.config["COMPRESS_ALGORITHM"] = ["zstd", "br", "gzip"]
357 c = Compress(self.app)
358 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
359 self.assertIsNone(chosen_algorithm)
360
361 def test_multiple_algos_with_wildcard(self) -> None:
362 """Request multiple unsupported compression algorithms and a wildcard"""
363 accept_encoding = "future-algo, alien-algo, forbidden-algo, *"
364 self.app.config["COMPRESS_ALGORITHM"] = ["zstd", "br", "gzip"]
365 c = Compress(self.app)
366 # We expect to see the first server-configured algorithm
367 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
368 self.assertEqual(chosen_algorithm, "zstd")
369
370 def test_multiple_algos_with_different_quality(self) -> None:
371 """Request multiple supported compression algorithms with different q-factors"""
372 accept_encoding = "zstd;q=0.8, br;q=0.9, gzip;q=0.5"
373 self.app.config["COMPRESS_ALGORITHM"] = ["zstd", "br", "gzip"]
374 c = Compress(self.app)
375 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
376 self.assertEqual(chosen_algorithm, "br")
377
378 def test_multiple_algos_with_equal_quality(self) -> None:
379 """Request multiple supported compression algorithms with equal q-factors"""
380 accept_encoding = "zstd;q=0.5, br;q=0.5, gzip;q=0.5"
381 self.app.config["COMPRESS_ALGORITHM"] = ["gzip", "br", "zstd"]
382 c = Compress(self.app)
383 # We expect to see the first server-configured algorithm
384 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
385 self.assertEqual(chosen_algorithm, "gzip")
386
387 def test_default_quality_is_1(self) -> None:
388 """Tests that when making mixed-quality requests, the default q-factor is 1.0"""
389 accept_encoding = "deflate, br;q=0.999, gzip;q=0.5"
390 self.app.config["COMPRESS_ALGORITHM"] = ["gzip", "br", "deflate"]
391 c = Compress(self.app)
392 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
393 self.assertEqual(chosen_algorithm, "deflate")
394
395 def test_default_wildcard_quality_is_0(self) -> None:
396 """Tests that a wildcard has a default q-factor of 0.0"""
397 accept_encoding = "br;q=0.001, *"
398 self.app.config["COMPRESS_ALGORITHM"] = ["gzip", "br", "deflate"]
399 c = Compress(self.app)
400 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
401 self.assertEqual(chosen_algorithm, "br")
402
403 def test_wildcard_quality(self) -> None:
404 """Tests that a wildcard with q=0 is discarded"""
405 accept_encoding = "*;q=0"
406 self.app.config["COMPRESS_ALGORITHM"] = ["gzip", "br", "deflate"]
407 c = Compress(self.app)
408 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
409 self.assertIsNone(chosen_algorithm)
410
411 def test_identity(self) -> None:
412 """Tests that identity is understood"""
413 accept_encoding = "identity;q=1, br;q=0.5, *;q=0"
414 self.app.config["COMPRESS_ALGORITHM"] = ["gzip", "br", "deflate"]
415 c = Compress(self.app)
416 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
417 self.assertIsNone(chosen_algorithm)
418
419 def test_chrome_ranged_requests(self) -> None:
420 """Tests that Chrome ranged requests behave as expected"""
421 accept_encoding = "identity;q=1, *;q=0"
422 self.app.config["COMPRESS_ALGORITHM"] = ["gzip", "br", "deflate"]
423 c = Compress(self.app)
424 chosen_algorithm = _choose_algorithm(c.enabled_algorithms, accept_encoding)
425 self.assertIsNone(chosen_algorithm)
426
427 def test_content_encoding_is_correct(self) -> None:
428 """Test that the `Content-Encoding` header matches the compression algorithm"""
429 self.app.config["COMPRESS_ALGORITHM"] = ["zstd", "br", "gzip", "deflate"]
430 Compress(self.app)
431
432 headers_gzip = [("Accept-Encoding", "gzip")]
433 client = self.app.test_client()
434 response_gzip = client.options("/small/", headers=headers_gzip)
435 self.assertIn("Content-Encoding", response_gzip.headers)
436 self.assertEqual(response_gzip.headers.get("Content-Encoding"), "gzip")
437
438 headers_br = [("Accept-Encoding", "br")]
439 client = self.app.test_client()
440 response_br = client.options("/small/", headers=headers_br)
441 self.assertIn("Content-Encoding", response_br.headers)
442 self.assertEqual(response_br.headers.get("Content-Encoding"), "br")
443
444 headers_deflate = [("Accept-Encoding", "deflate")]
445 client = self.app.test_client()
446 response_deflate = client.options("/small/", headers=headers_deflate)
447 self.assertIn("Content-Encoding", response_deflate.headers)
448 self.assertEqual(response_deflate.headers.get("Content-Encoding"), "deflate")
449
450 headers_zstd = [("Accept-Encoding", "zstd")]
451 client = self.app.test_client()
452 response_zstd = client.options("/small/", headers=headers_zstd)
453 self.assertIn("Content-Encoding", response_zstd.headers)
454 self.assertEqual(response_zstd.headers.get("Content-Encoding"), "zstd")
455
456
457 class CompressionPerViewTests(unittest.TestCase):
458 def setUp(self) -> None:
459 self.app = Flask(__name__)
460 self.app.testing = True
461 self.app.config["COMPRESS_REGISTER"] = False
462 compress = Compress()
463 compress.init_app(self.app)
464
465 @self.app.route("/route1/")
466 def view_1() -> str:
467 return render_template("large.html")
468
469 @self.app.route("/route2/")
470 @compress.compressed()
471 def view_2() -> str:
472 return render_template("large.html")
473
474 def test_compression(self) -> None:
475 client = self.app.test_client()
476 headers = [("Accept-Encoding", "deflate")]
477
478 response = client.get("/route1/", headers=headers)
479 self.assertEqual(response.status_code, 200)
480 self.assertNotIn("Content-Encoding", response.headers)
481
482 response = client.get("/route2/", headers=headers)
483 self.assertEqual(response.status_code, 200)
484 self.assertIn("Content-Encoding", response.headers)
485 self.assertEqual(response.headers.get("Content-Encoding"), "deflate")
486
487
488 class StreamTests(unittest.TestCase):
489 def setUp(self) -> None:
490 self.app = Flask(__name__)
491 self.app.testing = True
492
493 self.app.config["COMPRESS_ALGORITHM_STREAMING"] = [
494 "zstd",
495 "br",
496 "gzip", # not by default for streaming
497 "deflate",
498 ]
499
500 self.file_path = os.path.join(os.getcwd(), "tests", "templates", "large.html")
501 self.file_size = os.path.getsize(self.file_path)
502
503 @self.app.route("/stream/large")
504 def stream() -> Response:
505 def _stream() -> Iterator[str]:
506 with open(self.file_path) as f:
507 yield from f.readlines()
508
509 return self.app.response_class(_stream(), mimetype="text/html")
510
511 def test_no_compression_stream(self) -> None:
512 """Tests compression is skipped when COMPRESS_STREAMS is False"""
513 Compress(self.app)
514 self.app.config["COMPRESS_STREAMS"] = False
515 client = self.app.test_client()
516
517 for algorithm in (*ALGORITHMS, ""):
518 headers = [("Accept-Encoding", algorithm)]
519 response = client.get("/stream/large", headers=headers)
520 self.assertEqual(response.status_code, 200)
521 self.assertEqual(response.is_streamed, True)
522 self.assertEqual(self.file_size, len(response.data))
523
524 def test_compression_stream(self) -> None:
525 Compress(self.app)
526 client = self.app.test_client()
527 with open(self.file_path, "rb") as f:
528 original_data = f.read()
529
530 for algorithm in ALGORITHMS:
531 headers = [("Accept-Encoding", algorithm)]
532 response = client.get("/stream/large", headers=headers)
533 self.assertIn("Content-Encoding", response.headers)
534 self.assertEqual(response.status_code, 200)
535 self.assertEqual(response.is_streamed, True)
536 self.assertGreater(self.file_size, len(response.data))
537 self.assertEqual(original_data, _uncompress_data(response.data, algorithm))
538
539 headers = [("Accept-Encoding", "")]
540 response = client.get("/stream/large", headers=headers)
541 self.assertNotIn("Content-Encoding", response.headers)
542 self.assertEqual(response.status_code, 200)
543 self.assertEqual(response.is_streamed, True)
544 self.assertEqual(self.file_size, len(response.data))
545 self.assertEqual(original_data, response.data)
546
547
548 class StreamTestsWithETags(unittest.TestCase):
549 def setUp(self) -> None:
550 self.app = Flask(__name__, static_folder="web", static_url_path="/path")
551 self.app.testing = True
552
553 self.file_path = os.path.join(os.getcwd(), "tests", "templates", "large.html")
554 self.file_size = os.path.getsize(self.file_path)
555
556 self.app.config["COMPRESS_MIN_SIZE"] = 1
557
558 Compress(self.app)
559
560 @self.app.route("/stream/large")
561 def stream() -> Response:
562 def _stream() -> Iterator[str]:
563 with open(self.file_path) as f:
564 yield from f.readlines()
565
566 rv = make_response(stream_with_context(_stream()))
567 rv.mimetype = "text/html"
568 rv.set_etag("stream-etag", weak=False)
569 return rv
570
571 def test_conditionals_are_skipped_on_streaming(self) -> None:
572 client = self.app.test_client()
573
574 r1 = client.get("/stream/large", headers=[("Accept-Encoding", "br")])
575 tag, is_weak = r1.get_etag()
576 self.assertEqual(r1.status_code, 200)
577 self.assertEqual(r1.is_streamed, True)
578 self.assertIn("Content-Encoding", r1.headers)
579 self.assertEqual(r1.headers.get("Content-Encoding"), "br")
580 self.assertEqual(tag, "stream-etag:br")
581 self.assertFalse(is_weak)
582 r1.close()
583
584 r2 = client.get(
585 "/stream/large",
586 headers=[("Accept-Encoding", "br"), ("If-None-Match", r1.headers["ETag"])],
587 )
588 self.assertEqual(r2.status_code, 200) # Should be 200, not 304
589 self.assertEqual(r2.is_streamed, True)
590 self.assertIn("Content-Encoding", r1.headers)
591 self.assertEqual(r1.headers.get("Content-Encoding"), "br")
592 r2.close()
593
594 def test_static_exception_to_conditionals(self) -> None:
595 # Here we test that the static endpoint, which is using streaming responses,
596 # still respects conditional requests even when streaming.
597 # We use a custom static folder and static url path to show that the test
598 # works even if those are changed from the defaults.
599 # In practice there is almost no chance for a user to accidentally write a
600 # streaming 'static' endpoint, as this will raise an exception in Flask,
601 # because of the predefined static file handling.
602 client = self.app.test_client()
603
604 r1 = client.get("/path/test.xml", headers=[("Accept-Encoding", "br")])
605 tag, is_weak = r1.get_etag()
606 self.assertEqual(r1.status_code, 200)
607 self.assertEqual(r1.is_streamed, True)
608 self.assertIn("Content-Encoding", r1.headers)
609 self.assertEqual(r1.headers.get("Content-Encoding"), "br")
610 self.assertIsNotNone(tag)
611 assert tag is not None
612 self.assertEqual(tag[-3:], ":br")
613 self.assertFalse(is_weak)
614 r1.close()
615
616 r2 = client.get(
617 "/path/test.xml",
618 headers=[("Accept-Encoding", "br"), ("If-None-Match", r1.headers["ETag"])],
619 )
620 self.assertEqual(r2.status_code, 304) # static endpoint has an exception
621 self.assertEqual(r2.is_streamed, True)
622 self.assertIn("Content-Encoding", r1.headers)
623 self.assertEqual(r1.headers.get("Content-Encoding"), "br")
624 r2.close()
625
626
627 class CachingCompressionTests(unittest.TestCase):
628 def setUp(self) -> None:
629 # We keep track of the number of times the view is called
630 self.view_calls = 0
631 self.tmpdir = tempfile.TemporaryDirectory()
632
633 self.app = Flask(__name__)
634 self.app.testing = True
635 cache = Cache(
636 config={
637 "CACHE_TYPE": "FileSystemCache",
638 "CACHE_DIR": self.tmpdir.name,
639 "CACHE_DEFAULT_TIMEOUT": 60 * 60, # 1 hour cache timeout
640 }
641 )
642 cache.init_app(self.app)
643
644 def get_cache_key(request: Request) -> str:
645 return request.url
646
647 compress = Compress()
648 compress.init_app(self.app)
649
650 compress.cache = cache
651 compress.cache_key = get_cache_key
652
653 @self.app.route("/route/")
654 def view() -> str:
655 self.view_calls += 1
656 return render_template("large.html")
657
658 def tearDown(self) -> None:
659 self.tmpdir.cleanup()
660
661 def test_compression(self) -> None:
662 # Here we are testing cache pollution where the same query is cached
663 # but with different compression algorithms. The cache key should include
664 # the compression algorithm so that the cache is not polluted.
665 client = self.app.test_client()
666
667 headers = [("Accept-Encoding", "deflate")]
668 response = client.get("/route/", headers=headers)
669 self.assertEqual(response.status_code, 200)
670 self.assertIn("Content-Encoding", response.headers)
671 self.assertEqual(response.headers.get("Content-Encoding"), "deflate")
672 self.assertEqual(self.view_calls, 1)
673
674 headers = [("Accept-Encoding", "gzip")]
675 response = client.get("/route/", headers=headers)
676 self.assertEqual(response.status_code, 200)
677 self.assertIn("Content-Encoding", response.headers)
678 self.assertEqual(response.headers.get("Content-Encoding"), "gzip")
679 self.assertEqual(self.view_calls, 2)
680 # If cache is polluted, this decompression fails as we get brotli
681 _ = gzip.decompress(response.data)
682
683
684 class DictCacheTests(unittest.TestCase):
685 def setUp(self) -> None:
686 # We keep track of the number of times the cache key function is called
687 self.cache_key_calls = 0
688 self.app = Flask(__name__)
689 self.app.testing = True
690
691 def get_cache_key(request: Request) -> str:
692 self.cache_key_calls += 1
693 return request.url
694
695 compress = Compress()
696 compress.init_app(self.app)
697
698 compress.cache = DictCache()
699 compress.cache_key = get_cache_key
700
701 @self.app.route("/route/")
702 def view() -> str:
703 return render_template("large.html")
704
705 def test_compression(self) -> None:
706 client = self.app.test_client()
707
708 headers = [("Accept-Encoding", "deflate")]
709 response = client.get("/route/", headers=headers)
710 self.assertEqual(response.status_code, 200)
711 self.assertIn("Content-Encoding", response.headers)
712 self.assertEqual(response.headers.get("Content-Encoding"), "deflate")
713 self.assertEqual(self.cache_key_calls, 1)
714
715 headers = [("Accept-Encoding", "deflate")]
716 response = client.get("/route/", headers=headers)
717 self.assertEqual(response.status_code, 200)
718 self.assertIn("Content-Encoding", response.headers)
719 self.assertEqual(response.headers.get("Content-Encoding"), "deflate")
720 self.assertEqual(self.cache_key_calls, 2)
721
722
723 class ETagTests(unittest.TestCase):
724 def setUp(self) -> None:
725 self.app = Flask(__name__)
726 self.app.testing = True
727 self.app.config["COMPRESS_ALGORITHM"] = ["gzip"]
728 self.app.config["COMPRESS_MIN_SIZE"] = 1
729
730 Compress(self.app)
731
732 @self.app.route("/strong/")
733 def strong() -> Response:
734 rv = make_response(render_template("large.html"))
735 rv.set_etag("abc123", weak=False)
736 rv.make_conditional(request)
737 return rv
738
739 @self.app.route("/strong-compress-conditional/")
740 def strong_compress_conditional() -> Response:
741 rv = make_response(render_template("large.html"))
742 rv.set_etag("abc123", weak=False)
743 return rv
744
745 @self.app.route("/weak/")
746 def weak() -> Response:
747 rv = make_response(render_template("large.html"))
748 rv.set_etag("abc123", weak=True)
749 rv.make_conditional(request)
750 return rv
751
752 @self.app.route("/weak-compress-conditional/")
753 def weak_compress_conditional() -> Response:
754 rv = make_response(render_template("large.html"))
755 rv.set_etag("abc123", weak=True)
756 return rv
757
758 def test_strong_etag_is_mutated_with_suffix_and_remains_strong(self) -> None:
759 client = self.app.test_client()
760 r = client.get("/strong/", headers=[("Accept-Encoding", "gzip")])
761 self.assertEqual(r.status_code, 200)
762 self.assertEqual(r.headers.get("Content-Encoding"), "gzip")
763
764 tag, is_weak = r.get_etag()
765 self.assertFalse(is_weak)
766 self.assertEqual(tag, "abc123:gzip")
767 self.assertEqual(int(r.headers["Content-Length"]), len(r.data))
768
769 def test_weak_etag_is_preserved(self) -> None:
770 client = self.app.test_client()
771 r = client.get("/weak/", headers=[("Accept-Encoding", "gzip")])
772 self.assertEqual(r.status_code, 200)
773 self.assertEqual(r.headers.get("Content-Encoding"), "gzip")
774
775 tag, is_weak = r.get_etag()
776 self.assertTrue(is_weak)
777 # No :gzip suffix when flag is False
778 self.assertEqual(tag, "abc123")
779
780 def test_conditional_get_uses_strong_compressed_representation(self) -> None:
781 self.app.config["COMPRESS_EVALUATE_CONDITIONAL_REQUEST"] = False
782 client = self.app.test_client()
783 r1 = client.get("/strong/", headers=[("Accept-Encoding", "gzip")])
784
785 r2 = client.get(
786 "/strong/",
787 headers=[
788 ("Accept-Encoding", "gzip"),
789 ("If-None-Match", r1.headers["ETag"]),
790 ],
791 )
792 # This is the old behavior that broke make_conditional
793 # strong etags due rewrite at after_request
794 # We would expect a 304 but it does not because of etag mismatch
795 self.assertEqual(r2.status_code, 200)
796
797 def test_conditional_get_uses_weak_compressed_representation(self) -> None:
798 self.app.config["COMPRESS_EVALUATE_CONDITIONAL_REQUEST"] = False
799 client = self.app.test_client()
800 r1 = client.get("/weak/", headers=[("Accept-Encoding", "gzip")])
801 etag_header = r1.headers["ETag"]
802
803 r2 = client.get(
804 "/weak/",
805 headers=[("Accept-Encoding", "gzip"), ("If-None-Match", etag_header)],
806 )
807 # This is the behaviour we expect by not mutating
808 # the weak etags at after_request
809 self.assertEqual(r2.status_code, 304)
810 self.assertEqual(r2.headers.get("ETag"), etag_header)
811 self.assertNotIn("Content-Encoding", r2.headers)
812 self.assertEqual(len(r2.get_data()), 0)
813
814 def test_conditional_get_uses_strong_compressed_representation_evaluate_conditional(
815 self,
816 ) -> None:
817 client = self.app.test_client()
818 r1 = client.get(
819 "/strong-compress-conditional/", headers=[("Accept-Encoding", "gzip")]
820 )
821 etag_header = r1.headers["ETag"]
822
823 r2 = client.get(
824 "/strong-compress-conditional/",
825 headers=[("Accept-Encoding", "gzip"), ("If-None-Match", etag_header)],
826 )
827 # This is the behaviour we would expect after evaluating
828 # flask make_conditional at after_request
829 self.assertEqual(r2.status_code, 304)
830 self.assertEqual(r2.headers.get("ETag"), etag_header)
831 self.assertNotIn("Content-Encoding", r2.headers)
832 self.assertEqual(len(r2.get_data()), 0)
833
834 def test_conditional_get_uses_weak_compressed_representation_evaluate_conditional(
835 self,
836 ) -> None:
837 client = self.app.test_client()
838 r1 = client.get(
839 "/weak-compress-conditional/", headers=[("Accept-Encoding", "gzip")]
840 )
841 etag_header = r1.headers["ETag"]
842
843 r2 = client.get(
844 "/weak-compress-conditional/",
845 headers=[("Accept-Encoding", "gzip"), ("If-None-Match", etag_header)],
846 )
847 # This is the behaviour we would expect after evaluating
848 # flask make_conditional at after_request
849 self.assertEqual(r2.status_code, 304)
850 self.assertEqual(r2.headers.get("ETag"), etag_header)
851 self.assertNotIn("Content-Encoding", r2.headers)
852 self.assertEqual(len(r2.get_data()), 0)
853
854
855 if __name__ == "__main__":
856 unittest.main()