| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- """Static HTTP hosting tests; API traffic uses WebSocket or native gRPC."""
- import asyncio
- from pathlib import Path
- import tempfile
- import unittest
- import urllib.error
- import urllib.request
- from stl_backend.config import load_settings
- from stl_backend.server import start_server
- from stl_backend.web_gateway import WebGateway
- def http(url, method="GET"):
- request = urllib.request.Request(url, method=method)
- try:
- response = urllib.request.urlopen(request, timeout=5)
- except urllib.error.HTTPError as exc:
- response = exc
- with response:
- return response.status, dict(response.headers), response.read()
- class WebGatewayTests(unittest.IsolatedAsyncioTestCase):
- async def asyncSetUp(self):
- self.tmp = tempfile.TemporaryDirectory(prefix="stl-static-")
- settings = load_settings("config/simulated.json")
- settings["listen"] = "127.0.0.1:0"
- settings["data_dir"] = self.tmp.name
- self.server, self.bench, self.grpc_port = await start_server(settings)
- web_dir = Path(__file__).resolve().parents[1] / "src/stl_backend/web"
- self.gateway = WebGateway(self.bench.grpc_service, "127.0.0.1", 0, web_dir)
- await self.gateway.start()
- self.url = f"http://127.0.0.1:{self.gateway.server.sockets[0].getsockname()[1]}"
- async def asyncTearDown(self):
- await self.gateway.stop()
- await self.server.stop(0)
- await self.bench.grpc_service.drain()
- await self.bench.close()
- self.tmp.cleanup()
- async def test_static_and_missing_asset(self):
- status, headers, body = await asyncio.to_thread(http, self.url + "/")
- self.assertEqual(status, 200)
- self.assertIn("内存高温测试工作台", body.decode())
- self.assertIn("no-cache", headers["Cache-Control"])
- status, _, _ = await asyncio.to_thread(http, self.url + "/missing.js")
- self.assertEqual(status, 404)
- async def test_http_has_no_rpc_endpoint(self):
- status, _, _ = await asyncio.to_thread(
- http, self.url + "/stl.v1.BenchService/GetSystemInfo", "POST")
- self.assertEqual(status, 405)
- async def test_sibling_path_cannot_escape_static_directory(self):
- web = Path(self.tmp.name) / "web"
- sibling = Path(self.tmp.name) / "web-other"
- web.mkdir()
- sibling.mkdir()
- (sibling / "secret.txt").write_text("not static")
- self.gateway.web_dir = web
- status, _, _ = await asyncio.to_thread(http, self.url + "/../web-other/secret.txt")
- self.assertEqual(status, 404)
|