1context("rlang conditions") 2 3get_n_stop <- function(f) { 4 d <- getParseData(parse(f, keep.source = TRUE)) 5 sum(d$token == "SYMBOL_FUNCTION_CALL" & d$text == "stop") 6} 7 8get_n_warning <- function(f) { 9 d <- getParseData(parse(f, keep.source = TRUE)) 10 sum(d$token == "SYMBOL_FUNCTION_CALL" & d$text == "warning") 11} 12 13get_n_data.frame <- function(f) { 14 d <- getParseData(parse(f, keep.source = TRUE)) 15 16 idx_base <- d$token == "SYMBOL_PACKAGE" & d$text == "base" 17 idx_colons <- d$token == "NS_GET" & d$text == "::" 18 # exclude the case when the `data.frame` is prefixed with `base::` 19 idx_base_prefixed <- c(FALSE, FALSE, idx_base[1:(nrow(d) - 2)]) & c(FALSE, idx_colons[1:(nrow(d) - 1)]) 20 21 idx_data.frame <- d$token == "SYMBOL_FUNCTION_CALL" & d$text == "data.frame" 22 sum(idx_data.frame & !idx_base_prefixed) 23} 24 25test_that("`get_n_*() detects number of calls properly", { 26 withr::local_file("tmp.R") 27 writeLines( 28 c( 29 'stop("foo!")', 30 'warning("bar!")', 31 "data.frame(x = 1)", 32 "base::data.frame(x = 1)" # this is not counted 33 ), 34 "tmp.R" 35 ) 36 37 expect_equal(get_n_stop("tmp.R"), 1) 38 expect_equal(get_n_warning("tmp.R"), 1) 39 expect_equal(get_n_data.frame("tmp.R"), 1) 40}) 41 42# Pattern is needed filter out files such as ggplot2.rdb, which is created when running covr::package_coverage() 43R_paths <- c( 44 "../../R", # in the case of devtools::test() 45 "../../00_pkg_src/ggplot2/R" # in the case of R CMD check 46) 47R_files <- list.files(R_paths, pattern = ".*\\.(R|r)$", full.names = TRUE) 48 49test_that("list up R files properly", { 50 skip_on_covr() 51 skip_on_cran() 52 53 expect_true(length(R_files) > 0) 54}) 55 56test_that("do not use stop()", { 57 stops <- vapply(R_files, get_n_stop, integer(1)) 58 expect_equal(sum(stops), 0) 59}) 60 61test_that("do not use warning()", { 62 warnings <- vapply(R_files, get_n_warning, integer(1)) 63 expect_equal(sum(warnings), 0) 64}) 65 66test_that("do not use data.frame(), use `data_frame()` or `new_data_frame()`, or add `base::` prefix", { 67 data.frames <- vapply(R_files, get_n_data.frame, integer(1)) 68 expect_equal(sum(data.frames), 0) 69}) 70