Files
archie/internal/gateway/session_tracker_org_test.go

68 lines
1.9 KiB
Go

package gateway
import (
"context"
"errors"
"testing"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// orgSessions stores sessions the way the real store does: a session id
// belongs to the org that first wrote it, and listings are per org.
type orgSessions struct {
SessionStore
owner map[string]org.OrgID
byID map[string]SessionContext
}
func (s *orgSessions) Save(ctx context.Context, sc SessionContext) error {
caller := org.OrgFromContext(ctx)
if owner, taken := s.owner[sc.SessionID]; taken && owner != caller {
return errors.New("session owned by another org")
}
s.owner[sc.SessionID], s.byID[sc.SessionID] = caller, sc
return nil
}
func (s *orgSessions) GetByChannel(ctx context.Context, _, channelID string) ([]SessionContext, error) {
var out []SessionContext
for id, sc := range s.byID {
if s.owner[id] == org.OrgFromContext(ctx) && sc.Source.ChannelID == channelID {
out = append(out, sc)
}
}
return out, nil
}
func (s *orgSessions) Touch(context.Context, string) error { return nil }
func TestTrackerKeepsOrgsChatsApart(t *testing.T) {
store := &orgSessions{owner: map[string]org.OrgID{}, byID: map[string]SessionContext{}}
tracker := newSessionTracker(store)
tests := []struct {
name string
owner org.OrgID
want string
}{
{"the system org keeps the bare chat id", org.DefaultOrgID, "42"},
{"another org gets its own session for the same chat", "acme", "@acme:42"},
{"a third org does too", "beta", "@beta:42"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctx := org.WithOrg(t.Context(), tt.owner)
got, err := tracker.resolve(ctx, "telegram", "bot", "42", "")
if err != nil {
t.Fatalf("resolve() error = %v", err)
}
if got != tt.want {
t.Fatalf("resolve() = %q, want %q", got, tt.want)
}
if again, _ := tracker.resolve(ctx, "telegram", "bot", "42", ""); again != got {
t.Fatalf("second resolve() = %q, want the cached %q", again, got)
}
})
}
}