package audit import ( "path/filepath" "testing" "time" "supermarket/internal/db" ) func TestRecordAndList(t *testing.T) { d, err := db.Open(filepath.Join(t.TempDir(), "app.db")) if err != nil { t.Fatal(err) } defer d.Close() now := time.Now() for _, e := range []Entry{ {At: now.Add(-400 * 24 * time.Hour), UserID: 1, UserName: "Olu", Action: "signin"}, {At: now.Add(-time.Hour), UserID: 1, UserName: "Olu", Action: "signin", IP: "203.0.113.1"}, {At: now.Add(-30 * time.Minute), UserID: 2, UserName: "Sam", Action: "signin-failed", Target: "sam@example.com"}, {At: now, UserID: 1, UserName: "Olu", Action: "invited", Target: "sam@example.com", Detail: "Member: SEO"}, {At: now, Kind: System, Action: "published", Target: "X @acme"}, } { if err := Record(d, e); err != nil { t.Fatal(err) } } all, _ := List(d, Filter{}, 10) if len(all) != 5 || all[0].Action != "published" || all[0].Kind != System || all[4].Kind != Person { t.Fatalf("all: %+v", all) } if l, _ := List(d, Filter{Action: "signin"}, 10); len(l) != 3 { t.Errorf("signin*: %d", len(l)) } if l, _ := List(d, Filter{UserID: 2}, 10); len(l) != 1 { t.Errorf("Sam: %d", len(l)) } if l, _ := List(d, Filter{Text: "SAM@"}, 10); len(l) != 2 { t.Errorf("text: %d", len(l)) } page2, _ := List(d, Filter{Before: all[1].ID}, 2) if len(page2) != 2 || page2[0].ID != all[2].ID { t.Errorf("paging: %+v", page2) } if n, _ := Prune(d, 365*24*time.Hour, now); n != 1 { t.Errorf("pruned %d", n) } }