# The testthat loop, end to end: builds a throwaway package in a temporary # folder, adds a small function and its tests with usethis, and runs the tests # with testthat. # # Rscript first-tests.R bmi_code <- c( "#' Body mass index", "#'", "#' @param weight_kg Weight in kilograms.", "#' @param height_m Height in metres.", "#' @return Weight divided by height squared.", "#' @export", "bmi <- function(weight_kg, height_m) {", " if (any(height_m <= 0, na.rm = TRUE)) {", " stop(\"`height_m` must be positive.\", call. = FALSE)", " }", " weight_kg / height_m^2", "}" ) bmi_tests <- c( "test_that(\"bmi() divides weight by height squared\", {", " expect_equal(bmi(70, 1.75), 22.857, tolerance = 1e-4)", "})", "", "test_that(\"bmi() is vectorised\", {", " expect_length(bmi(c(60, 70, 80), c(1.6, 1.7, 1.8)), 3)", "})", "", "test_that(\"bmi() rejects heights that aren't positive\", {", " expect_error(bmi(70, 0), \"must be positive\")", "})", "", "test_that(\"bmi() keeps missing values missing\", {", " expect_true(is.na(bmi(NA, 1.7)))", "})" ) # Creates the package and returns its path. make_demo_package <- function(path = file.path(tempdir(), "bmicalc")) { usethis::create_package(path, rstudio = FALSE, open = FALSE) usethis::with_project(path, { usethis::use_testthat(3) # tests/testthat/, tests/testthat.R, edition 3 usethis::use_r("bmi", open = FALSE) # creates the R/bmi.R file usethis::use_test("bmi", open = FALSE) # creates its test file }) writeLines(bmi_code, file.path(path, "R", "bmi.R")) writeLines(bmi_tests, file.path(path, "tests", "testthat", "test-bmi.R")) path } # Loads the package from source and runs its tests (like devtools::test()). run_demo_tests <- function(path, reporter = testthat::default_reporter()) { testthat::test_local(path, reporter = reporter, stop_on_failure = FALSE) } # Run only when called as a script (not when sourced by the tests). if (sys.nframe() == 0L) { path <- make_demo_package() results <- run_demo_tests(path) print(as.data.frame(results)[, c("test", "nb", "failed", "error")]) }