import unittest import sys import os import gzip from io import BytesIO # Add scripts directory to path so we can import web_dashboard sys.path.append(os.path.dirname(os.path.abspath(__file__))) from web_dashboard import app class TestWebDashboardCompression(unittest.TestCase): def setUp(self): self.app = app.test_client() self.app.testing = True def test_gzip_compression_enabled(self): """Test that the response is gzipped when Accept-Encoding contains gzip and content is large.""" # Ensure we hit a route that returns > 500 bytes (e.g. dashboard with README) response = self.app.get('/', headers={'Accept-Encoding': 'gzip'}) self.assertEqual(response.headers.get('Content-Encoding'), 'gzip', "Response should be gzipped") self.assertIn('Vary', response.headers) self.assertIn('Accept-Encoding', response.headers['Vary']) # Verify content is actually compressed try: gzip.GzipFile(fileobj=BytesIO(response.data)).read() except OSError: self.fail("Response content is not valid gzip data") def test_no_compression_without_header(self): """Test that the response is NOT gzipped when Accept-Encoding is missing.""" response = self.app.get('/') self.assertIsNone(response.headers.get('Content-Encoding'), "Response should not be gzipped without header") def test_no_compression_for_small_response(self): """Test that small responses are not gzipped.""" # /health returns a small JSON response = self.app.get('/health', headers={'Accept-Encoding': 'gzip'}) self.assertIsNone(response.headers.get('Content-Encoding'), "Small response should not be gzipped") if __name__ == '__main__': unittest.main()