test_web_gateway.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """Static HTTP hosting tests; API traffic uses WebSocket or native gRPC."""
  2. import asyncio
  3. from pathlib import Path
  4. import tempfile
  5. import unittest
  6. import urllib.error
  7. import urllib.request
  8. from stl_backend.config import load_settings
  9. from stl_backend.server import start_server
  10. from stl_backend.web_gateway import WebGateway
  11. def http(url, method="GET"):
  12. request = urllib.request.Request(url, method=method)
  13. try:
  14. response = urllib.request.urlopen(request, timeout=5)
  15. except urllib.error.HTTPError as exc:
  16. response = exc
  17. with response:
  18. return response.status, dict(response.headers), response.read()
  19. class WebGatewayTests(unittest.IsolatedAsyncioTestCase):
  20. async def asyncSetUp(self):
  21. self.tmp = tempfile.TemporaryDirectory(prefix="stl-static-")
  22. settings = load_settings("config/simulated.json")
  23. settings["listen"] = "127.0.0.1:0"
  24. settings["data_dir"] = self.tmp.name
  25. self.server, self.bench, self.grpc_port = await start_server(settings)
  26. web_dir = Path(__file__).resolve().parents[1] / "src/stl_backend/web"
  27. self.gateway = WebGateway(self.bench.grpc_service, "127.0.0.1", 0, web_dir)
  28. await self.gateway.start()
  29. self.url = f"http://127.0.0.1:{self.gateway.server.sockets[0].getsockname()[1]}"
  30. async def asyncTearDown(self):
  31. await self.gateway.stop()
  32. await self.server.stop(0)
  33. await self.bench.grpc_service.drain()
  34. await self.bench.close()
  35. self.tmp.cleanup()
  36. async def test_static_and_missing_asset(self):
  37. status, headers, body = await asyncio.to_thread(http, self.url + "/")
  38. self.assertEqual(status, 200)
  39. self.assertIn("内存高温测试工作台", body.decode())
  40. self.assertIn("no-cache", headers["Cache-Control"])
  41. status, _, _ = await asyncio.to_thread(http, self.url + "/missing.js")
  42. self.assertEqual(status, 404)
  43. async def test_http_has_no_rpc_endpoint(self):
  44. status, _, _ = await asyncio.to_thread(
  45. http, self.url + "/stl.v1.BenchService/GetSystemInfo", "POST")
  46. self.assertEqual(status, 405)
  47. async def test_sibling_path_cannot_escape_static_directory(self):
  48. web = Path(self.tmp.name) / "web"
  49. sibling = Path(self.tmp.name) / "web-other"
  50. web.mkdir()
  51. sibling.mkdir()
  52. (sibling / "secret.txt").write_text("not static")
  53. self.gateway.web_dir = web
  54. status, _, _ = await asyncio.to_thread(http, self.url + "/../web-other/secret.txt")
  55. self.assertEqual(status, 404)