R packages
CI/CD
GxP
Testing series · part 7

Coverage and tests as evidence

Measure code coverage with {covr}, generate test evidence in CI, and trace requirements for regulated work

Use covr to spot untested paths, export Cobertura and JUnit XML in CI, and build automated requirement traceability matrices.
Published

2026-09-27

Modified

2026-09-27

The problem: line coverage is not tested behaviour

Earlier posts in this series covered testthat essentials, fixtures and mocking, snapshots, Shiny modules, browser tests, and property testing.

As a test suite expands, two questions emerge: how much code is tested, and how do we prove to reviewers that software meets its requirements?

The common metric is code coverage: the percentage of lines executed during tests. But equating line execution with verified behaviour is a mistake.

A line can execute without an assertion evaluating its correctness:

calculate_pfs <- function(event, days) {
  # Dummy function: event argument is unused to demonstrate unverified logic
  if (is.na(event) || is.na(days)) return(NA_real_)
  if (days < 0) stop("Days cannot be negative", call. = FALSE)
  days / 30.4375
}

# Touches lines without verifying output
res <- calculate_pfs(1, 60)
testthat::expect_true(TRUE)

In a coverage report, every statement in the main path turns green. Yet the test asserts nothing about the result: if the formula broke, the test would still pass.

This reflects Goodhart’s law: mandating a coverage threshold nudges developers toward superficial tests without real assertions.

Coverage is a diagnostic signal, not a quality target:

  • Low coverage provides a dependable negative signal, locating code paths and functions tests never touch.
  • High coverage provides no proof of correctness: it confirms statements ran, not that boundary cases, error branches, or calculations are right.

Producing reliable evidence requires both coverage metrics to spot untested gaps and traceable tests that link automated expectations directly to functional requirements.

The web-repo way: thresholds, V8 profiling, and machine-readable reports

Web repositories integrate coverage into CI through engine profilers and standardized formats.

Instrumentation versus engine profiling: Istanbul and c8

Historically, Istanbul (nyc) injected counter variables into source files, adding runtime overhead.

Modern runners like Vitest and Jest support native V8 coverage (via @vitest/coverage-v8 or Jest’s built-in V8 provider). The engine tracks bytecode execution ranges directly across four dimensions: lines, statements, functions, and branches (if/else paths and fallbacks).

Enforcing coverage gates in configuration

Projects enforce coverage gates in configuration. In Vitest (vitest.config.ts), teams set aggregate thresholds or enforce per-file rules:

import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    coverage: {
      provider: "v8",
      reporter: ["text", "json", "cobertura"],
      thresholds: {
        lines: 80,
        functions: 80,
        branches: 75,
        statements: 80,
        perFile: true,
      },
    },
  },
});

Setting perFile: true prevents well-tested helpers from masking untested critical business logic. CI workflows export JUnit XML for test status and Cobertura XML for coverage, rendering them into pull request dashboards.

The R way: measuring coverage with {covr}

{covr} is the standard framework for measuring R code coverage. Available on CRAN and documented on covr.r-lib.org, {covr} uses source references (srcrefs) to trace statement evaluation during tests.

Core coverage functions

{covr} provides functions for different scopes:

  • covr::package_coverage(path = "."): Standard entry point; installs the package to a temporary library and tracks evaluated expressions.
  • covr::file_coverage(source_files, test_files): Evaluates standalone scripts against test files.
  • covr::code_coverage(source_code, test_code): Evaluates coverage directly from code strings.
  • covr::environment_coverage(env, test_files): Measures functions defined in a specific environment.

Inspecting coverage results locally

In interactive development, three functions assess test thoroughness:

cov <- covr::package_coverage()

# Return aggregate percentage as numeric(1)
covr::percent_coverage(cov)

# Return data frame of locations with no test execution
covr::zero_coverage(cov)

# Open interactive HTML report highlighting covered and uncovered lines
covr::report(cov)

covr::percent_coverage(cov) returns the total percentage as a number.

covr::zero_coverage(cov) returns a data frame with columns filename, functions, line, and value, isolating statements that never ran. In RStudio, it also populates the Markers pane.

covr::report(cov) renders an interactive HTML document with source lines colored by execution count (browse defaults to interactive()).

Detecting coverage execution

When test behaviour must adjust during coverage runs (such as skipping long benchmarks), {covr} sets the environment variable R_COVR. The helper covr::in_covr() returns TRUE during coverage:

testthat::test_that("expensive benchmark runs only during standard passes", {
  testthat::skip_if(covr::in_covr(), "Skipping benchmark during coverage")
})

Running coverage in continuous integration

Continuous integration provides reproducible coverage measurement on every pull request. The canonical GitHub Actions workflow maintained by r-lib/actions (examples/test-coverage.yaml) demonstrates the modern pattern:

- uses: r-lib/actions/setup-r-dependencies@v2
  with:
    extra-packages: any::covr, any::xml2
    needs: coverage

- name: Test coverage
  run: |
    cov <- covr::package_coverage(
      quiet = FALSE,
      clean = FALSE,
      install_path = file.path(normalizePath(Sys.getenv("RUNNER_TEMP"), winslash = "/"), "package")
    )
    print(cov)
    covr::to_cobertura(cov)
  shell: Rscript {0}

- uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7
  with:
    fail_ci_if_error: ${{ github.event_name != 'pull_request' || secrets.CODECOV_TOKEN }}
    files: ./cobertura.xml
    plugins: noop
    disable_search: true
    token: ${{ secrets.CODECOV_TOKEN }}

This workflow decouples calculation from upload: R runs covr::package_coverage(...), exports XML via covr::to_cobertura(cov) (using {xml2}), and hands ./cobertura.xml to codecov/codecov-action. The official r-lib/actions template pins actions by immutable commit SHA for supply-chain security.

Tests as evidence: requirements and traceability

In regulated work, including clinical reporting and GxP applications, verifying software requires showing that intended functionality meets documented requirements. A passing test suite is meaningful evidence only if each test ties back to a specific requirement.

Naming tests with requirement identifiers

The simplest way to establish requirement traceability is to embed requirement identifiers directly into test descriptions:

derive_age_years <- function(days) {
  if (!is.numeric(days)) stop("days must be numeric", call. = FALSE)
  as.integer(floor(days / 365.25))
}

derive_study_day <- function(target_date, ref_date) {
  diff <- as.integer(as.Date(target_date) - as.Date(ref_date))
  ifelse(diff >= 0L, diff + 1L, diff)
}

testthat::test_that("REQ-01: derive_age_years converts days to complete years", {
  testthat::expect_equal(derive_age_years(731), 2L)
  testthat::expect_error(derive_age_years("731"), "days must be numeric")
})

testthat::test_that("REQ-02: derive_study_day computes 1-based day without day 0", {
  ref <- "2026-09-27"
  testthat::expect_equal(derive_study_day("2026-09-27", ref), 1L)
  testthat::expect_equal(derive_study_day("2026-09-28", ref), 2L)
  testthat::expect_equal(derive_study_day("2026-09-26", ref), -1L)
})

Identifiers such as REQ-01 and REQ-02 allow automated tooling to parse test results and construct a traceability matrix without maintaining error-prone manual spreadsheets.

Building a traceability matrix from test results

testthat::test_local() and testthat::test_file() return a testthat_results object. Calling as.data.frame() exposes structured test execution data:

test_file <- tempfile(fileext = ".R")
writeLines(
  c(
    "test_that(\"REQ-01: derive_age_years converts days\", { expect_equal(2L, 2L) })",
    "test_that(\"REQ-02: derive_study_day computes 1-based day\", { expect_equal(1L, 1L) })"
  ),
  test_file
)

df <- as.data.frame(testthat::test_file(test_file, reporter = "silent"))
has_req <- grepl("^REQ-[0-9]+:", df$test)

trace_table <- data.frame(
  requirement_id = ifelse(has_req, sub(":.*$", "", df$test), NA_character_),
  description = ifelse(has_req, trimws(sub("^[^:]+:[[:space:]]*", "", df$test)), df$test),
  test_file = basename(df$file),
  passed_expectations = df$passed,
  status = ifelse(
    df$skipped,
    "SKIPPED",
    ifelse(df$failed == 0 & !df$error, "PASS", "FAIL")
  ),
  stringsAsFactors = FALSE
)

testthat::expect_equal(nrow(trace_table), 2L)
testthat::expect_true(all(trace_table$status == "PASS"))

Tracking skipped tests as SKIPPED is vital for audit evidence: in testthat_results, a skipped test has failed = 0 and error = FALSE. Without checking df$skipped, unexecuted tests would falsely register as PASS. This tabular view maps each requirement to its test file, pass/fail status, and expectation count, producing verification output directly from code execution.

Recording results in CI with JUnit XML

To record test evidence in CI, configure testthat to write standard JUnit XML. testthat::JunitReporter formats test results into XML compatible with CI dashboards:

xml_output <- file.path("inst", "test-evidence", "test-results.xml")
dir.create(dirname(xml_output), recursive = TRUE, showWarnings = FALSE)

reporter <- testthat::MultiReporter$new(list(
  testthat::SummaryReporter$new(),
  testthat::JunitReporter$new(file = xml_output)
))

testthat::test_local(reporter = reporter, stop_on_failure = FALSE)

testthat::MultiReporter allows simultaneous console reporting via SummaryReporter and machine-readable persistence via JunitReporter.

Preserving provenance: results, commits, and lockfiles

Evidence is only as dependable as its provenance: a report claiming tests passed has little value without the exact code and dependency versions that generated it.

In an automated CI pipeline:

  1. Test and coverage results (test-results.xml, cobertura.xml) are saved as build artifacts.
  2. The Git commit SHA identifies the exact code that generated the evidence.
  3. The renv.lock lockfile records the version, source, and hash of R and every dependency.

Preserving these three artifacts together provides reproducible evidence: any auditor or team member can check out the exact commit, restore the identical dependency environment with renv::restore(), and re-execute the test suite.

Honest GxP framing: risk-based qualification, not pre-approved software

In regulated environments, developers sometimes claim that an open-source package is certified or pre-approved for regulatory submissions. Such claims misunderstand regulatory guidance.

As articulated in the R Validation Hub white paper (A Risk-based Approach for Assessing R package Accuracy within a Validated Infrastructure, Nicholls et al., pharmar.org):

  • Software is never globally certified: Regulatory agencies (such as the FDA) do not approve third-party software packages in the abstract. Validation is the responsibility of the sponsoring organization, conducted for a specific intended use within a specific configured environment.
  • Qualification versus validation: Individual packages are qualified by gathering objective evidence of stability, testing quality, and numerical accuracy. The complete computerized system (incorporating hardware, the operating system, R, supporting packages, and analytical programs) is validated for its operational workflow.
  • Risk-based testing: Scrutiny should match operational risk. Base R and recommended packages undergo extensive peer review and testing by the R Core Team. Specialized packages require proportional testing: unit assertions verifying intended use cases, boundary evaluations, and comparison against known reference values.

Automated unit tests and code coverage reports do not magically validate an application. Instead, they provide objective, verifiable evidence that designated requirements were executed and confirmed within a controlled environment.

Companion code

View coverage-demo.R · Download

Builds a throwaway R package containing two clinical derivation functions, measures coverage before and after adding a missing test, and writes both a requirement-to-test traceability matrix and JUnit XML output. Requires {covr}, {testthat}, {usethis} and {withr}. Running it (Rscript coverage-demo.R) shows the workflow:

  1. Initial coverage check: Evaluates coverage with covr::package_coverage(), finding derive_study_day() untested (60.0% coverage).
  2. Identifying missing paths: Calls covr::zero_coverage() to locate unreached lines in R/derivations.R.
  3. Closing coverage gaps: Adds a test for REQ-02 checking study days (with no day 0 convention), reaching 100% coverage.
  4. Generating auditable evidence: Runs tests via testthat::MultiReporter, writing JUnit XML and outputting the traceability table mapping requirements to passing tests.

The script’s operations are tested in the repository suite, confirming coverage numbers and traceability tables reflect real execution.

# Coverage measurement and requirement-to-test evidence:
# builds a throwaway package with two clinical derivation functions,
# measures initial coverage where one function lacks tests, identifies
# uncovered lines, adds the missing test, confirms complete coverage,
# and constructs a requirement-to-test traceability matrix alongside
# JUnit XML results.
#
#   Rscript coverage-demo.R

demo_files <- list(
  "NAMESPACE" = c(
    "export(derive_age_years)",
    "export(derive_study_day)"
  ),
  "R/derivations.R" = c(
    "#' Derive age in completed years",
    "#' @param days Number of days elapsed since birth.",
    "#' @return Integer age in years.",
    "#' @export",
    "derive_age_years <- function(days) {",
    "  if (!is.numeric(days)) {",
    "    stop(\"days must be numeric\", call. = FALSE)",
    "  }",
    "  as.integer(floor(days / 365.25))",
    "}",
    "",
    "#' Derive study day from reference date (1-based, no day 0)",
    "#' @param target_date Target assessment date.",
    "#' @param ref_date Reference date (typically study baseline / day 1).",
    "#' @return Integer study day.",
    "#' @export",
    "derive_study_day <- function(target_date, ref_date) {",
    "  diff <- as.integer(as.Date(target_date) - as.Date(ref_date))",
    "  ifelse(diff >= 0L, diff + 1L, diff)",
    "}"
  ),
  "tests/testthat/test-derivations.R" = c(
    "test_that(\"REQ-01: derive_age_years converts days to completed years\", {",
    "  expect_equal(derive_age_years(731), 2L)",
    "})",
    "",
    "test_that(\"REQ-01: derive_age_years rejects non-numeric input\", {",
    "  expect_error(derive_age_years(\"731\"), \"days must be numeric\")",
    "})"
  )
)

make_demo_package <- function(path = file.path(tempdir(), "covdemo")) {
  withr::local_options(usethis.quiet = TRUE)
  usethis::create_package(path, rstudio = FALSE, open = FALSE)
  usethis::with_project(path, {
    usethis::use_testthat(3)
  })
  for (rel_path in names(demo_files)) {
    full_path <- file.path(path, rel_path)
    dir.create(dirname(full_path), recursive = TRUE, showWarnings = FALSE)
    writeLines(demo_files[[rel_path]], full_path)
  }
  path
}

measure_coverage <- function(path) {
  covr::package_coverage(path)
}

coverage_percent <- function(cov) {
  covr::percent_coverage(cov)
}

uncovered_locations <- function(cov) {
  covr::zero_coverage(cov)
}

add_study_day_test <- function(path) {
  test_file <- file.path(path, "tests", "testthat", "test-derivations.R")
  existing <- readLines(test_file)
  new_test <- c(
    "",
    "test_that(\"REQ-02: derive_study_day computes 1-based day without day 0\", {",
    "  ref <- \"2026-09-27\"",
    "  expect_equal(derive_study_day(\"2026-09-27\", ref), 1L)",
    "  expect_equal(derive_study_day(\"2026-09-28\", ref), 2L)",
    "  expect_equal(derive_study_day(\"2026-09-26\", ref), -1L)",
    "})"
  )
  writeLines(c(existing, new_test), test_file)
}

run_package_tests <- function(path, reporter = "silent", xml_file = NULL) {
  rep <- if (!is.null(xml_file)) {
    testthat::MultiReporter$new(list(
      testthat::SummaryReporter$new(),
      testthat::JunitReporter$new(file = xml_file)
    ))
  } else {
    reporter
  }
  testthat::test_local(path, reporter = rep, stop_on_failure = FALSE)
}

build_traceability <- function(test_results) {
  df <- as.data.frame(test_results)
  has_req <- grepl("^REQ-[0-9]+:", df$test)
  req_id <- ifelse(has_req, sub(":.*$", "", df$test), NA_character_)
  req_desc <- ifelse(
    has_req,
    trimws(sub("^[^:]+:[[:space:]]*", "", df$test)),
    df$test
  )
  status <- ifelse(
    df$skipped,
    "SKIPPED",
    ifelse(df$failed == 0 & !df$error, "PASS", "FAIL")
  )

  data.frame(
    requirement_id = req_id,
    description = req_desc,
    test_file = basename(df$file),
    passed_expectations = df$passed,
    status = status,
    stringsAsFactors = FALSE
  )
}

if (sys.nframe() == 0L) {
  pkg_path <- make_demo_package()
  message("Measuring initial package coverage (derive_study_day uncovered)...")
  cov_initial <- measure_coverage(pkg_path)
  pct_initial <- coverage_percent(cov_initial)
  message(sprintf("Initial coverage: %.1f%%", pct_initial))

  zero_locs <- uncovered_locations(cov_initial)
  message("Uncovered code locations:")
  print(zero_locs[, c("filename", "functions", "line")])

  message("\nAdding test for REQ-02 (derive_study_day)...")
  add_study_day_test(pkg_path)

  cov_updated <- measure_coverage(pkg_path)
  pct_updated <- coverage_percent(cov_updated)
  message(sprintf("Updated coverage: %.1f%%", pct_updated))

  message("\nExecuting test suite and writing JUnit XML evidence...")
  xml_path <- file.path(pkg_path, "test-results.xml")
  results <- run_package_tests(pkg_path, xml_file = xml_path)

  message("\nRequirement-to-test traceability matrix:")
  trace_matrix <- build_traceability(results)
  print(trace_matrix)

  message(sprintf("\nJUnit XML written to: %s", xml_path))
}

Sources

Package documentation

Standards and CI references

Web-repo comparison

NoteUpdates
  • 2026-09-27: Added a Companion code section with the full script.