使用匹配时,dplyr与testthat包冲突

时间:2016-11-15 02:30:06

标签: r dplyr testthat

我收到错误,因为testthat::matchesdplyr::matches冲突,我想知道如何使用testthat::test_file检查包含matches()调用的函数,而不是在函数体中指定dplyr::matches

E.g:

> testthat::test_file('tmp_fn_testthat_test.R')

Attaching package: ‘testthat’

The following object is masked from ‘package:dplyr’:

    matches

The following object is masked from ‘package:purrr’:

    is_null

 Show Traceback

 Rerun with Debug
 Error in -matches("tmp") : invalid argument to unary operator In addition: Warning message:
package ‘testthat’ was built under R version 3.2.5 

DONE =========================================================================================================================================

通过将以下代码保存在工作目录中名为tmp_fn_testthat_test.R的文件中,并运行命令testthat::test_file('tmp_fn_testthat_test_20161115.R'),可以重现此错误。请注意,在未加载expect_equal时获取或运行testthat命令会使测试通过。

tmp_fn <- function() {
    tmp_df <- data.frame(tmp_a = 1, tmp_b = 2)

    tmp_df %>%
        select(-matches('tmp')) %>%
        ncol


}

testthat::expect_equal(tmp_fn(), 0)

2 个答案:

答案 0 :(得分:2)

使用dplyr 0.5

This is a known issue。建议的解决方案是使用显式名称空间前缀:dplyr::matches

答案 1 :(得分:0)

解决方法似乎是在library(testthat)的定义中注释testthat::test_file,并使函数调用显式(不确定这是否会产生不良副作用):

my_test_that_file <- function (path, reporter = "summary", env = testthat::test_env(), start_end_reporter = TRUE, 
          load_helpers = TRUE) 
{
    # library(testthat)
    reporter <- testthat:::find_reporter(reporter)
    if (load_helpers) {
        testthat:::source_test_helpers(dirname(path), env = env)
    }
    lister <- testthat:::ListReporter$new()
    if (!is.null(reporter)) {
        reporter <- testthat:::MultiReporter$new(reporters = list(reporter, 
                                                       lister))
    }
    else {
        reporter <- lister
    }
    testthat::with_reporter(reporter = reporter, start_end_reporter = start_end_reporter, 
                  {
                      lister$start_file(basename(path))
                      testthat::source_file(path, new.env(parent = env), chdir = TRUE)
                      testthat:::end_context()
                  })
    invisible(lister$get_results())
}