# 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)) }