package store import ( "net/netip" "testing" "time" ) func kinds(evs []Event) []EventKind { var out []EventKind for _, e := range evs { if e.Kind != EventScan { out = append(out, e.Kind) } } return out } func equal(a, b []EventKind) bool { if len(a) != len(b) { return false } for i := range a { if a[i] != b[i] { return false } } return true } func TestObserve(t *testing.T) { dir := t.TempDir() s, err := Open(dir) if err != nil { t.Fatal(err) } all := func(netip.Addr) bool { return true } a := Sighting{Key: "aa:aa:aa:aa:aa:aa", IP: "10.0.0.2", MAC: "aa:aa:aa:aa:aa:aa"} b := Sighting{Key: "bb:bb:bb:bb:bb:bb", IP: "10.0.0.3", MAC: "bb:bb:bb:bb:bb:bb", Hostname: "phone"} c := Sighting{Key: "cc:cc:cc:cc:cc:cc", IP: "10.0.0.4"} t0 := time.Now() at := func(i int) time.Time { return t0.Add(time.Duration(i) * time.Minute) } steps := []struct { seen []Sighting want []EventKind }{ {[]Sighting{a, b}, nil}, // first run ever: no "new" flood {[]Sighting{a, b, c}, []EventKind{EventNew}}, // c is new {[]Sighting{a, c}, nil}, // b missed once: not gone yet {[]Sighting{a, c}, []EventKind{EventLeave}}, // b missed twice: gone {[]Sighting{a, c}, nil}, // no repeated leave {[]Sighting{a, b, c}, []EventKind{EventJoin}}, } for i, st := range steps { evs, err := s.Observe(at(i), st.seen, all) if err != nil { t.Fatal(err) } if got := kinds(evs); !equal(got, st.want) { t.Errorf("step %d: events %v, want %v", i, got, st.want) } } // Tracking marks leave/join events for notification. if err := s.Update(b.Key, func(d *Device) { d.Tracked, d.Name = true, "Anna's iPhone" }); err != nil { t.Fatal(err) } s.Observe(at(10), []Sighting{a, c}, all) evs, _ := s.Observe(at(11), []Sighting{a, c}, all) if len(kinds(evs)) != 1 || !evs[0].Notify || evs[0].Label != "Anna's iPhone" { t.Errorf("tracked leave = %+v", evs) } // Out-of-scope devices are not reported as gone. s.Observe(at(12), []Sighting{a, c}, all) none := func(netip.Addr) bool { return false } s.Observe(at(13), nil, none) if evs, _ := s.Observe(at(14), nil, none); len(kinds(evs)) != 0 { t.Errorf("out of scope events %v", kinds(evs)) } // Everything survives a reload. s2, err := Open(dir) if err != nil { t.Fatal(err) } d, ok := s2.Device(b.Key) if !ok || d.Name != "Anna's iPhone" || !d.Tracked || d.Hostname != "phone" { t.Errorf("reloaded device = %+v", d) } if got := len(s2.Events(t0.Add(-time.Hour))); got != len(s.Events(t0.Add(-time.Hour))) || got == 0 { t.Errorf("reloaded %d events", got) } }