package ai import ( "context" "errors" "fmt" openai "github.com/sashabaranov/go-openai" "github.com/tradarr/backend/internal/models" "testing" ) type connectionRepo struct { p *models.AIProvider err error } func (r connectionRepo) GetAIProviderByID(string) (*models.AIProvider, error) { return r.p, r.err } type connectionKey struct{ err error } func (k connectionKey) Decrypt(s string) (string, error) { if s != "cipher" { panic("wrong cipher") } return "secret", k.err } type connectionProvider struct { err error calls int } func (*connectionProvider) Name() string { return "fake" } func (*connectionProvider) Summarize(context.Context, string, GenOptions) (string, error) { panic("must not generate") } func (p *connectionProvider) ListModels(context.Context) ([]string, error) { p.calls++ return []string{"private-model"}, p.err } func TestConnectionSavedCredentials(t *testing.T) { for _, tt := range []struct { name string upstream, want error }{ {"success", nil, nil}, {"auth", fmt.Errorf("wrapped: %w", &openai.APIError{HTTPStatusCode: 401}), ErrConnectionAuth}, {"forbidden", &openai.RequestError{HTTPStatusCode: 403}, ErrConnectionAuth}, {"rate limit", &openai.APIError{HTTPStatusCode: 429}, ErrConnectionUnavailable}, {"untrusted text", errors.New("401 secret endpoint"), ErrConnectionUnavailable}, } { t.Run(tt.name, func(t *testing.T) { p := &connectionProvider{err: tt.upstream} tester := NewConnectionTester(connectionRepo{p: &models.AIProvider{Name: "fake", APIKeyEncrypted: "cipher", Endpoint: "private"}}, connectionKey{}, func(name, key, endpoint string) (Provider, error) { if name != "fake" || key != "secret" || endpoint != "private" { t.Fatal("saved config not used") } return p, nil }) if got := tester.Test(context.Background(), "id"); !errors.Is(got, tt.want) { t.Fatalf("got %v want %v", got, tt.want) } if p.calls != 1 { t.Fatal("ListModels calls") } }) } } func TestConnectionLocalFailures(t *testing.T) { for _, tt := range []struct { name string repo connectionRepo key connectionKey buildErr, want error }{ {name: "missing", want: ErrConnectionNotFound}, {name: "database", repo: connectionRepo{err: errors.New("secret")}, want: ErrConnectionLocal}, {name: "decrypt", repo: connectionRepo{p: &models.AIProvider{APIKeyEncrypted: "cipher"}}, key: connectionKey{errors.New("secret")}, want: ErrConnectionLocal}, {name: "factory", repo: connectionRepo{p: &models.AIProvider{}}, buildErr: errors.New("secret"), want: ErrConnectionLocal}, } { t.Run(tt.name, func(t *testing.T) { tester := NewConnectionTester(tt.repo, tt.key, func(string, string, string) (Provider, error) { return nil, tt.buildErr }) if got := tester.Test(context.Background(), "id"); !errors.Is(got, tt.want) { t.Fatalf("got %v", got) } }) } }