Property-based testing in R
Find edge cases example-based tests miss with generative testing and shrinking
The problem
In the first post in this series, we wrote unit tests with explicit expectations. For a function, we typically pick a normal input, a boundary case, and perhaps an NA.
Consider a function that categorises patient ages into clinical reporting groups:
classify_age <- function(age) {
dplyr::case_when(
is.na(age) ~ NA_character_,
age < 18 ~ "< 18",
age >= 18 & age < 65 ~ "18-64",
age >= 65 ~ ">= 65"
)
}A standard test suite checks it against hand-picked values:
test_that("classify_age() categorises hand-picked examples", {
expect_identical(classify_age(10), "< 18")
expect_identical(classify_age(30), "18-64")
expect_identical(classify_age(70), ">= 65")
})These assertions pass. But example-based tests only cover cases you thought to write down: if a developer wrote age > 18 & age < 65 instead of age >= 18 & age < 65, this suite still passes, because nobody tested 18 exactly. The same blind spot hides off-by-one boundaries, extreme inputs, and silent NAs.
Property-based testing inverts the relationship: instead of specific inputs and expected outputs, you define universal properties that must hold for any valid input, and let a generator search for counterexamples.
The web-repo way
In web development and systems programming, property-based testing goes back to Haskell’s QuickCheck (Claessen and Hughes, 2000) and is now widely used:
- Python: Hypothesis generates data, detects edge cases, and shrinks failures to minimal examples.
- JavaScript and TypeScript: fast-check tests API boundaries and state machines across generated inputs:
import fc from "fast-check";
import { formatAgeGroup } from "./format";
fc.assert(
fc.property(fc.integer({ min: 0, max: 120 }), (age) =>
["< 18", "18-64", ">= 65"].includes(formatAgeGroup(age))
)
);Web repositories rely on this for parsers, serializers, and business rules where bad input could cause silent corruption or crashes.
The R way
In R, {quickcheck} (built on {hedgehog}) integrates property-based testing directly with {testthat}.
Properties versus examples
An example test asserts one concrete value (“when age is 30, the result is '18-64'”). A property test asserts a universal truth across the whole domain: “for any non-missing integer age from 0 to 100, the result is never missing and always in c('< 18', '18-64', '>= 65').”
Generators: defining input domains
{quickcheck} provides composable generators for specific types and shapes, inspectable via quickcheck::show_example():
library(quickcheck)
# Inspect generated values
set.seed(42)
quickcheck::show_example(quickcheck::integer_bounded(0L, 100L))
quickcheck::show_example(quickcheck::character_alphanumeric())Used later in this post:
| Generator | Data produced | Key arguments |
|---|---|---|
integer_() |
Integer vectors | len = c(1L, 10L), any_na = FALSE |
integer_bounded() |
Bounded integer vectors | left, right, len = c(1L, 10L) |
double_bounded() |
Bounded double vectors | left, right, len = c(1L, 10L) |
data_frame_() |
Data frames from column generators | ..., rows = c(1L, 10L) |
{quickcheck} also exports numeric_(), character_(), factor_(), and tibble_() for other shapes.
Evaluating properties with quickcheck::for_all()
The workhorse of {quickcheck} is for_all(), connecting generators to an expectation function:
quickcheck::for_all(
...,
property,
tests = getOption("quickcheck.tests", 100L),
shrinks = getOption("quickcheck.shrinks", 100L),
discards = getOption("quickcheck.discards", 100L)
)By default, for_all() runs 100 iterations, drawing samples from the named generators and passing them to property; if an expectation fails, {quickcheck} stops and begins shrinking.
Evaluated across the generated inputs:
test_that("classify_age() produces valid categories for any valid age", {
allowed_levels <- c("< 18", "18-64", ">= 65")
withr::local_seed(42)
quickcheck::for_all(
age = quickcheck::integer_bounded(0L, 100L),
property = function(age) {
res <- classify_age(age)
expect_true(all(!is.na(res)))
expect_true(all(res %in% allowed_levels))
}
)
})Because classify_age() handles every boundary, all 100 iterations pass quietly.
Shrinking: finding the minimal counterexample
Suppose a developer writes classify_age_buggy(), accidentally using age > 18 instead of age >= 18:
classify_age_buggy <- function(age) {
dplyr::case_when(
is.na(age) ~ NA_character_,
age < 18 ~ "< 18",
age > 18 & age < 65 ~ "18-64", # Planted edge-case bug: misses age == 18
age >= 65 ~ ">= 65"
)
}A generator produces a multi-element vector each run; when one element is 18, buried among noise, the property fails without saying which value mattered.
Shrinking answers that: {quickcheck} delegates to {hedgehog}, which retries smaller inputs — shorter vectors, numbers pulled toward 0 — until only the smallest failing input remains.
Running for_all() against classify_age_buggy(), the property fails and shrinks:
test_that("the property detects the missing boundary condition at age 18", {
withr::local_seed(42)
expect_failure(
quickcheck::for_all(
age = quickcheck::integer_bounded(0L, 100L),
property = function(age) {
res <- classify_age_buggy(age)
expect_true(all(!is.na(res)))
}
)
)
})Evaluated directly without expect_failure(), the report highlights the exact shrunk counterexample:
Error: Falsifiable after 36 tests, and 9 shrinks
<expectation_failure/expectation/error/condition>
Expected `all(!is.na(res))` to be TRUE.
Differences:
`actual`: FALSE
`expected`: TRUE
Counterexample:
$age
[1] 18
36 test iterations turned up an input containing 18; 9 shrink steps then stripped away every unrelated number and element until only that boundary value remained — the exact input that broke the logic, instead of an unwieldy failure log.
Four properties worth testing
Four recurring patterns cover most data processing and package functions:
1 · Invariants (structural properties)
Invariants must hold for any valid input — a standard deviation is never negative, deriving a column never changes the row count, categorisation never leaves the controlled domain:
test_that("square root maintains non-negativity", {
quickcheck::for_all(
x = quickcheck::double_bounded(0, 1000),
property = function(x) {
s <- sqrt(x)
expect_equal(length(s), length(x))
expect_true(all(s >= 0))
},
tests = 25L
)
})2 · Round trips (symmetry)
Convert data to another format and back, and you should recover the original value:
test_that("integer to character round-trips identically", {
quickcheck::for_all(
x = quickcheck::integer_(),
property = function(x) {
expect_identical(as.integer(as.character(x)), x)
},
tests = 25L
)
})Round-trip properties suit serializers, date-time formatters, and encoder-decoder pipelines.
3 · Idempotence (stability under repetition)
An idempotent operation gives the same result applied once or many times (f(f(x)) == f(x)):
test_that("sorting is idempotent", {
quickcheck::for_all(
x = quickcheck::integer_(),
property = function(x) {
expect_identical(sort(sort(x)), sort(x))
},
tests = 25L
)
})Idempotence suits data cleaning, string trimming, and deduplication routines.
4 · Reference implementation comparison (oracle testing)
When you rewrite a function for speed, verify it against a trusted reference implementation — here, base R’s cut(), run against both integer and double ages:
reference_age <- function(age) {
as.character(cut(
age,
breaks = c(-Inf, 18, 65, Inf),
right = FALSE,
labels = c("< 18", "18-64", ">= 65")
))
}
check_reference <- function(age) expect_identical(classify_age(age), reference_age(age))
test_that("classify_age() matches reference cut() implementation", {
quickcheck::for_all(age = quickcheck::integer_bounded(0L, 100L), property = check_reference, tests = 25L)
quickcheck::for_all(age = quickcheck::double_bounded(0, 100), property = check_reference, tests = 25L)
})Even a slower, less readable reference gives high confidence when your optimized code matches it across many random inputs.
Derivation invariants in clinical data
In clinical reporting (ADaM derivations), errors here can silently corrupt downstream tables, listings, and figures (TFLs). Property-based testing verifies derivation functions systematically.
Consider a derivation that appends an age group column (AGEGR1) to a clinical data frame:
derive_age_group <- function(data, age_col = "AGE", new_col = "AGEGR1") {
if (!is.data.frame(data)) {
stop("`data` must be a data frame.", call. = FALSE)
}
if (!age_col %in% names(data)) {
stop(sprintf("Column `%s` not found in `data`.", age_col), call. = FALSE)
}
data[[new_col]] <- classify_age(data[[age_col]])
data
}This derivation must satisfy three properties: row preservation (no rows added or dropped, even on empty or single-row data frames), missingness preservation (a non-missing AGE never yields a missing AGEGR1), and controlled terminology (derived values match the allowed study protocol levels).
We can express these as a property test using quickcheck::data_frame_():
test_that("derive_age_group() preserves rows and missingness across random data frames", {
allowed_levels <- c("< 18", "18-64", ">= 65")
quickcheck::for_all(
df = quickcheck::data_frame_(
AGE = quickcheck::integer_bounded(0L, 100L, any_na = FALSE),
rows = c(0L, 20L)
),
property = function(df) {
res <- derive_age_group(df)
expect_equal(nrow(res), nrow(df))
expect_equal(is.na(res$AGEGR1), is.na(df$AGE))
expect_true(all(res$AGEGR1 %in% allowed_levels))
},
tests = 25L
)
})We can also verify the derivation on real CDISC data from {pharmaverseadam}. This runs over every subject in ADSL, not just the safety population (SAFFL == "Y"), since row and missingness preservation are properties of the derivation, not of a particular analysis subset:
test_that("derive_age_group() processes clinical adsl dataset cleanly", {
data <- pharmaverseadam::adsl
res <- derive_age_group(data)
expect_equal(nrow(res), nrow(data))
expect_false(any(is.na(res$AGEGR1)))
expect_true(all(res$AGEGR1 %in% c("< 18", "18-64", ">= 65")))
expect_equal(sum(res$AGEGR1 == "18-64"), 42)
expect_equal(sum(res$AGEGR1 == ">= 65"), 264)
})Limitations, performance, and reproducibility
Property-based testing finds defects example-based tests miss, but it has trade-offs:
1 · Execution time
Running 100 iterations per property adds up across a large suite. for_all()’s tests argument defaults to getOption("quickcheck.tests", 100L); a project can lower it locally and raise it in CI by setting the option once, e.g. in a tests/testthat/setup.R file:
options(quickcheck.tests = 20L)Save property tests for core transformations and parsers, not trivial getters.
2 · Generator design
A property test is only as good as its generator: one producing only positive integers will never surface issues with negative numbers or NA. Realistic, constrained clinical generators take deliberate thought.
3 · Randomness and reproducibility
Because {quickcheck} generates random values on each run, an unseeded test could pass locally yet fail in CI on a rare combination.
To keep test runs deterministic:
- Set seeds with
withr::local_seed(): As in the previous post’s fixtures, prefer it over bareset.seed()insidetest_that()blocks — it restores the prior RNG state on exit, so one test’s seed can’t leak into the next. - Turn counterexamples into permanent unit tests: Whenever a property test catches a bug, take the shrunk counterexample (such as
18L) and write it as an explicitexpect_identical()test. This preserves the regression check even if generator settings change later.
Companion code
View property-demo.R · Download
Runs a planted boundary bug in clinical age grouping, demonstrates the failing property test with its shrunk counterexample, and validates the corrected derivation. Its properties are themselves tested, including that the property fails on the buggy function. Requires {quickcheck}, {testthat} and {dplyr}.
property-demo.R
# Property-based testing demo: detects an edge-case boundary bug in clinical age grouping
# using quickcheck::for_all() and shrinks the failing input to the minimal counterexample.
#
# Run with:
# Rscript property-demo.R
library(quickcheck)
library(testthat)
#' Classify age into standard clinical categories (buggy version)
#'
#' @param age Numeric or integer vector of patient ages.
#' @return Character vector with categories "< 18", "18-64", or ">= 65".
classify_age_buggy <- function(age) {
dplyr::case_when(
is.na(age) ~ NA_character_,
age < 18 ~ "< 18",
age > 18 & age < 65 ~ "18-64", # Planted edge-case bug: strict > drops age == 18
age >= 65 ~ ">= 65"
)
}
#' Classify age into standard clinical categories (fixed version)
#'
#' @param age Numeric or integer vector of patient ages.
#' @return Character vector with categories "< 18", "18-64", or ">= 65".
classify_age_fixed <- function(age) {
dplyr::case_when(
is.na(age) ~ NA_character_,
age < 18 ~ "< 18",
age >= 18 & age < 65 ~ "18-64",
age >= 65 ~ ">= 65"
)
}
#' Derive age group in an ADaM-style dataset
#'
#' @param data A data frame containing patient records.
#' @param age_col Name of the numeric age column (default "AGE").
#' @param new_col Name of the derived column to create (default "AGEGR1").
#' @param classify Classification function to use (default classify_age_fixed).
#' @return Data frame with the derived age group column appended.
derive_age_group <- function(
data,
age_col = "AGE",
new_col = "AGEGR1",
classify = classify_age_fixed
) {
if (!is.data.frame(data)) {
stop("`data` must be a data frame.", call. = FALSE)
}
if (!age_col %in% names(data)) {
stop(sprintf("Column `%s` not found in `data`.", age_col), call. = FALSE)
}
data[[new_col]] <- classify(data[[age_col]])
data
}
#' Convenience wrapper: derive age group using buggy classifier
#'
#' @param data A data frame containing patient records.
#' @param age_col Name of the numeric age column.
#' @param new_col Name of the derived column to create.
#' @return Data frame with derived age group.
derive_age_group_buggy <- function(data, age_col = "AGE", new_col = "AGEGR1") {
derive_age_group(
data,
age_col = age_col,
new_col = new_col,
classify = classify_age_buggy
)
}
#' Convenience wrapper: derive age group using fixed classifier
#'
#' @param data A data frame containing patient records.
#' @param age_col Name of the numeric age column.
#' @param new_col Name of the derived column to create.
#' @return Data frame with derived age group.
derive_age_group_fixed <- function(data, age_col = "AGE", new_col = "AGEGR1") {
derive_age_group(
data,
age_col = age_col,
new_col = new_col,
classify = classify_age_fixed
)
}
#' Run property test for age classification
#'
#' Invariant: every valid, non-missing integer age between 0 and 100 must produce
#' a non-missing classification belonging to the allowed clinical levels.
#'
#' @param classify_fn Function under test.
#' @param tests Number of random iterations (default 100L).
#' @param seed Random seed for reproducible generation.
#' @return The expectation result from for_all().
test_age_property <- function(classify_fn, tests = 100L, seed = 42L) {
set.seed(seed)
allowed_levels <- c("< 18", "18-64", ">= 65")
quickcheck::for_all(
age = quickcheck::integer_bounded(0L, 100L),
property = function(age) {
res <- classify_fn(age)
testthat::expect_true(all(!is.na(res)))
testthat::expect_true(all(res %in% allowed_levels))
},
tests = tests
)
}
#' Run property test for tabular derivation
#'
#' Invariants:
#' 1. Row count is preserved: nrow(result) == nrow(data)
#' 2. Completeness: is.na(result$AGEGR1) == is.na(data$AGE)
#' 3. Domain: all non-NA derived values belong to the allowed levels
#'
#' @param derive_fn Derivation function under test.
#' @param tests Number of random iterations (default 100L).
#' @param seed Random seed for reproducible generation.
#' @return The expectation result from for_all().
test_derivation_property <- function(derive_fn, tests = 100L, seed = 42L) {
set.seed(seed)
allowed_levels <- c("< 18", "18-64", ">= 65")
quickcheck::for_all(
df = quickcheck::data_frame_(
AGE = quickcheck::integer_bounded(0L, 100L, any_na = FALSE),
rows = c(0L, 25L)
),
property = function(df) {
res <- derive_fn(df)
testthat::expect_equal(nrow(res), nrow(df))
testthat::expect_equal(is.na(res$AGEGR1), is.na(df$AGE))
valid_vals <- res$AGEGR1[!is.na(res$AGEGR1)]
testthat::expect_true(all(valid_vals %in% allowed_levels))
},
tests = tests
)
}
# Run demo when executed as a standalone script
if (sys.nframe() == 0L) {
cat("=======================================================\n")
cat("Step 1: Testing classify_age_buggy() with quickcheck\n")
cat("=======================================================\n")
tryCatch(
test_age_property(classify_age_buggy, tests = 100L, seed = 42L),
error = function(e) {
cat("Caught property failure:\n", conditionMessage(e), "\n\n")
}
)
cat("=======================================================\n")
cat("Step 2: Testing classify_age_fixed() with quickcheck\n")
cat("=======================================================\n")
fixed_res <- test_age_property(classify_age_fixed, tests = 100L, seed = 42L)
cat("Result:", class(fixed_res)[1], "(passed all 100 random tests)\n\n")
cat("=======================================================\n")
cat("Step 3: Testing derive_age_group_fixed() on random data frames\n")
cat("=======================================================\n")
df_res <- test_derivation_property(
derive_age_group_fixed,
tests = 100L,
seed = 42L
)
cat("Result:", class(df_res)[1], "(all tabular invariants hold)\n")
}Sources
Package documentation
- quickcheck: CRAN
- hedgehog: CRAN
- testthat: testthat.r-lib.org
- withr: withr.r-lib.org
- dplyr: dplyr.tidyverse.org
- pharmaverseadam: pharmaverse.github.io/pharmaverseadam
Property-based testing outside R
- QuickCheck (Haskell; Claessen and Hughes, 2000): hackage.haskell.org/package/QuickCheck
- Hypothesis (Python): hypothesis.readthedocs.io
- fast-check (JavaScript/TypeScript): fast-check.dev
- 2026-09-27: Added a Sources section.
- 2026-09-27: Added a Companion code section with the full script.