import unittest import sys import os import json import gzip import io # 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 TestWebDashboard(unittest.TestCase): def setUp(self): self.app = app.test_client() self.app.testing = True def test_dashboard_route(self): """Test that the root route returns HTML.""" response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'', response.data) self.assertIn(b'MQL5 Trading Automation Dashboard', response.data) def test_health_route_json(self): """Test that the health route returns a JSON response.""" response = self.app.get('/health') self.assertEqual(response.status_code, 200) # This is what we expect AFTER the optimization. # For TDD, this test will fail initially if I ran it now against the current code # (because current code returns HTML for /health). try: data = json.loads(response.data) self.assertEqual(data.get('status'), 'healthy') except json.JSONDecodeError: self.fail("Response is not valid JSON") def test_skip_link_present(self): """Test that the skip link is present in the dashboard HTML.""" response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'', response.data) def test_security_headers(self): """Test that security headers are present.""" response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn('Content-Security-Policy', response.headers) self.assertIn('X-Content-Type-Options', response.headers) self.assertIn('X-Frame-Options', response.headers) self.assertIn('Referrer-Policy', response.headers) def test_gzip_compression(self): """Test that responses are gzip compressed when requested.""" # 1. Request without gzip resp = self.app.get('/') self.assertEqual(resp.status_code, 200) # Headers should not contain Content-Encoding self.assertNotIn('Content-Encoding', resp.headers) # 2. Request with gzip resp_gzip = self.app.get('/', headers={'Accept-Encoding': 'gzip'}) self.assertEqual(resp_gzip.status_code, 200) # Check if response is large enough to be compressed original_size = len(resp.data) if original_size < 500: # If too small, it won't be compressed self.assertNotIn('Content-Encoding', resp_gzip.headers) return self.assertIn('Content-Encoding', resp_gzip.headers) self.assertEqual(resp_gzip.headers['Content-Encoding'], 'gzip') self.assertIn('Vary', resp_gzip.headers) self.assertIn('Accept-Encoding', resp_gzip.headers['Vary']) # Decompress and compare buffer = io.BytesIO(resp_gzip.data) with gzip.GzipFile(mode='rb', fileobj=buffer) as f: decompressed_data = f.read() self.assertEqual(decompressed_data, resp.data) if __name__ == '__main__': unittest.main()