package main import ( "context" "testing" "time" ) func TestAuth_LoginWrongCode(t *testing.T) { m := StartMiniRedis(t) a := NewTestAuth(t, m, "rightcode", time.Hour) ok, err := a.Login(context.Background(), 42, "wrongcode") if err != nil { t.Fatalf("login err: %v", err) } if ok { t.Fatal("wrong code should fail") } authed, err := a.IsAuthed(context.Background(), 42) if err != nil || authed { t.Fatalf("user must NOT be authed after wrong code (authed=%v err=%v)", authed, err) } } func TestAuth_LoginRightCode_SetsTTL(t *testing.T) { m := StartMiniRedis(t) a := NewTestAuth(t, m, "rightcode", 30*time.Second) ok, err := a.Login(context.Background(), 7, "rightcode") if err != nil || !ok { t.Fatalf("login: ok=%v err=%v", ok, err) } authed, err := a.IsAuthed(context.Background(), 7) if err != nil || !authed { t.Fatalf("user must be authed after correct code (authed=%v err=%v)", authed, err) } rem, err := a.Remaining(context.Background(), 7) if err != nil { t.Fatalf("Remaining err: %v", err) } if rem <= 0 || rem > 30*time.Second { t.Fatalf("Remaining = %s, want (0, 30s]", rem) } } func TestAuth_Logout(t *testing.T) { m := StartMiniRedis(t) a := NewTestAuth(t, m, "code", time.Hour) if _, err := a.Login(context.Background(), 1, "code"); err != nil { t.Fatal(err) } if err := a.Logout(context.Background(), 1); err != nil { t.Fatalf("logout: %v", err) } authed, _ := a.IsAuthed(context.Background(), 1) if authed { t.Fatal("must NOT be authed after logout") } } func TestAuth_NewAuth_RequiresSecret(t *testing.T) { m := StartMiniRedis(t) if _, err := NewAuth("redis://"+m.Addr(), "", time.Hour); err == nil { t.Fatal("expected error when AUTH_SECRET is empty") } } func TestAuth_NilReceiver_Safe(t *testing.T) { var a *Auth authed, err := a.IsAuthed(context.Background(), 1) if err != nil || authed { t.Fatalf("nil Auth.IsAuthed must return (false,nil), got (%v,%v)", authed, err) } if err := a.Logout(context.Background(), 1); err != nil { t.Fatalf("nil Auth.Logout must be no-op, got: %v", err) } }