我正在构建一个与 data.table 一起使用的包,并且应该使用包 testthat 对其进行测试。虽然从命令行调用时代码工作正常,但从测试用例调用时遇到问题。似乎在运行测试时使用了基本包中的 [] 函数,即 data.frames 的函数。
我创建了一个最小示例,可以在这里找到:https ://github.com/utalo/test_datatable_testthat
该包包含一个功能:
test <- function() {
dt <- data.table(MESSAGE="Test 1234567890",TYPE="ERROR")
dt[,.(MESSAGE=strwrap(MESSAGE,width = 10)),by=.(TYPE)]
}
test.datatable.testthat:::test()
从命令行调用时,我得到了预期的结果:
TYPE MESSAGE
1: ERROR Test
2: ERROR 1234567890
但是,在执行以下单元测试时:
test_that("Test package",{
dt <- test()
expected_res <- structure(list(TYPE = c("ERROR", "ERROR"),
MESSAGE = c("Test","1234567890")),
row.names = c(NA, -2L), class = c("data.table","data.frame"),
.Names = c("TYPE", "MESSAGE"))
expect_equal(dt,expected_res)
})
我收到一个错误:
1
1. Error: Test package -------------------------------------------------------------------------------------------------------
could not find function "."
1: withCallingHandlers(eval(code, new_test_environment), error = capture_calls, message = function(c) invokeRestart("muffleMessage"))
2: eval(code, new_test_environment)
3: eval(expr, envir, enclos)
4: test() at test.R:4
5: dt[, .(MESSAGE = strwrap(MESSAGE, width = 10)), by = .(TYPE)] at test.datatable.testthat/R/hello.R:5
6: `[.data.table`(dt, , .(MESSAGE = strwrap(MESSAGE, width = 10)), by = .(TYPE)) at C:\Users\D057806\Documents\R\test.datatable.testthat/R/hello.R:5
7: `[.data.frame`(x, i, j)
如您所见,在测试中调用了 data.frame 的 []。我的第一个猜测是对 data.table 包的依赖没有正确声明。这是我的说明文件:
Package: test.datatable.testthat
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1
Date: 2016-04-07
Authors@R: person("First", "Last", email = "first.last@example.com", role = c("aut", "cre"))
Description: More about what it does (maybe more than one line)
License: What license is it under?
LazyData: TRUE
Depends:
data.table
Suggests:
testthat
RoxygenNote: 5.0.1
根据在我自己的包中使用 data.table 包,将 data.table声明为依赖包就足够了。但是,这里的情况似乎并非如此。
关于为什么我的函数在被直接调用而不是在 testthat 的上下文中工作的任何线索?