move_detect/server/tests/EventValidatorTest.php
유창욱 a203c42bf3 feat(zones): occupancy rule engine - lone-worker / capacity / dwell limits
Per-zone declarative safety rules, set in the zone editor and enforced on the
edge from the tracking the pipeline already does (no new geometry, no new model):

- min_workers (2인 1조): 0 < count < minimum sustained 30s -> lone_worker/HIGH.
  A solo worker in a buddy-rule zone is a compliance violation and a rescue-
  delay risk, so it outranks the other two.
- max_workers: count > limit sustained 10s -> overcapacity/WARNING.
- max_dwell_s: one track's continuous stay past the limit -> overstay/WARNING.
  A short detection dropout (<=5s grace) does NOT reset the dwell timer -
  without that, run_once's stale-track filter would quietly neuter every
  10-minute rule at real-world detection rates.

Edge: detectors/occupancy.py consumes Zone.rules; the engine flips the zone
detector's per-track membership into per-zone headcounts (stale tracks already
excluded), so counts always match what was actually detected this tick. Fired
states clear on condition recovery - re-alerts need a fresh violation, not a
cooldown expiry. Malformed rules_json keeps the zone's intrusion detection
alive and logs the rules as inactive (never fail dark).

Server: move_zones.rules_json (nullable JSON, migration included) validated
strictly in ZoneConfigController (bounds, min<=max, unknown keys rejected -
a silently dropped rule is one the operator believes is active). Delivered to
the edge unchanged via GET /api/config. EventValidator accepts the 3 new types.

UI: zone editor gains the three rule fields (dwell entered in minutes, wired
in seconds) and shows each zone's rules in its list row; the events console
and detail view now render every event type in Korean (wire codes fall back).

Verified: pytest 216 pass / PHPUnit 123 pass + real-render harness in Chrome
(editor save payload, list labels, console type labels).
2026-08-06 19:33:12 +09:00

89 lines
4.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Tests;
use App\Ingest\EventValidator;
use PHPUnit\Framework\TestCase;
final class EventValidatorTest extends TestCase
{
private function valid(): array {
return ['device_id' => 'pi-1', 'camera_id' => 'cam-1', 'event_type' => 'fall',
'severity' => 'high', 'occurred_at' => 1000.0, 'snapshots' => ['aGk=']];
}
public function testAcceptsValid(): void {
$r = EventValidator::validate($this->valid());
$this->assertTrue($r['ok'], implode(',', $r['errors']));
$this->assertSame('fall', $r['clean']['event_type']);
}
public function testRejectsOverlongIds(): void {
// An overlong id must be a 400 (invalid), not a MySQL 'Data too long' 500 that the edge
// then retries forever. Columns: device_id/camera_id VARCHAR(64), zone_id CHAR(32).
$long = $this->valid(); $long['device_id'] = str_repeat('x', 65);
$this->assertFalse(EventValidator::validate($long)['ok']);
$cam = $this->valid(); $cam['camera_id'] = str_repeat('y', 65);
$this->assertFalse(EventValidator::validate($cam)['ok']);
$zone = $this->valid(); $zone['zone_id'] = str_repeat('z', 33);
$this->assertFalse(EventValidator::validate($zone)['ok']);
// a normal-length id still passes
$ok = $this->valid(); $ok['device_id'] = str_repeat('x', 64);
$this->assertTrue(EventValidator::validate($ok)['ok']);
}
public function testAcceptsAndCleansEventUuid(): void {
$p = $this->valid(); $p['event_uuid'] = str_repeat('a', 32);
$r = EventValidator::validate($p);
$this->assertTrue($r['ok'], implode(',', $r['errors']));
$this->assertSame(str_repeat('a', 32), $r['clean']['event_uuid']);
// Optional: omitting it is valid and clean carries null (legacy edges send no uuid).
$none = EventValidator::validate($this->valid());
$this->assertTrue($none['ok']);
$this->assertNull($none['clean']['event_uuid']);
}
public function testRejectsMalformedEventUuid(): void {
foreach (['XYZ', str_repeat('a', 31), str_repeat('A', 32), 'g' . str_repeat('a', 31)] as $bad) {
$p = $this->valid(); $p['event_uuid'] = $bad;
$this->assertFalse(EventValidator::validate($p)['ok'], "uuid '$bad' must be rejected");
}
}
public function testRejectsUnknownEventType(): void {
$p = $this->valid(); $p['event_type'] = 'explode';
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testAcceptsOccupancyRuleEventTypes(): void {
foreach (['lone_worker', 'overcapacity', 'overstay'] as $type) {
$p = $this->valid(); $p['event_type'] = $type;
$this->assertTrue(EventValidator::validate($p)['ok'], "$type must be a known type");
}
}
public function testRejectsUnknownSeverity(): void {
$p = $this->valid(); $p['severity'] = 'ULTRA';
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testRejectsMissingRequired(): void {
$p = $this->valid(); unset($p['device_id']);
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testRejectsTooManySnapshots(): void {
$p = $this->valid(); $p['snapshots'] = ['a', 'b', 'c', 'd'];
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testRejectsNonNumericOccurredAt(): void {
$p = $this->valid(); $p['occurred_at'] = ['bad'];
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testRejectsNonStringDeviceId(): void {
$p = $this->valid(); $p['device_id'] = ['x'];
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testRejectsNonArraySnapshots(): void {
$p = $this->valid(); $p['snapshots'] = 'notarray';
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testRejectsNonStringSnapshotItem(): void {
$p = $this->valid(); $p['snapshots'] = [123];
$this->assertFalse(EventValidator::validate($p)['ok']);
}
public function testRejectsNonStringZoneId(): void {
$p = $this->valid(); $p['zone_id'] = ['z'];
$this->assertFalse(EventValidator::validate($p)['ok']);
}
}