You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS CodeBuild单元测试失败时不终止CodePipeline流程问题

解决方案:让单元测试失败时终止CodePipeline推进

核心问题分析

CodeBuild 只会在命令返回非零退出码时,标记当前阶段失败并停止 Pipeline 继续执行。你的单元测试脚本虽然打印了FAIL,但进程最终仍以退出码0(表示执行成功)结束,所以 CodeBuild 会继续执行后续命令。此外,测试脚本里还存在一处变量名错误,可能导致测试逻辑异常。


步骤1:修复单元测试脚本,返回正确的退出码

修改测试脚本,在测试失败时让 Node.js 进程返回非零退出码,同时修正变量名错误:

const Allsayings = require('./testAllsayings');
let testFailed = false;

function logPass(tName){
    console.log("PASS - " + tName);
}
function logFail(tName){
    console.log("FAIL - " + tName );
    testFailed = true;
}

// T01 - Search for a saying and succeed
let say01 = new Allsayings();
say01.addQuote("Everyone is looking for something.");
say01.addQuote("Let's try to figure this out together, so help me please");
// 修复变量名错误:aq01 → say01
let output01 = say01.findSaying("Not here");
if (output01.search("Before you embark") > -1){
    logPass("T01");
} else {
    logFail("T01");
}

// 根据测试结果设置进程退出码
if (testFailed) {
    process.exit(1); // 非零码表示测试失败
} else {
    process.exit(0); // 零码表示测试成功
}

如果有多个测试用例,可以维护一个失败计数器,跑完所有用例后再统一判断退出,这样能看到所有失败的用例信息。


步骤2:确保 CodeBuild 检测到失败并终止

你的现有 buildspec.yml 无需大幅修改,只要测试脚本返回非零退出码,CodeBuild 默认会终止当前阶段,进而停止整个 Pipeline。如果需要更严格的执行规则,可以在阶段开头添加 set -e(让 Shell 在任何命令失败时立即退出):

version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 16
    commands:
      - echo Installing
  pre_build:
    commands:
      - echo Installing source NPM dependencies.
      - cd serverSide
      - npm install
  build:
    commands:
      - set -e  # 开启严格模式:任何命令失败立即终止
      - echo Build started on `date`
      - npm install pm2@latest -g
      - ls
      - echo "for debugging ... starting test"
      - node testAllsayings.js  # 测试失败会返回非零码,触发终止
      - echo "test is successful ... "  # 只有测试成功才会执行到这里
  post_build:
    commands:
      - echo Build completed on `date`
artifacts:
  files:
    - '**/*'

验证效果

修改后重新触发 Pipeline,当单元测试失败时:

  1. 测试脚本会返回退出码1
  2. CodeBuild 会立即终止当前阶段,不会执行后续的echo "test is successful ..."和post_build步骤
  3. CodePipeline 会标记该阶段失败,停止向后续的 CodeDeploy 阶段推进

内容的提问来源于stack exchange,提问作者spock's-neurons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:55:54