import { AuditService } from '../audit/audit.service'; import { IntegrationRequestError } from '../common/errors/integration-error'; import { JenkinsClient } from '../integrations/jenkins/jenkins.client'; import { DeployNotificationService } from '../notifications/wecom/deploy-notification.service'; import { ProjectSummary } from '../projects/project.types'; import { DeployExecutionService } from './deploy-execution.service'; import { DeployRunRepository } from './deploy-run.repository'; import { CreateDeployRunInput, DeployRunSummary } from './deploy-run.types'; describe('DeployExecutionService', () => { const project: ProjectSummary = { id: 'project_001', key: 'access-manage', name: 'access-manage', repositoryUrl: 'https://gitea.ops.mrzhan.top/my-project/access-manage.git', defaultBranch: 'develop', status: 'active', environments: [ { name: 'test', displayName: '测试环境', jenkinsJobPath: 'my-project-dev/test-access-manage-develop', releasePolicy: 'branch', refPattern: '^(develop|feature/.+|hotfix/.+)$', }, ], }; const input: CreateDeployRunInput = { projectKey: 'access-manage', environment: 'test', ref: 'develop', operator: 'ops-admin', }; function createRepository(): DeployRunRepository { return new DeployRunRepository( { get: jest.fn(() => false), } as never, {} as never, ); } function createService(options: { jenkinsHealth: ReturnType; notificationStatus: 'sent' | 'skipped'; queueId?: string; queueBuildNumber?: number; queueSearchBuildNumber?: number; jobBuildable?: boolean; jobInfoError?: Error; matchedBuildNumber?: number; buildResult?: 'SUCCESS' | 'FAILURE' | 'ABORTED' | 'UNSTABLE'; buildRunning?: boolean; buildTimestamp?: string; buildDurationMs?: number; logText?: string; }) { const repository = createRepository(); const audit = { record: jest.fn(), } satisfies Pick; const notification = { sendDeployRunEvent: jest.fn(() => Promise.resolve({ status: options.notificationStatus, channel: 'wecom' as const, reason: options.notificationStatus === 'skipped' ? 'Missing WECOM_WEBHOOK_URL' : undefined, }), ), } satisfies Pick; const jenkins = { healthSummary: jest.fn(() => options.jenkinsHealth), buildWithParameters: jest.fn(() => Promise.resolve({ queueId: options.queueId ?? 'queue_001', }), ), getJobInfo: jest.fn(() => { if (options.jobInfoError) { return Promise.reject(options.jobInfoError); } return Promise.resolve({ jobPath: 'my-project-dev/test-access-manage-develop', name: 'test-access-manage-develop', fullName: 'my-project-dev/test-access-manage-develop', url: 'https://jenkins.example/job/my-project-dev/job/test-access-manage-develop/', buildable: options.jobBuildable ?? true, }); }), getQueueItem: jest.fn((queueId: string) => Promise.resolve({ queueId, buildNumber: options.queueBuildNumber, executableUrl: options.queueBuildNumber ? `https://jenkins.example/job/${options.queueBuildNumber}/` : undefined, }), ), findBuildByQueueId: jest.fn((_jobPath: string, queueId: string) => Promise.resolve( options.queueSearchBuildNumber ? { jobPath: 'my-project-dev/test-access-manage-develop', buildNumber: options.queueSearchBuildNumber, building: options.buildRunning ?? false, result: options.buildResult, url: `https://jenkins.example/job/${options.queueSearchBuildNumber}/`, queueId, } : undefined, ), ), findLatestBuildByParameter: jest.fn((_jobPath: string, name: string) => Promise.resolve( options.matchedBuildNumber ? { jobPath: 'my-project-dev/test-access-manage-develop', buildNumber: options.matchedBuildNumber, building: options.buildRunning ?? false, result: options.buildResult, url: `https://jenkins.example/job/${options.matchedBuildNumber}/`, matchedParameterName: name, matchedParameterValue: 'run_001', } : undefined, ), ), getBuildStatus: jest.fn((_jobPath: string, buildNumber: number) => Promise.resolve({ jobPath: 'my-project-dev/test-access-manage-develop', buildNumber, building: options.buildRunning ?? false, result: options.buildResult, url: `https://jenkins.example/job/${buildNumber}/`, timestamp: options.buildTimestamp, durationMs: options.buildDurationMs, }), ), getProgressiveText: jest.fn(() => Promise.resolve({ text: options.logText ?? '', nextStart: options.logText?.length ?? 0, hasMore: false, }), ), } satisfies Pick< JenkinsClient, | 'healthSummary' | 'buildWithParameters' | 'getJobInfo' | 'getQueueItem' | 'findBuildByQueueId' | 'findLatestBuildByParameter' | 'getBuildStatus' | 'getProgressiveText' >; const service = new DeployExecutionService( repository, audit as unknown as AuditService, notification as unknown as DeployNotificationService, jenkins as unknown as JenkinsClient, ); return { audit, jenkins, notification, repository, service, }; } async function createRun( repository: DeployRunRepository, idempotencyKey: string, ): Promise { const result = await repository.create({ ...input, idempotencyKey, }); return result.run; } function step(run: DeployRunSummary, bpmnNodeId: string) { return run.steps.find((item) => item.bpmnNodeId === bpmnNodeId); } it('fails a release when Jenkins is not configured instead of dry-running success', async () => { const { audit, jenkins, repository, service } = createService({ jenkinsHealth: { status: 'not_configured', message: 'Missing JENKINS_API_TOKEN', }, notificationStatus: 'skipped', }); const run = await createRun(repository, 'run_dry_001'); const result = await service.execute(run, project); expect(result.status).toBe('failed'); expect(result.jenkinsQueueId).toBeUndefined(); expect(result.failureSummary).toContain('Jenkins 集成尚未配置'); expect(step(result, 'gitea-check')?.status).toBe('success'); expect(step(result, 'jenkins-build')?.status).toBe('failed'); expect(step(result, 'jenkins-build')?.errorSummary).toContain( 'Jenkins 集成尚未配置', ); expect(step(result, 'health-check')?.status).toBe('pending'); expect(step(result, 'notify-wecom')?.status).toBe('skipped'); expect(step(result, 'finish-release')?.status).toBe('pending'); expect(jenkins.buildWithParameters).not.toHaveBeenCalled(); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'DEPLOY_FAILED' }), ); }); it('fails before triggering when the configured Jenkins job is missing', async () => { const { jenkins, repository, service } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'skipped', jobInfoError: new IntegrationRequestError('jenkins', 'Jenkins 请求失败', { status: 404, }), }); const run = await createRun(repository, 'run_missing_job_001'); const result = await service.execute(run, project); expect(result.status).toBe('failed'); expect(result.failureSummary).toBe( 'Jenkins job 不存在:my-project-dev/test-access-manage-develop', ); expect(step(result, 'jenkins-build')?.status).toBe('failed'); expect(jenkins.buildWithParameters).not.toHaveBeenCalled(); }); it('triggers Jenkins and keeps the run queued until status polling completes', async () => { const { audit, jenkins, repository, service } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'sent', queueId: 'jenkins_queue_42', }); const run = await createRun(repository, 'run_queue_001'); const result = await service.execute(run, project); expect(result.status).toBe('queued'); expect(result.jenkinsQueueId).toBe('jenkins_queue_42'); expect(step(result, 'jenkins-build')?.status).toBe('queued'); expect(step(result, 'health-check')?.status).toBe('pending'); expect(step(result, 'notify-wecom')?.status).toBe('pending'); expect(jenkins.buildWithParameters).toHaveBeenCalledWith( 'my-project-dev/test-access-manage-develop', expect.objectContaining({ DEPLOY_RUN_ID: 'run_queue_001', DEPLOY_ENVIRONMENT: 'test', GIT_REF: 'develop', }), ); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'JENKINS_BUILD_TRIGGERED', after: expect.objectContaining({ queueId: 'jenkins_queue_42', }), }), ); expect(audit.record).not.toHaveBeenCalledWith( expect.objectContaining({ action: 'DEPLOY_SUCCEEDED' }), ); }); it('sends the selected tag through RELEASE_TAG for production tag jobs', async () => { const { repository, service, jenkins } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'sent', }); const tagProject: ProjectSummary = { ...project, environments: [ { ...project.environments[0], name: 'production', releasePolicy: 'tag', jenkinsJobPath: 'prod/access-manage-tag', }, ], }; const { run } = await repository.create({ ...input, environment: 'production', ref: 'v2026.10.28-stellar.1', idempotencyKey: 'tag-contract', }); await service.execute(run, tagProject); expect(jenkins.buildWithParameters).toHaveBeenCalledWith( 'prod/access-manage-tag', expect.objectContaining({ GIT_REF: 'v2026.10.28-stellar.1', RELEASE_TAG: 'v2026.10.28-stellar.1', }), ); }); it('passes an immutable historical commit through the real deployment workflow', async () => { const { repository, service, jenkins } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'sent', }); const { run } = await repository.create({ ...input, idempotencyKey: 'pinned-rollback', resolvedCommit: 'a'.repeat(40), operationKind: 'rollback', sourceRunId: 'historical-run', }); await service.execute(run, project); expect(jenkins.buildWithParameters).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ DEPLOY_COMMIT: 'a'.repeat(40) }), ); expect( (await repository.findByOperationKey('pinned-rollback'))?.resolvedCommit, ).toBe('a'.repeat(40)); }); it('syncs a queued Jenkins run to success', async () => { const { audit, repository, service } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'sent', queueId: 'queue_success', queueBuildNumber: 18, buildResult: 'SUCCESS', buildTimestamp: '2026-06-12T08:00:00.000Z', buildDurationMs: 90_000, }); const run = await service.execute( await createRun(repository, 'run_success_001'), project, ); const result = await service.syncJenkinsRun(run, project); expect(result.status).toBe('success'); expect(result.jenkinsBuildNumber).toBe(18); expect(result.finishedAt).toBe('2026-06-12T08:01:30.000Z'); expect(step(result, 'jenkins-build')?.status).toBe('success'); expect(step(result, 'health-check')?.status).toBe('success'); expect(step(result, 'notify-wecom')?.status).toBe('success'); expect(step(result, 'finish-release')?.status).toBe('success'); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'JENKINS_BUILD_STARTED' }), ); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'DEPLOY_SUCCEEDED' }), ); }); it('recovers a completed Jenkins result from the console log when build status has no result yet', async () => { const { audit, repository, service } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'sent', queueId: 'queue_log_success', queueBuildNumber: 22, logText: [ 'deploy ok', '[Pipeline] End of Pipeline', 'Finished: SUCCESS', ].join('\n'), }); const run = await service.execute( await createRun(repository, 'run_log_success_001'), project, ); const result = await service.syncJenkinsRun(run, project); expect(result.status).toBe('success'); expect(result.jenkinsBuildNumber).toBe(22); expect(step(result, 'jenkins-build')?.status).toBe('success'); expect(step(result, 'health-check')?.status).toBe('success'); expect(step(result, 'notify-wecom')?.status).toBe('success'); expect(step(result, 'finish-release')?.status).toBe('success'); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'JENKINS_BUILD_RESULT_RECOVERED_FROM_LOG', after: expect.objectContaining({ buildNumber: 22, result: 'SUCCESS', }), }), ); }); it('links a Jenkins build by queue id when the queue item has expired', async () => { const { audit, jenkins, repository, service } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'sent', queueId: 'queue_431', queueSearchBuildNumber: 19, buildResult: 'SUCCESS', }); const run = await service.execute( await createRun(repository, 'run_queue_search_001'), project, ); const result = await service.syncJenkinsRun(run, project); expect(result.status).toBe('success'); expect(result.jenkinsBuildNumber).toBe(19); expect(jenkins.findBuildByQueueId).toHaveBeenCalledWith( 'my-project-dev/test-access-manage-develop', 'queue_431', ); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'JENKINS_BUILD_LINKED' }), ); }); it('links an existing Jenkins build by DEPLOY_RUN_ID when the run has no build number', async () => { const { audit, jenkins, repository, service } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'sent', matchedBuildNumber: 21, buildResult: 'SUCCESS', }); const run = await createRun(repository, 'run_missing_build_001'); const result = await service.syncJenkinsRun(run, project); expect(result.status).toBe('success'); expect(result.jenkinsBuildNumber).toBe(21); expect(jenkins.findLatestBuildByParameter).toHaveBeenCalledWith( 'my-project-dev/test-access-manage-develop', 'DEPLOY_RUN_ID', 'run_missing_build_001', ); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'JENKINS_BUILD_LINKED' }), ); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'DEPLOY_SUCCEEDED' }), ); }); it('syncs a queued Jenkins run to failure with a log excerpt', async () => { const { audit, repository, service } = createService({ jenkinsHealth: { status: 'ok' }, notificationStatus: 'skipped', queueId: 'queue_failure', queueBuildNumber: 19, buildResult: 'FAILURE', logText: ['install ok', 'build failed', 'token=secret-value'].join('\n'), }); const run = await service.execute( await createRun(repository, 'run_failure_001'), project, ); const result = await service.syncJenkinsRun(run, project); expect(result.status).toBe('failed'); expect(result.failureSummary).toBe('Jenkins 构建 #19 FAILURE'); expect(step(result, 'jenkins-build')?.status).toBe('failed'); expect(step(result, 'jenkins-build')?.errorSummary).toBe( 'Jenkins 构建 #19 FAILURE', ); expect(step(result, 'jenkins-build')?.logExcerpt).toContain('build failed'); expect(step(result, 'notify-wecom')?.status).toBe('skipped'); expect(audit.record).toHaveBeenCalledWith( expect.objectContaining({ action: 'DEPLOY_FAILED' }), ); }); });