我可以从roxygen2示例中自动为testthat生成单元测试吗?
我正在为R编写PKNCA包。在开发测试代码的同时,一些测试也是很好的例子。我想让它们同时作为测试和示例。有没有一种方法可以让我在roxygen2文档中嵌入一些东西,并将其复制到测试中 我所考虑的是如下文档:我可以从roxygen2示例中自动为testthat生成单元测试吗?,r,roxygen2,testthat,R,Roxygen2,Testthat,我正在为R编写PKNCA包。在开发测试代码的同时,一些测试也是很好的例子。我想让它们同时作为测试和示例。有没有一种方法可以让我在roxygen2文档中嵌入一些东西,并将其复制到测试中 我所考虑的是如下文档: #' @exampleTest #' set.seed(5) #' rnorm(1) ## -0.8409 这将生成一个测试,如: expect_equal({set.seed(5) rnorm(1)}, -0.8409, tol=1e-4) (tol来源于示
#' @exampleTest
#' set.seed(5)
#' rnorm(1) ## -0.8409
这将生成一个测试,如:
expect_equal({set.seed(5)
rnorm(1)}, -0.8409, tol=1e-4)
(tol来源于示例中所示的数字和位数。)使用
devtools::run_examples()
,如中所述。运行R CMD CHECK时会测试函数示例。这不是testthat的一部分,而是标准R包检查系统的一部分。有一种方法,但它并不像您希望的那样平滑。您必须在@examples
块中调用testthat
函数。下面是一个示例函数:
#' @examples
#' testStrings <- c("1234567890",
#' "123 456 7890")
#'
#' testthat::expect_equal(extractPhoneNumbers(testStrings), "0123")
extractPhoneNumbers <- function(inputStr) {
# check input:
if (!is.character(inputStr)) {
stop("'inputStr' must be a (vector of) string(s)!")
}
# imports
`%>%` <- stringr::`%>%`
replace_all <- stringr::str_replace_all
extract_all <- stringr::str_extract_all
# intermediary regex's
visualDelimitersRegex <- "[()+\\-_. ]"
phoneNumberRegex <- "[:digit:]{10}"
inputStr %>%
replace_all(pattern = visualDelimitersRegex, replacement = "") %>%
extract_all(pattern = phoneNumberRegex)
}
阅读文档,这看起来会确认示例运行时没有错误,但看起来不会执行精度测试。我想我可以在需要精确性的地方运行我的示例,但这并不能直接将其放入测试框架中。如果没有其他答案,我会将此设置为答案。但是,我也希望找到一种方法来确认示例的准确性。更直接地说,
test::test_examples
将在测试期间在包中运行示例。当运行示例时没有错误时,测试通过。感谢您的建议。正如你所建议的,它不像我想要的那么平滑。因为它会混淆示例,所以我不认为我会使用它,但我建议在示例中使用testthat可能会有所帮助。
*** SNIP ***
* checking for unstated dependencies in examples ... OK
* checking examples ... ERROR
Running examples in ‘demoPkg-Ex.R’ failed
The error most likely occurred in:
> base::assign(".ptime", proc.time(), pos = "CheckExEnv")
> ### Name: extractPhoneNumbers
> ### Title: Extract Phone Numbers
> ### Aliases: extractPhoneNumbers
>
> ### ** Examples
>
> testStrings <- c("1234567890",
+ "123 456 7890")
>
> testthat::expect_equal(extractPhoneNumbers(testStrings), "0123")
Error: extractPhoneNumbers(testStrings) not equal to "0123"
Modes: list, character
Length mismatch: comparison on first 1 components
Component 1: 1 string mismatch
Execution halted
* checking for unstated dependencies in ‘tests’ ... OK
* checking tests ...
Running ‘testthat.R’
OK
* checking PDF version of manual ... OK
* DONE
Status: 1 ERROR