【问题标题】:Simple data.table snippet fails when run in testthat unit test简单的 data.table 片段在 testthat 单元测试中运行时失败
【发布时间】:2017-03-22 19:12:25
【问题描述】:

使用单个测试文件运行 devtools::test() 时出现错误,如下所示。然而,当单独运行test_that 语句(或其中的代码,逐行)时,它可以完美运行,即 myDt1 有一列 (y) 而 myDt 有两列 ( x 和 z),满足expect_equal 语句,没有失败,没有运行时错误...

当然,我一定做错了什么,但我看不到明显的东西!这似乎与依赖 NSE(非标准评估)的 data.table 的功能有关,与测试使用的一些 NSE 和其他魔法暂时冲突?

救命!

context("data.table and testthat do not play nice ?")
library(data.table)

test_that("data.table ", {

  # the following runs perfectly on it own
  # but fails when run as a test.
  myDt <- data.table(x=rnorm(10), y=rnorm(10), z=rnorm(10))
  targetCols <- c("y")

  myDt1 <- myDt[, targetCols, with=FALSE]
  expect_equal(ncol(myDt1), 1)

  myDt2 <- myDt[, !targetCols, with=FALSE]
  expect_equal(ncol(myDt2), 2)
})

我在测试模式下遇到的错误是: “1.失败”是由于 myDt1 没有被创建,它是 NULL,没有产生错误。 “2. 错误”表示 !targetCols 没有得到正确解释。在 devtool::test() 框架之外运行时,这些都不会发生。

> devtools::test()
Loading myLib
Testing myLib
data.table and testthat do not play nice ?: 12

Failed -----------------------------
1. Failure: data.table  (@testSimple.R#9) ----------------
ncol(myDt1) not equal to 1.
target is NULL, current is numeric


2. Error: data.table  (@testSimple.R#11) -----------------
invalid argument type
1: myDt[, !targetCols, with = FALSE] at D:\GitRepos\BlueMoon/tests/testthat/testSimple.R:11
2: `[.data.table`(myDt, , !targetCols, with = FALSE) at D:\GitRepos\BlueMoon/tests/testthat/testSimple.R:11
3: `[.data.frame`(x, i, j)

DONE ========================================================================
>

【问题讨论】:

    标签: r data.table testthat


    【解决方案1】:

    问题已解决: NAMESPACE 文件中没有import(data.table) 命令。 添加它解决了这个问题。就我而言,我间接地添加了它,因为我使用 roxygen,即使用

    #' @import data.table
    NULL
    

    在一个或多个源文件中。在这里,注释一个 NULL 对象,但这也可以是使用 data.table 库的任何一个函数。 (当上述用法普遍存在时,以跟踪使用该包的所有函数的方式添加这些并没有真正的好处)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-17
      • 2023-03-06
      • 2023-04-04
      • 1970-01-01
      相关资源
      最近更新 更多