68 lines
2.1 KiB
Go
68 lines
2.1 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/samcharles93/archie-core/internal/domain/access"
|
|
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
|
"github.com/samcharles93/archie-core/internal/domain/org"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
|
)
|
|
|
|
// recordingSaver stands in for the SaveSession upsert. rows is what the query
|
|
// reports as affected: 0 is the upsert matching no row, which is how the SQL
|
|
// refuses another org's session or another person's conversation.
|
|
type recordingSaver struct {
|
|
rows int64
|
|
params postgresdb.SaveSessionParams
|
|
calls int
|
|
}
|
|
|
|
func (r *recordingSaver) SaveSession(_ context.Context, p postgresdb.SaveSessionParams) (int64, error) {
|
|
r.calls++
|
|
r.params = p
|
|
return r.rows, nil
|
|
}
|
|
|
|
func TestSaveSession(t *testing.T) {
|
|
for _, tc := range []struct {
|
|
name string
|
|
platform string
|
|
org org.OrgID
|
|
rows int64
|
|
wantErr error
|
|
}{
|
|
{"a messaging chat creates its session", "telegram", "org-a", 1, nil},
|
|
{"a web conversation creates its session", "web", "org-a", 1, nil},
|
|
{"another org's session is refused by the upsert", "telegram", "org-b", 0, ErrSessionNotFound},
|
|
{"another person's thread is refused by the upsert", "web", "org-a", 0, ErrSessionNotFound},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
ctx := access.WithPrincipal(t.Context(), access.Principal{IdentityID: "alice"})
|
|
ctx = org.WithOrg(ctx, tc.org)
|
|
saved := &recordingSaver{rows: tc.rows}
|
|
sc := SessionContext{
|
|
SessionID: "session-1",
|
|
Source: messaging.SessionSource{Platform: tc.platform, ChannelID: "chat-1", ThreadID: "thread-1"},
|
|
CreatedAt: time.Unix(1, 0),
|
|
LastActiveAt: time.Unix(2, 0),
|
|
}
|
|
|
|
err := saveSession(ctx, saved, sc)
|
|
if !errors.Is(err, tc.wantErr) {
|
|
t.Fatalf("save err=%v want=%v", err, tc.wantErr)
|
|
}
|
|
if saved.calls != 1 {
|
|
t.Fatalf("writes=%d want=1", saved.calls)
|
|
}
|
|
if saved.params.Platform != tc.platform || saved.params.OrgID != string(tc.org) {
|
|
t.Fatalf("platform=%q org=%q want platform=%q org=%q",
|
|
saved.params.Platform, saved.params.OrgID, tc.platform, tc.org)
|
|
}
|
|
})
|
|
}
|
|
}
|