Skip to content

Instantly share code, notes, and snippets.

@krlmlr
Last active March 23, 2023 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krlmlr/262b7df52839de6f0dbad33a69824247 to your computer and use it in GitHub Desktop.
Save krlmlr/262b7df52839de6f0dbad33a69824247 to your computer and use it in GitHub Desktop.
Create boilerplate test files from source files in an R package
library(conflicted)
library(tidyverse)
new_region <- function(name) {
paste0("# ", name, " ", strrep("-", max(88 - nchar(name) - 4, 0)))
}
boilerplate <- function(name) {
paste(collapse = "\n", c(
new_region(name),
"",
paste0('test_that("`', name, '()` snapshot test", {'),
" expect_snapshot({",
paste0(" ", gsub("[.][^.]+$", "", name), "()"),
" })",
"})"
))
}
sync_file <- function(path) {
basename <- fs::path_file(path)
test_path <- fs::path("tests/testthat", paste0("test-", basename))
text <- brio::read_lines(path)
matches <- str_match(text, "^([^ ]*) [<]- function[(]")
functions <- unique(na.omit(matches[,2]))
if (!fs::file_exists(test_path)) {
old_tests <- NULL
} else {
old_tests <- paste(collapse = "\n", c(
new_region("Legacy tests"),
"",
brio::read_lines(test_path)
))
}
code <- paste(c(map_chr(functions, boilerplate), old_tests), collapse = "\n\n\n")
brio::write_lines(code, test_path)
}
files <- fs::dir_ls("R")
walk(files, sync_file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment