Files
nano-fcp/tests/test_batch_store.py

312 lines
11 KiB
Python

import json
import sqlite3
import tempfile
import time
import unittest
from pathlib import Path
from unittest.mock import patch
import batch_store
class BatchStoreUnifiedBatchTests(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.TemporaryDirectory()
self.root = Path(self.temp_dir.name)
self.db_path = self.root / "feedmill.db"
self.state_path = self.root / "current_batch.json"
def tearDown(self):
self.temp_dir.cleanup()
def make_store(self):
return batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_mode="manual",
logger=lambda _message: None,
)
def test_mixed_batch_counts_sacks_and_boxes_separately(self):
store = self.make_store()
store.start_new_batch()
store.record_counted_object_crossing(1, object_label="sack")
store.record_counted_object_crossing(2, object_label="box")
status = store.get_status()
self.assertEqual(status["count"], 2)
self.assertEqual(status["sack_count"], 1)
self.assertEqual(status["box_count"], 1)
self.assertEqual(status["object_label"], "mixed")
store.db.close()
def test_same_track_id_counts_once_per_class(self):
store = self.make_store()
store.start_new_batch()
store.record_counted_object_crossing(7, object_label="sack")
store.record_counted_object_crossing(7, object_label="box")
status = store.get_status()
self.assertEqual(status["count"], 2)
self.assertEqual(status["sack_count"], 1)
self.assertEqual(status["box_count"], 1)
store.db.close()
def test_legacy_active_state_resumes_as_mixed_and_accepts_both_classes(self):
counting_date = "2026-11-13"
self.state_path.write_text(
json.dumps(
{
"counting_date": counting_date,
"batch_number": 4,
"object_label": "sack",
"count": 4,
"start_time": "2026-11-13T10:00:00",
"last_detection_time": "2026-11-13T10:01:00",
"counted_event_ids": ["1"],
}
),
encoding="utf-8",
)
with patch.object(
batch_store.BatchStore, "get_counting_date", return_value=counting_date
):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_mode="manual",
logger=lambda _message: None,
)
store.get_counting_date = lambda dt=None: counting_date
status = store.get_status()
self.assertEqual(status["object_label"], "mixed")
self.assertEqual(status["count"], 4)
self.assertEqual(status["sack_count"], 4)
self.assertEqual(status["box_count"], 0)
store.record_counted_object_crossing(2, object_label="box")
status = store.get_status()
self.assertEqual(status["count"], 5)
self.assertEqual(status["sack_count"], 4)
self.assertEqual(status["box_count"], 1)
store.db.close()
def test_legacy_database_rows_are_backfilled_without_changing_totals(self):
conn = sqlite3.connect(self.db_path)
conn.executescript(
"""
CREATE TABLE batches (
id INTEGER PRIMARY KEY AUTOINCREMENT,
counting_date TEXT NOT NULL,
batch_number INTEGER NOT NULL,
camera_name TEXT NOT NULL,
object_label TEXT NOT NULL,
count INTEGER NOT NULL,
start_time TEXT NOT NULL,
end_time TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(counting_date, batch_number, camera_name, object_label)
);
CREATE TABLE daily_summaries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
counting_date TEXT NOT NULL,
camera_name TEXT NOT NULL,
object_label TEXT NOT NULL,
total_count INTEGER NOT NULL DEFAULT 0,
total_batches INTEGER NOT NULL DEFAULT 0,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(counting_date, camera_name, object_label)
);
INSERT INTO batches
(counting_date, batch_number, camera_name, object_label, count, start_time, end_time)
VALUES
('2026-11-13', 1, 'camera-a', 'sack', 5, '2026-11-13T08:00:00', '2026-11-13T08:10:00');
INSERT INTO daily_summaries
(counting_date, camera_name, object_label, total_count, total_batches)
VALUES
('2026-11-13', 'camera-a', 'sack', 5, 1);
"""
)
conn.commit()
conn.close()
schema = getattr(batch_store, "ensure_batch_schema", None)
self.assertIsNotNone(schema, "ensure_batch_schema must exist")
conn = sqlite3.connect(self.db_path)
schema(conn)
row = conn.execute(
"SELECT total_count, sack_count, box_count FROM daily_summaries"
).fetchone()
conn.close()
self.assertEqual(row, (5, 5, 0))
def test_mixed_batch_persists_one_row_with_separate_counts(self):
store = self.make_store()
store.start_new_batch()
store.record_counted_object_crossing(1, object_label="sack")
store.record_counted_object_crossing(2, object_label="box")
self.assertTrue(store.end_batch(closed_by="manual"))
row = store.db.execute(
"""
SELECT object_label, count, sack_count, box_count
FROM batches
"""
).fetchone()
self.assertEqual(row, ("mixed", 2, 1, 1))
store.db.close()
def test_mixed_daily_summary_counts_batch_once(self):
store = self.make_store()
store.start_new_batch()
store.record_counted_object_crossing(1, object_label="sack")
store.record_counted_object_crossing(2, object_label="box")
store.end_batch(closed_by="manual")
row = store.db.execute(
"""
SELECT object_label, total_count, total_batches, sack_count, box_count
FROM daily_summaries
"""
).fetchone()
self.assertEqual(row, ("mixed", 2, 1, 1, 1))
store.db.close()
def test_empty_manual_batch_is_persisted(self):
store = self.make_store()
store.start_new_batch()
self.assertTrue(store.end_batch(closed_by="manual"))
batch_count = store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0]
summary_row = store.db.execute(
"SELECT total_count, total_batches, sack_count, box_count FROM daily_summaries"
).fetchone()
self.assertEqual(batch_count, 1)
self.assertEqual(summary_row, (0, 1, 0, 0))
store.db.close()
def test_morning_cutoff_0600_assigns_early_morning_to_previous_day(self):
from datetime import datetime
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="06:00",
batch_mode="manual",
logger=lambda _message: None,
)
self.assertEqual(
store.get_counting_date(datetime(2026, 11, 17, 5, 59, 59)),
"2026-11-16",
)
self.assertEqual(
store.get_counting_date(datetime(2026, 11, 17, 6, 0, 0)),
"2026-11-17",
)
self.assertEqual(
store.get_counting_date(datetime(2026, 11, 16, 21, 30, 0)),
"2026-11-16",
)
store.db.close()
def test_default_batch_timeout_is_30_seconds(self):
store = self.make_store()
self.addCleanup(store.db.close)
self.assertEqual(store.batch_timeout, 30.0)
def test_auto_mode_truck_present_prevents_timeout_until_truck_leaves(self):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_timeout=0.15,
min_object_per_batch=1,
min_duration_per_batch=0,
batch_mode="auto",
logger=lambda _message: None,
)
self.addCleanup(store.shutdown)
store.set_truck_present(True)
store.record_counted_object_crossing(1, object_label="sack")
time.sleep(0.25)
self.assertTrue(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 0
)
store.set_truck_present(False)
time.sleep(0.25)
self.assertFalse(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
)
def test_auto_mode_truck_entering_cancels_running_timeout(self):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_timeout=0.15,
min_object_per_batch=1,
min_duration_per_batch=0,
batch_mode="auto",
logger=lambda _message: None,
)
self.addCleanup(store.shutdown)
store.record_counted_object_crossing(1, object_label="sack")
time.sleep(0.05)
store.set_truck_present(True)
time.sleep(0.20)
self.assertTrue(store.get_status()["active"])
store.set_truck_present(False)
time.sleep(0.25)
self.assertFalse(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
)
def test_auto_mode_closes_after_timeout_when_no_truck(self):
store = batch_store.BatchStore(
db_path=self.db_path,
state_file=self.state_path,
camera_name="camera-a",
cutoff_time="23:59",
batch_timeout=0.15,
min_object_per_batch=1,
min_duration_per_batch=0,
batch_mode="auto",
logger=lambda _message: None,
)
self.addCleanup(store.shutdown)
store.record_counted_object_crossing(1, object_label="sack")
time.sleep(0.25)
self.assertFalse(store.get_status()["active"])
self.assertEqual(
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
)
if __name__ == "__main__":
unittest.main()