package adminweb import ( "context" "errors" "testing" "time" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/dingtalkconfig" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/secretstore" "gitea.zheromiku.top/Weknora/dobotai-platform/internal/settings" ) type controlRepo struct { savedVerified bool savedRef string candidateRef string failedCode string } func (*controlRepo) ActiveDingTalkConfig(context.Context, string) (string, string, bool, error) { return "old", "old-ref", true, nil } func (r *controlRepo) CandidateDingTalkConfig(context.Context, string) (string, string, error) { return "new", r.candidateRef, nil } func (r *controlRepo) SaveDingTalkConfig(_ context.Context, _, _, ref string, verified bool) error { r.savedRef = ref r.savedVerified = verified r.candidateRef = ref return nil } func (r *controlRepo) MarkDingTalkCandidateFailed(_ context.Context, _, _, code string) error { r.failedCode = code return nil } func (*controlRepo) AdministratorCount(context.Context, string) (int, error) { return 1, nil } func (*controlRepo) ActiveBindings(context.Context, string) (map[string]settings.ResourceBinding, error) { return map[string]settings.ResourceBinding{}, nil } func (*controlRepo) CreateBootstrapChallenge(context.Context, string, string, time.Time) error { return nil } func (*controlRepo) ConfirmBootstrap(context.Context, string) error { return nil } type verifyOK struct{} func (verifyOK) Verify(context.Context, string, string) dingtalkconfig.Result { return dingtalkconfig.Result{OK: true, Code: "oauth_ok"} } type activatorStub struct { err error calls int } func (a *activatorStub) ActivateCandidate(context.Context) error { a.calls++; return a.err } func TestSaveCredentialsCreatesCandidateNotActive(t *testing.T) { secrets, err := secretstore.New(t.TempDir()) if err != nil { t.Fatal(err) } repo := &controlRepo{} service, err := NewControlService("tenant", repo, secrets, verifyOK{}) if err != nil { t.Fatal(err) } if err = service.SaveCredentials(context.Background(), "new", "secret"); err != nil { t.Fatal(err) } if repo.savedVerified { t.Fatal("candidate must not be active") } if repo.savedRef == "" || !secrets.Configured(repo.savedRef) { t.Fatalf("ref=%q", repo.savedRef) } } func TestActivateCandidateDelegatesAndMarksFailure(t *testing.T) { secrets, err := secretstore.New(t.TempDir()) if err != nil { t.Fatal(err) } repo := &controlRepo{candidateRef: "candidate-ref"} activator := &activatorStub{err: errors.New("candidate_start_failed_rolled_back")} service, err := NewControlService("tenant", repo, secrets, verifyOK{}) if err != nil { t.Fatal(err) } service.SetCandidateActivator(activator) if err = service.ActivateCandidate(context.Background()); err == nil { t.Fatal("expected failure") } if activator.calls != 1 || repo.failedCode != "activation_failed" { t.Fatalf("calls=%d code=%q", activator.calls, repo.failedCode) } }