Files
zenai-fpc/tests/test_dashboard.py

333 lines
13 KiB
Python

import json
import os
import shutil
import sqlite3
import tempfile
import unittest
import urllib.request
from io import BytesIO
from pathlib import Path
from unittest.mock import patch
from openpyxl import load_workbook
TEST_ROOT = Path(tempfile.mkdtemp(prefix="feedmill-dashboard-", dir="/tmp/opencode"))
os.environ["DB_PATH"] = str(TEST_ROOT / "import.db")
os.environ["STATE_FILE"] = str(TEST_ROOT / "import-state.json")
import counter_dashboard
from counter_control import start_control_server
class DashboardUnifiedBatchTests(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory(dir="/tmp/opencode")
self.root = Path(self.temp_dir.name)
self.db_path = self.root / "feedmill.db"
self.state_path = self.root / "current_batch.json"
counter_dashboard.DB_PATH = str(self.db_path)
counter_dashboard.CURRENT_BATCH_PATH = str(self.state_path)
counter_dashboard._ensure_db()
self.client = counter_dashboard.app.test_client()
def tearDown(self):
self.temp_dir.cleanup()
def seed_batch(self, counting_date, batch_number=1, sack_count=3, box_count=2, plate="B 1234 XYZ"):
conn = sqlite3.connect(self.db_path)
conn.execute(
"""
INSERT INTO batches
(counting_date, batch_number, camera_name, object_label, count,
sack_count, box_count, plate, start_time, end_time)
VALUES (?, ?, 'camera-a', 'mixed', ?, ?, ?, ?, ?, ?)
""",
(
counting_date,
batch_number,
sack_count + box_count,
sack_count,
box_count,
plate,
f"{counting_date}T08:00:00",
f"{counting_date}T08:10:00",
),
)
conn.execute(
"""
INSERT INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches,
sack_count, box_count)
VALUES (?, 'camera-a', 'mixed', ?, 1, ?, ?)
""",
(counting_date, sack_count + box_count, sack_count, box_count),
)
conn.commit()
conn.close()
def test_dashboard_renders_single_start_button_and_separate_counters(self):
html = self.client.get("/").get_data(as_text=True)
self.assertIn('id="btnBatchStart"', html)
self.assertNotIn('id="btnBatchStartSack"', html)
self.assertNotIn('id="btnBatchStartBox"', html)
self.assertIn('id="live-sack-count"', html)
self.assertIn('id="live-box-count"', html)
self.assertIn('id="live-plate"', html)
self.assertIn('id="today-sack-count"', html)
self.assertIn('id="today-box-count"', html)
self.assertIn('id="modalStopBatchSackCount"', html)
self.assertIn('id="modalStopBatchBoxCount"', html)
self.assertIn('id="modalStopBatchPlate"', html)
def test_daily_export_has_sack_and_box_columns(self):
counting_date = counter_dashboard.get_counting_date()
self.seed_batch(counting_date)
response = self.client.get("/api/export-daily-csv?days=30")
self.assertEqual(response.status_code, 200)
workbook = load_workbook(BytesIO(response.get_data()))
sheet = workbook.active
headers = [cell.value for cell in sheet[1]]
self.assertIn("Plate", headers)
self.assertIn("Sack", headers)
self.assertIn("Box", headers)
self.assertIn("Total", headers)
row = [cell.value for cell in sheet[2]]
self.assertEqual(row[headers.index("Plate")], "B 1234 XYZ")
self.assertEqual(row[headers.index("Sack")], 3)
self.assertEqual(row[headers.index("Box")], 2)
self.assertEqual(row[headers.index("Total")], 5)
def test_day_export_has_sack_and_box_columns(self):
counting_date = counter_dashboard.get_counting_date()
self.seed_batch(counting_date)
response = self.client.get(f"/api/export-day-csv/{counting_date}")
self.assertEqual(response.status_code, 200)
workbook = load_workbook(BytesIO(response.get_data()))
sheet = workbook.active
headers = [cell.value for cell in sheet[1]]
self.assertIn("Plate", headers)
self.assertIn("Sack", headers)
self.assertIn("Box", headers)
self.assertIn("Total", headers)
row = [cell.value for cell in sheet[2]]
self.assertEqual(row[headers.index("Plate")], "B 1234 XYZ")
self.assertEqual(row[headers.index("Sack")], 3)
self.assertEqual(row[headers.index("Box")], 2)
self.assertEqual(row[headers.index("Total")], 5)
def test_start_endpoint_sends_unified_start_command(self):
with patch(
"counter_dashboard._send_counter_command",
return_value=({"success": True, "batch_number": 1}, 200),
) as send:
response = self.client.post("/api/batch/start")
self.assertEqual(response.status_code, 200)
send.assert_called_once_with("start")
def test_legacy_start_routes_send_unified_start_command(self):
for path in ("/api/batch/start/sack", "/api/batch/start/box"):
with self.subTest(path=path):
with patch(
"counter_dashboard._send_counter_command",
return_value=({"success": True, "batch_number": 1}, 200),
) as send:
response = self.client.post(path)
self.assertEqual(response.status_code, 200)
send.assert_called_once_with("start")
def test_current_batch_returns_separate_counts(self):
self.state_path.write_text(
json.dumps(
{
"counting_date": counter_dashboard.get_counting_date(),
"batch_number": 4,
"object_label": "mixed",
"count": 5,
"sack_count": 3,
"box_count": 2,
"start_time": "2026-11-13T08:00:00",
"last_detection_time": "2026-11-13T08:01:00",
}
),
encoding="utf-8",
)
response = self.client.get("/api/current-batch")
data = response.get_json()
self.assertEqual(response.status_code, 200)
self.assertEqual(data["object_label"], "mixed")
self.assertEqual(data["count"], 5)
self.assertEqual(data["sack_count"], 3)
self.assertEqual(data["box_count"], 2)
def test_summary_returns_separate_today_totals(self):
counting_date = counter_dashboard.get_counting_date()
self.seed_batch(counting_date)
response = self.client.get("/api/summary")
data = response.get_json()
self.assertEqual(response.status_code, 200)
self.assertEqual(data["today"]["count"], 5)
self.assertEqual(data["today"]["sack_count"], 3)
self.assertEqual(data["today"]["box_count"], 2)
self.assertEqual(data["all_time"]["count"], 5)
self.assertEqual(data["all_time"]["sack_count"], 3)
self.assertEqual(data["all_time"]["box_count"], 2)
def test_batch_status_fallback_returns_separate_counts(self):
self.state_path.write_text(
json.dumps(
{
"counting_date": counter_dashboard.get_counting_date(),
"batch_number": 4,
"object_label": "mixed",
"count": 5,
"sack_count": 3,
"box_count": 2,
"start_time": "2026-11-13T08:00:00",
}
),
encoding="utf-8",
)
with patch(
"counter_dashboard.urllib.request.urlopen",
side_effect=OSError("control server offline"),
):
response = self.client.get("/api/batch/status")
data = response.get_json()
self.assertEqual(response.status_code, 200)
self.assertEqual(data["count"], 5)
self.assertEqual(data["sack_count"], 3)
self.assertEqual(data["box_count"], 2)
def test_day_detail_returns_separate_counts(self):
counting_date = counter_dashboard.get_counting_date()
self.seed_batch(counting_date)
response = self.client.get(f"/api/day-detail/{counting_date}")
data = response.get_json()
self.assertEqual(response.status_code, 200)
self.assertEqual(data["total_count"], 5)
self.assertEqual(data["sack_count"], 3)
self.assertEqual(data["box_count"], 2)
self.assertEqual(data["batches"][0]["sack_count"], 3)
self.assertEqual(data["batches"][0]["box_count"], 2)
self.assertEqual(data["batches"][0]["plate"], "B 1234 XYZ")
def test_recent_and_previous_batches_return_separate_counts(self):
counting_date = counter_dashboard.get_counting_date()
self.seed_batch(counting_date)
recent = self.client.get("/api/recent-batches").get_json()
previous = self.client.get("/api/previous-batch").get_json()
self.assertEqual(recent[0]["sack_count"], 3)
self.assertEqual(recent[0]["box_count"], 2)
self.assertEqual(recent[0]["plate"], "B 1234 XYZ")
self.assertEqual(previous["sack_count"], 3)
self.assertEqual(previous["box_count"], 2)
self.assertEqual(previous["plate"], "B 1234 XYZ")
def test_control_server_stop_returns_separate_counts(self):
class FakeStore:
def get_status(self):
return {
"active": True,
"batch_number": 7,
"object_label": "mixed",
"count": 5,
"sack_count": 3,
"box_count": 2,
}
def end_batch(self, closed_by="manual"):
return True
server = start_control_server(FakeStore(), port=0)
self.addCleanup(server.shutdown)
port = server.server_address[1]
request = urllib.request.Request(
f"http://127.0.0.1:{port}/stop", data=b"", method="POST"
)
with urllib.request.urlopen(request) as response:
data = json.loads(response.read().decode("utf-8"))
self.assertEqual(data["count"], 5)
self.assertEqual(data["sack_count"], 3)
self.assertEqual(data["box_count"], 2)
def test_control_server_start_aliases_create_one_mixed_batch(self):
class FakeStore:
def __init__(self):
self.calls = []
def get_status(self):
return {"active": False, "batch_number": None, "count": 0}
def start_new_batch(self, counting_date=None, object_label=None):
self.calls.append((counting_date, object_label))
return 7
store = FakeStore()
server = start_control_server(store, host="127.0.0.1", port=0)
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
port = server.server_address[1]
for path in ("/start/sack", "/start/box"):
request = urllib.request.Request(
f"http://127.0.0.1:{port}{path}",
data=b"{}",
method="POST",
headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request, timeout=2) as response:
self.assertEqual(response.status, 200)
self.assertEqual(store.calls, [(None, None), (None, None)])
def test_peer_sync_api_key_validation_and_body_forwarding(self):
with patch("counter_dashboard._get_peer_api_token", return_value="secret-token"):
bad = self.client.post(
"/api/batch/start",
headers={"X-API-Key": "wrong-token"},
json={"plate": "B 1234 XYZ"},
)
self.assertEqual(bad.status_code, 401)
self.assertFalse(bad.get_json()["success"])
with patch(
"counter_dashboard._send_counter_command",
return_value=({"success": True, "batch_number": 1}, 200),
) as send:
ok = self.client.post(
"/api/batch/start",
headers={"X-API-Key": "secret-token"},
json={"plate": "B 1234 XYZ", "source": "fcp-semarang"},
)
self.assertEqual(ok.status_code, 200)
self.assertEqual(send.call_count, 1)
self.assertEqual(send.call_args[0][0], "start")
self.assertIn(b"B 1234 XYZ", send.call_args[1]["data"])
def tearDownModule():
shutil.rmtree(TEST_ROOT, ignore_errors=True)
if __name__ == "__main__":
unittest.main()