package identity import ( "context" "errors" "testing" "time" ) type tokenFake struct { PersonalTokenStore token PersonalToken touched int } func (f *tokenFake) PersonalTokenOf(context.Context, Subject) (PersonalToken, error) { return f.token, nil } func (f *tokenFake) TouchPersonalToken(context.Context, Subject, time.Time) error { f.touched++ return nil } // TestUsePersonalToken pins that an expired token is refused and that last use // is written at most once a minute. func TestUsePersonalToken(t *testing.T) { now := time.Date(2026, 10, 27, 12, 0, 0, 0, time.UTC) at := func(d time.Duration) *time.Time { v := now.Add(d); return &v } tests := []struct { name string token PersonalToken wantErr error wantTouched int }{ {"valid", PersonalToken{ExpiresAt: at(time.Hour)}, nil, 1}, {"expired", PersonalToken{ExpiresAt: at(-time.Second)}, ErrNotFound, 0}, {"expires now", PersonalToken{ExpiresAt: at(0)}, ErrNotFound, 0}, {"no expiry", PersonalToken{}, nil, 1}, {"used seconds ago", PersonalToken{LastUsedAt: at(-10 * time.Second)}, nil, 0}, {"used minutes ago", PersonalToken{LastUsedAt: at(-2 * time.Minute)}, nil, 1}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { f := &tokenFake{token: tt.token} err := UsePersonalToken(context.Background(), f, Subject{}, now) if !errors.Is(err, tt.wantErr) || f.touched != tt.wantTouched { t.Fatalf("err %v touched %d, want %v and %d", err, f.touched, tt.wantErr, tt.wantTouched) } }) } }