fix bounding box in tracking mode
This commit is contained in:
parent
48140f0f77
commit
a617d40777
13 changed files with 392 additions and 16 deletions
|
|
@ -12,13 +12,50 @@ Then tell stratoflights to use it:
|
|||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Optional: serve a canned prediction (stratoflights Prediction dump / Tawhiri
|
||||
# JSON) instead of synthesizing one. Point datetimes are shifted so the
|
||||
# trajectory starts at the requested launch_datetime.
|
||||
TRAJ_FILE = os.environ.get("FAKE_TAWHIRI_TRAJECTORY")
|
||||
|
||||
|
||||
def _iso(dt: datetime) -> str:
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def _parse(dt: str) -> datetime:
|
||||
return datetime.fromisoformat(dt.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
def build_from_file(params):
|
||||
d = json.load(open(TRAJ_FILE))
|
||||
res = d.get("result") or d
|
||||
stages = copy.deepcopy(res["prediction"])
|
||||
try:
|
||||
launch_dt = _parse(params.get("launch_datetime"))
|
||||
except Exception:
|
||||
launch_dt = datetime.now(timezone.utc)
|
||||
t0 = _parse(stages[0]["trajectory"][0]["datetime"])
|
||||
delta = launch_dt - t0
|
||||
last = None
|
||||
for stage in stages:
|
||||
for p in stage["trajectory"]:
|
||||
p["datetime"] = _iso(_parse(p["datetime"]) + delta)
|
||||
last = p
|
||||
return {
|
||||
"metadata": {
|
||||
"start_datetime": _iso(launch_dt - timedelta(hours=1)),
|
||||
"complete_datetime": last["datetime"],
|
||||
},
|
||||
"prediction": stages,
|
||||
"request": res.get("request", {}),
|
||||
}
|
||||
|
||||
|
||||
def build_prediction(params):
|
||||
try:
|
||||
launch_dt = datetime.fromisoformat(
|
||||
|
|
@ -81,11 +118,15 @@ def build_prediction(params):
|
|||
class Handler(BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
parsed = urlparse(self.path)
|
||||
if not parsed.path.rstrip("/").endswith("/api/v2"):
|
||||
path = parsed.path.rstrip("/")
|
||||
# /api/v2 — legacy e2e endpoint; /api/v1/prediction — what
|
||||
# stratoflights' TawhiriClient (Go predictor URL) actually calls.
|
||||
if not (path.endswith("/api/v2") or path.endswith("/api/v1/prediction")):
|
||||
self.send_error(404)
|
||||
return
|
||||
params = {k: v[0] for k, v in parse_qs(parsed.query).items()}
|
||||
body = json.dumps(build_prediction(params)).encode()
|
||||
builder = build_from_file if TRAJ_FILE else build_prediction
|
||||
body = json.dumps(builder(params)).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
|
|
@ -98,7 +139,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||
|
||||
|
||||
if __name__ == "__main__":
|
||||
port = 8001
|
||||
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8001
|
||||
server = HTTPServer(("127.0.0.1", port), Handler)
|
||||
print(f"fake-tawhiri listening on http://127.0.0.1:{port}/api/v2/")
|
||||
src = f"file {TRAJ_FILE}" if TRAJ_FILE else "synthetic"
|
||||
print(f"fake-tawhiri listening on http://127.0.0.1:{port}/ ({src})")
|
||||
server.serve_forever()
|
||||
|
|
|
|||
64
tests/e2e/track.spec.ts
Normal file
64
tests/e2e/track.spec.ts
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
import { test, expect, openPredict, login } from './fixtures';
|
||||
|
||||
test.beforeEach(async ({ context, page }) => {
|
||||
await login(context);
|
||||
await page.goto('/');
|
||||
await page.evaluate(() => localStorage.removeItem('workspaces'));
|
||||
});
|
||||
|
||||
/** Count map layers whose scoped id belongs to a bounding-box scene. */
|
||||
function bboxLayerCount(page: import('@playwright/test').Page) {
|
||||
return page.evaluate(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const map: any = (window as any)._lsvMap;
|
||||
if (!map) return 0;
|
||||
return map.getStyle().layers.filter((l: { id: string }) => l.id.startsWith('bbox')).length;
|
||||
});
|
||||
}
|
||||
|
||||
// Regression: the bounding box is drawn only by WorkspaceRenderer (predict-only).
|
||||
// Selecting the same forecast on /track must redraw its box, otherwise it
|
||||
// "disappears" the moment the user switches into tracking mode.
|
||||
test('selected forecast bounding box is drawn on the tracking page', async ({ page }) => {
|
||||
test.setTimeout(90_000);
|
||||
await openPredict(page);
|
||||
|
||||
const panel = page.locator('.panel-container-right');
|
||||
const runBtn = panel
|
||||
.locator('.workspace-row')
|
||||
.first()
|
||||
.getByRole('button', { name: /Рассчитать|Run/ });
|
||||
await runBtn.click();
|
||||
|
||||
// Wait for the run to complete (workspace scene appears).
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
page.evaluate(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const map: any = (window as any)._lsvMap;
|
||||
if (!map) return 0;
|
||||
return map
|
||||
.getStyle()
|
||||
.layers.filter((l: { id: string }) => l.id.startsWith('ws/')).length;
|
||||
}),
|
||||
{ timeout: 75_000, intervals: [1000, 2000, 3000] },
|
||||
)
|
||||
.toBeGreaterThan(0);
|
||||
|
||||
// Enable the bounding box for this forecast.
|
||||
await panel.getByRole('button', { name: /Построить рамку|Generate bounding box/ }).click();
|
||||
await expect.poll(() => bboxLayerCount(page), { timeout: 10_000 }).toBeGreaterThan(0);
|
||||
|
||||
// Client-side navigate to tracking (a full reload would drop the in-memory
|
||||
// prediction result, which is intentionally not persisted).
|
||||
await page.getByRole('link', { name: /Слежение|Track/ }).click();
|
||||
await page
|
||||
.locator('.map-container canvas')
|
||||
.first()
|
||||
.waitFor({ state: 'attached', timeout: 15_000 });
|
||||
|
||||
// Select the forecast to track against — its box must appear on this map.
|
||||
await page.locator('#forecast-select').selectOption({ index: 1 });
|
||||
await expect.poll(() => bboxLayerCount(page), { timeout: 10_000 }).toBeGreaterThan(0);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue