package store_test import ( "context" "testing" "time" "atlas9.dev/c/core" "atlas9.dev/c/core/assert" "atlas9.dev/c/core/dbi" "atlas9.dev/c/core/iam" "atlas9.dev/c/demo/store" ) func testSessionStore(t *testing.T, ctx context.Context, setup func(t *testing.T) iam.SessionStore) { t.Run("Save and Get", func(t *testing.T) { s := setup(t) exp := time.Now().UTC().Truncate(time.Second).Add(time.Hour) sess := &iam.Session{ Token: "tok-abc", Principal: core.NewID("t"), Expiration: exp, } assert.Ok(t, s.Save(ctx, sess)) var got iam.Session assert.Ok(t, s.Get(ctx, "tok-abc", &got)) assert.Eq(t, got.Token, "tok-abc") assert.Eq(t, got.Principal, sess.Principal) assert.Eq(t, got.Expiration.UTC(), exp) }) t.Run("Save upserts", func(t *testing.T) { s := setup(t) principal1 := core.NewID("t") principal2 := core.NewID("t") exp := time.Now().UTC().Truncate(time.Second).Add(time.Hour) assert.Ok(t, s.Save(ctx, &iam.Session{Token: "tok-upsert", Principal: principal1, Expiration: exp})) assert.Ok(t, s.Save(ctx, &iam.Session{Token: "tok-upsert", Principal: principal2, Expiration: exp})) var got iam.Session assert.Ok(t, s.Get(ctx, "tok-upsert", &got)) assert.Eq(t, got.Principal, principal2) }) t.Run("Get not found", func(t *testing.T) { s := setup(t) var got iam.Session err := s.Get(ctx, "nonexistent", &got) assert.Eq(t, err, core.ErrNotFound) }) t.Run("Delete", func(t *testing.T) { s := setup(t) exp := time.Now().UTC().Truncate(time.Second).Add(time.Hour) assert.Ok(t, s.Save(ctx, &iam.Session{Token: "tok-del", Principal: core.NewID("t"), Expiration: exp})) assert.Ok(t, s.Delete(ctx, "tok-del")) var got iam.Session err := s.Get(ctx, "tok-del", &got) assert.Eq(t, err, core.ErrNotFound) }) t.Run("Delete nonexistent is no-op", func(t *testing.T) { s := setup(t) assert.Ok(t, s.Delete(ctx, "nonexistent")) }) } func TestSqliteSessionStore(t *testing.T) { db := setupTestDB(t) tx, err := db.Begin() assert.Ok(t, err) t.Cleanup(func() { tx.Rollback() }) w := dbi.WrapTx(tx) ctx := t.Context() testSessionStore(t, ctx, func(t *testing.T) iam.SessionStore { return store.NewSqliteSessionStore(w) }, ) }