我正在尝试为 R 中的包函数编写测试。
\n\n假设我们有一个函数,只需x使用以下命令将字符串写入磁盘writeLines():
exporting_function <- function(x, file) {\n\n writeLines(x, con = file)\n\n invisible(NULL)\n}\n测试它的一种方法是检查文件是否存在。通常,它一开始不应该存在,但在运行导出函数之后它应该存在。另外,您可能想测试文件大小是否大于 0:
\n\nlibrary(testthat)\n\ntest_that("file is written to disk", {\n file = \'output.txt\'\n expect_false(file.exists(file))\n\n exporting_function("This is a test",\n                    file = file)\n\n\n expect_true(file.exists(file))\n\n expect_gt(file.info(\'output.txt\')$size, 0)\n})\n这是一个很好的测试方法吗?在CRAN 存储库政策中,它指出Packages should not write in the user\xe2\x80\x99s home filespace (including clipboards), nor anywhere else on the file system apart from the R session\xe2\x80\x99s temporary directory. 这个测试会违反这个限制吗?
有一个expect_output_file函数。从文档和示例中,我不确定这是否是测试该功能的更合适的期望。它需要一个object参数,该参数应该是object to test. 我的案例中要测试的对象是什么?
这看起来好像违反了 CRAN 政策。为什么不简单地写入临时目录,使用
file <-  tempfile()
代替
file = 'output.txt'
?
至于这是否是一个好的测试:尝试读回文件并确认读取的内容与写入的内容是否匹配不是更好吗?在你的玩具示例中这很容易。在真实的情况下可能会更困难,但是将导入函数与导出函数配合使用总是一个好主意。
| 归档时间: | 
 | 
| 查看次数: | 624 次 | 
| 最近记录: |