【发布时间】:2018-10-31 10:08:31
【问题描述】:
我正在尝试为 R 中的包函数编写测试。
假设我们有一个函数,它使用 writeLines() 简单地将字符串 x 写入磁盘:
exporting_function <- function(x, file) {
writeLines(x, con = file)
invisible(NULL)
}
测试它的一种方法是检查文件是否存在。通常,它一开始不应该存在,但在导出函数运行后它应该存在。此外,您可能希望测试文件大小是否大于 0:
library(testthat)
test_that("file is written to disk", {
file = 'output.txt'
expect_false(file.exists(file))
exporting_function("This is a test",
file = file)
expect_true(file.exists(file))
expect_gt(file.info('output.txt')$size, 0)
})
这是测试它的好方法吗?在CRAN Repository Policy 中声明Packages should not write in the user’s home filespace (including clipboards), nor anywhere else on the file system apart from the R session’s temporary directory。这个测试会违反这个约束吗?
有一个expect_output_file 函数。从文档和示例中,我不确定这是否是测试该功能的更合适的期望。它需要 a.o.一个object 参数,它应该是object to test。在我的情况下要测试的对象是什么?
【问题讨论】:
-
该政策还规定“如果包获得用户的确认,则可以在交互式会话中允许有限的例外情况。”我必须假设这包括隐含的确认,例如使用明确目的是写入磁盘的函数;否则
devtools、Rcpp和RcppArmadillo等软件包永远不会出现在 CRAN 上,因为它们为用户设置了 R 软件包目录结构。 -
关于如何测试函数的问题对于 Stack Overflow 来说是一个很好的问题。询问 CRAN 政策的部分可能更适合 R-package-devel mailing list。
-
添加到问题中也很棒:如何正确地将示例添加到写入文件的函数中
-
这可以使用`\dontrun{}`来完成