package approvals import ( "errors" "path/filepath" "testing" "time" "supermarket/internal/db" ) func TestRequestsAndGrants(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() r := &Request{Agent: 5, Class: "post:2", Module: "content", Target: 11, Params: map[string]string{"at": "x"}, Summary: "Publish draft 11"} if err := Add(d, r, now); err != nil { t.Fatal(err) } if p, _ := Pending(d, "post:2", 11); p == nil || p.ID != r.ID { t.Error("not pending") } if err := Claim(d, r.ID, 1, Done, now); err != nil { t.Fatal(err) } if err := Claim(d, r.ID, 2, Refused, now); !errors.Is(err, ErrDecided) { t.Errorf("decided twice: %v", err) } Finish(d, r.ID, errors.New("X said no")) got, _ := Get(d, r.ID) if got.Status != Failed || got.Result != "X said no" || got.DecidedBy != 1 || got.Params["at"] != "x" || got.OnItsOwn() { t.Errorf("%+v", got) } if list, _ := List(d, Waiting, 0, 10); len(list) != 0 { t.Error("still waiting") } // On its own, with a cap of 2 a day. if ok, _ := Allowed(d, 5, "email-first", now); ok { t.Error("allowed without a grant") } Allow(d, Grant{Agent: 5, Class: "email-first", Label: "send a first email", Module: "prospects", DailyCap: 2, GrantedBy: 1}, now) for i := 0; i < 2; i++ { if ok, _ := Allowed(d, 5, "email-first", now); !ok { t.Fatalf("call %d refused", i) } Add(d, &Request{Agent: 5, Class: "email-first", Module: "prospects", Target: int64(i), Summary: "x", Status: Done}, now) } if ok, _ := Allowed(d, 5, "email-first", now); ok { t.Error("over the cap") } if ok, _ := Allowed(d, 5, "email-first", now.Add(25*time.Hour)); !ok { t.Error("the cap is per day") } if gs, _ := Grants(d, 5); len(gs) != 1 || gs[0].DailyCap != 2 { t.Errorf("grants %+v", gs) } WithdrawAll(d, 5) if ok, _ := Allowed(d, 5, "email-first", now.Add(25*time.Hour)); ok { t.Error("withdrawn") } }