"""Behavioral tests for response compression. The contract under test: large JSON responses are compressed via the encoding the client advertises (gzip and brotli, both shipped with flask-compress), while streamed exports (``Response(stream_with_context(...))``) are left uncompressed because ``COMPRESS_STREAMS=False`` (flask-compress must not buffer the streamed contract exports). """ from collections.abc import Iterator from flask import Flask, Response, jsonify, stream_with_context from core.config import Config from core.hardening.compression import setup_compression class _Cfg(Config): pass def _build_app() -> Flask: app = Flask(__name__) setup_compression(app, _Cfg) @app.get('/big') def big() -> Response: return jsonify({'x': 'y' * 5000}) @app.get('/stream') def stream() -> Response: def gen() -> Iterator[str]: for _ in range(100): yield 'y' * 50 return Response(stream_with_context(gen()), mimetype='application/json') @app.get('/tiny') def tiny() -> Response: return jsonify({'x': 'y'}) # well under COMPRESS_MIN_SIZE (500 bytes) @app.get('/csv') def csv() -> Response: return Response('y' * 5000, mimetype='text/csv') # not in COMPRESS_MIMETYPES return app def test_large_json_is_gzipped() -> None: """A sizable JSON body is gzipped when the client advertises gzip support.""" res = _build_app().test_client().get('/big', headers={'Accept-Encoding': 'gzip'}) assert res.headers.get('Content-Encoding') == 'gzip' def test_large_json_is_brotli_compressed() -> None: """A brotli-only client gets brotli: flask-compress ships brotli and prefers it over gzip.""" res = _build_app().test_client().get('/big', headers={'Accept-Encoding': 'br'}) assert res.headers.get('Content-Encoding') == 'br' def test_small_body_is_not_compressed() -> None: """A body under COMPRESS_MIN_SIZE (500 bytes) is left uncompressed.""" res = _build_app().test_client().get('/tiny', headers={'Accept-Encoding': 'gzip'}) assert 'Content-Encoding' not in res.headers def test_non_allowlisted_mimetype_is_not_compressed() -> None: """A large response whose type is not in COMPRESS_MIMETYPES (text/csv) is left uncompressed.""" res = _build_app().test_client().get('/csv', headers={'Accept-Encoding': 'gzip'}) assert 'Content-Encoding' not in res.headers def test_streamed_export_is_not_compressed() -> None: """A streamed export stays uncompressed. Advertise ``deflate``: flask-compress would compress a stream with that encoding if ``COMPRESS_STREAMS`` were left at its default (True), so this genuinely guards the ``COMPRESS_STREAMS=False`` setting (a gzip-only client never gets a compressed stream regardless, which would make the assertion vacuous). """ res = ( _build_app() .test_client() .get('/stream', headers={'Accept-Encoding': 'deflate'}) ) assert 'Content-Encoding' not in res.headers