Lesson 2 of 3 Automated Testing in Pipelines

Automating Unit Tests, Code Coverage and Health Checks from Exit Codes

A test that runs but whose result is ignored provides no protection. This lesson explains how CodeBuild publishes test and code coverage reports, how coverage thresholds are enforced, and how exit codes are used throughout AWS deployment tooling to decide whether a build, a deployment step or an application is healthy.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how CodeBuild report groups collect test and code coverage results.
  • Describe how to enforce a minimum code coverage level in a pipeline.
  • Explain how exit codes determine success in CodeBuild, CodeDeploy hooks, Systems Manager commands and container health checks.
  • Identify why a pipeline can pass despite failing tests and how to correct it.

Test Reports in CodeBuild

When a buildspec contains a reports section, CodeBuild reads the specified result files at the end of the build and publishes them to a report group. A report group holds the reports of many builds, so the console shows trends such as the pass rate and duration over time, and each report lists individual test cases with their status, duration and failure message. If a report group does not exist when the build runs, CodeBuild creates one named <project-name>-<report-name>; creating report groups explicitly in IaC allows their export to S3, their encryption key and their retention to be controlled.

Test report formats include JUnit XML (produced by most frameworks, including pytest, Jest with a reporter, Maven Surefire and Go tools), Cucumber JSON, TestNG XML, Visual Studio TRX, NUnit XML and NUnit3 XML. The service role needs codebuild:CreateReportGroup, codebuild:CreateReport, codebuild:UpdateReport and codebuild:BatchPutTestCases on the report group ARN.

Reports versus results

Publishing a report does not by itself fail the build. The build fails because the test command exits with a non-zero code when tests fail. Reports are for visibility; exit codes are for control.

Code Coverage

Code coverage measures how much of the code the tests execute. Line coverage is the percentage of lines executed, and branch coverage is the percentage of decision branches, such as both sides of an if statement, that were taken. Coverage does not prove that the code is correct, because a test can execute a line without checking its result, but low coverage reliably shows untested code.

CodeBuild publishes code coverage reports in JaCoCo XML, Cobertura XML, Clover XML, SimpleCov JSON and LCOV formats, using a report entry with the corresponding file-format. The report shows line and branch coverage per file and over time. CodeBuild does not itself fail a build for low coverage. A threshold is enforced by the test tool, for example pytest --cov-fail-under=80, Jest's coverageThreshold or the JaCoCo Maven plugin's check goal, which exits with a non-zero code when coverage is below the threshold and therefore fails the build.

phases:
  build:
    commands:
      # Exits non-zero if any test fails or total coverage is below 80 percent
      - pytest --junitxml=reports/junit.xml --cov=orders --cov-report=xml:reports/coverage.xml --cov-fail-under=80
reports:
  orders-unit:
    files: [junit.xml]
    base-directory: reports
    file-format: JUNITXML
  orders-coverage:
    files: [coverage.xml]
    base-directory: reports
    file-format: COBERTURAXML

Exit Codes as the Universal Health Signal

By convention, a process that finishes successfully exits with code 0, and any other code indicates failure. AWS deployment tooling relies on this convention everywhere, which is why the exam guide asks you to measure application health based on exit codes. The places where exit codes decide outcomes are described below.

CodeBuild commands

Every command in a buildspec phase must exit with 0. A non-zero exit fails the phase and the build, and a failed build fails the CodePipeline action. This is why a test framework's exit code is enough to stop a pipeline.

CodeDeploy lifecycle hook scripts

Scripts listed in the AppSpec file for hooks such as ApplicationStart and ValidateService run on the instance through the CodeDeploy agent. A non-zero exit, or a script that exceeds its timeout, fails the lifecycle event and the deployment on that instance, which can trigger automatic rollback. A ValidateService script that calls the application's health endpoint and exits non-zero on failure is the standard way to verify an in-place deployment.

Systems Manager Run Command and Automation

A Run Command invocation records each instance's exit code. A non-zero exit marks that invocation Failed, and error and concurrency thresholds decide whether the command continues on other instances. Specific exit codes also ask the SSM Agent to reboot the instance and then rerun the script: 3010 on Windows and 194 on Linux, which is used by patching and configuration scripts.

Container health checks

An ECS task definition can define a container health check command, for example CMD-SHELL, curl -f http://localhost:8080/health || exit 1. Exit code 0 means healthy and 1 means unhealthy. After the configured number of retries fails, ECS marks the container unhealthy; if the container is essential, the task is stopped and the service replaces it. Separately, when an essential container's process exits, ECS stops the whole task, and the stopped reason and exit code appear in the task details, which is the first place to look when tasks keep restarting. Kubernetes liveness and readiness probes with exec commands use exit codes in the same way.

The table below summarises where exit codes are evaluated and what a failure causes.

WhereWho evaluatesEffect of a non-zero exit
Buildspec commandCodeBuildPhase and build fail; the pipeline action fails
AppSpec hook scriptCodeDeploy agentLifecycle event fails; deployment fails and can roll back
Run Command scriptSSM AgentInvocation fails; thresholds may stop the command
Container health checkECS agent or kubeletContainer marked unhealthy; task or pod replaced
Essential container processECSTask stops; service starts a replacement

Why Pipelines Sometimes Pass Despite Failing Tests

A pipeline that stays green while tests fail almost always discards an exit code. Common causes are piping a test command into another command such as tee, where the shell returns the exit code of the last command in the pipe; appending || true to keep a build running; running tests in a script that does not propagate failures; and setting on-failure: CONTINUE without checking the result afterwards. In bash, set -o pipefail makes a pipeline return the first non-zero exit code. Reviewing the buildspec for these patterns is the first troubleshooting step.

Spot the bug

A build that never fails

Exam skills 1.2.3 · 1.2.4

Find the three lines that let this build pass with failing tests or low coverage.

Log in to try this activity Interactive activities are free with an account.
Worked example

Enforcing a Quality Gate

A team's pipeline must fail if any unit test fails or line coverage falls below 80%, and test trends must be visible to the team. Today the buildspec runs npm test | tee test.log, and the pipeline has passed with failing tests.

The pipe into tee hides the test exit code, so the first change is to add set -o pipefail or remove the pipe. The Jest configuration sets a coverageThreshold of 80 for lines, so Jest exits non-zero below the threshold. The buildspec adds a JUnit reporter output as a JUNITXML report and the coverage output as a COBERTURAXML report, giving the team trends in the report group. No CodeBuild setting is needed to enforce the gate, because the exit code already does so.

Check yourself

An ECS service's tasks repeatedly start and stop, and the target group shows no healthy targets. Where should an engineer look first to see why the containers stop?

Show answer

At the stopped tasks' stopped reason and the containers' exit codes in the ECS console or DescribeTasks output, together with the container logs in CloudWatch Logs. An essential container exiting or failing its health check stops the task.

Exam Tips

Remember for the exam

  • Test and coverage reports provide visibility; the test command's non-zero exit code is what fails the build.
  • CodeBuild does not enforce coverage thresholds itself; configure the test tool to exit non-zero below the threshold (for example --cov-fail-under).
  • A non-zero exit from an AppSpec hook script (such as ValidateService) fails the CodeDeploy deployment and can trigger automatic rollback.
  • ECS container health checks use exit code 0 for healthy; an unhealthy or exited essential container stops the task.
  • Pipes, || true and on-failure: CONTINUE can hide failing tests; use set -o pipefail.