【问题标题】:Testing package exports using 'testthat'使用“testthat”测试包导出
【发布时间】:2015-10-23 15:06:56
【问题描述】:

问题:如何让testthat加载我的包而不是继承我的包的环境中运行?

背景:testthat 包在“从包的命名空间环境继承的环境中”运行测试[参见test_check 的文档]。这意味着它不能确保我正确地完成了我的导出,这让我很痛苦。

例如,我的包中有以下代码:

##' The foo() method
##' @param x object
##' @export
foo <- function(x)
  UseMethod('foo')

##' @rdname foo
foo.data.frame <- function(x) {
  message("foo data.frame")
}

##' @rdname foo
foo.default <- function(x) {
  message("foo default")
}

我的测试中有以下内容:

x <- 5:13
foo(x)

测试很好。但是如果用户安装了这个包,他们会得到这个错误:

Error in UseMethod("foo") : 
  no applicable method for 'foo' applied to an object of class "c('integer', 'numeric')"

解决方案是为这两种方法添加@exports 声明,但测试没有捕捉到这一点真是太可惜了。

我更愿意从用户的角度运行我的所有测试,因为我有时会搞砸我的导出。或许可以向testthat:::run_tests 添加一个选项来选择所需的行为?

【问题讨论】:

    标签: r namespaces testthat


    【解决方案1】:

    使用test_dir。出于这个确切原因,我不使用test_check。在“/tests/run-tests.R”(文件名无所谓,只要在那个目录下,以“.R”结尾)写:

    library(testthat)
    library(<my package>)  # insert actual package name here
    test_dir('testthat')   # assuming your tests are in "tests/testthat"
    

    然后,为了运行您的测试:

    setwd("<pkg dir>/tests")
    source("run-tests.R")
    

    或者从命令行:

    cd <pkg-dir>/tests
    Rscript run-tests.R
    

    或者使用R CMD buildR CMD check 以这种方式运行测试。

    如果您的测试不关心工作目录,则setwd 不是绝对必要的。但是,如果他们这样做,将复制R CMD check 设置的工作目录。

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 2018-01-17
      • 2016-08-03
      • 1970-01-01
      • 2015-10-11
      • 2012-02-12
      • 2020-09-26
      • 2014-02-18
      • 2018-02-02
      相关资源
      最近更新 更多