Last active
March 23, 2023 08:03
-
-
Save krlmlr/262b7df52839de6f0dbad33a69824247 to your computer and use it in GitHub Desktop.
Create boilerplate test files from source files in an R package
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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