Introduction to Idempotent Test Listings for testthat: Global and Section Lists

Rafal Urniaz

2025-10-16

Overview

This vignette introduces two functions for generating roxygen-style listings of your testthat tests:

The listings are written as roxygen comments:

#' @testsList
#' @testsItem 1 alpha one
#' @testsItem 2 alpha two

#' @testsSection Section A
#' @testsItem 1 alpha one
#' @testsItem 2 alpha two

Why? Quick navigation and auditing of tests; machine- and human-readable structure that integrates with documentation tooling; and predictable, idempotent re-generation inside CI/CD.


Key Concepts

Sections

Markers and Items

Titles: Raw but Clean

The first argument to test_that() is recorded as raw code: - Literals like "alpha one" are kept without the outer quotesalpha one. - Expressions like paste("a", b) or glue::glue("{x}") are not evaluated and are listed unchanged.

Numbering Templates

Use placeholders to control numbering in both the global and section listings: - {g} — global index (1..N across all tests in the file) - {s} — section index (1..S) - {i} — local index within a section (1.. per section) - {l}final line number in the modified file (after insertion) - Aliases: {local}{i}, {line}{l}

Two presets: - template = "simple""{g}" - template = "advanced""{g}.{s}.{i}.{l}"

Override with global_fmt and section_fmt for full control.


document_file()

Arguments

Return Value

A list of class tests_listing_result with: - text: final modified lines (character vector). - listing: data frame with columns: - g, s, i, l (final line number), - title_raw (cleaned raw title), - section_title (if any). - written (logical), backup (path or NULL).

Example

library(testthatdocs)

res <- document_file(
  path = system.file("examples", "tests_sample_before.R", package="testthatdocs"),
  section_prefix = "# -",
  template = "advanced",   # or "simple"
  encoding = "UTF-8",
  backup = TRUE,
  write = TRUE
)

# Summary of tests 
res$listing

# Modified test file 
res$text

document()

Recursively processes a tree of test files (by default, tests/testthat).

library(testthatdocs)

all_res <- document(
  root = system.file("examples", package="testthatdocs"),
  template = "advanced",
  section_prefix = "# -",
  encoding = "UTF-8",
  backup = TRUE,
  write = TRUE,
  quiet = TRUE
)

# Combined table (with 'file' column)
all_res$listing

Arguments

Return Value

A list of class tests_listing_dir_result with: - files: processed file paths, - results: per-file tests_listing_result objects, - listing: combined table (adds a file column), - backups: vector of backup file paths (when write=TRUE).


Idempotency Guarantees


Edge Cases & Notes


Troubleshooting


Performance Tips


CI Integration

TBA


Reproducible Example

In sections # document_file() and # document()