R 包中已弃用函数的单元测试会在检查期间导致警告



通过在函数的开头包含一个.Deprecated("new_function_name")行,我已经弃用了R包中的几个函数。 我对这些已弃用的函数进行了完整的单元测试覆盖。 现在,这些测试会产生警告(由于弃用消息(并混淆testthat::test()devtools::check().

的结果

我可以删除已弃用函数的测试覆盖率,但似乎只要用户仍然可以调用这些函数,我就应该保留测试覆盖率。 有没有办法保留测试但避免check()结果混乱? 例如,如果expect_equal()仍然有效,告诉testthat将它们计为通过,忽略弃用警告?

.Deprecated会产生警告。因此,如果您不想测试它是否发出警告,则始终可以临时存储输出并将其包装在对expect_warningsuppressWarnings的调用中。

my_dep_fun <- function(x){
   .Deprecated("my_new_fun")
   return(x+1)
}

使用这个

> # This is what I expect you're doing right now
> expect_equal(my_dep_fun(3), 4)
Warning message:
'my_dep_fun' is deprecated.
Use 'my_new_fun' instead.
See help("Deprecated") 
> 
> # If we store and use expect_warning we don't get the warning
> expect_warning(tmp <- my_dep_fun(3))
> expect_equal(tmp, 4)
> # Alternatively...
> suppressWarnings(expect_equal(my_dep_fun(3), 4))
> 

这是一个老问题,但现在"生命周期"包提供了一个很好的方法。 文档清晰简洁:

library(testthat)
mytool <- function() {
  deprecate_soft("1.0.0", "mytool()")
  10 * 10
}
# Forcing the verbosity level is useful for unit testing. You can
# force errors to test that the function is indeed deprecated:
test_that("mytool is deprecated", {
  rlang::local_options(lifecycle_verbosity = "error")
  expect_error(mytool(), class = "defunctError")
})
# Or you can enforce silence to safely test that the function
# still works:
test_that("mytool still works", {
  rlang::local_options(lifecycle_verbosity = "quiet")
  expect_equal(mytool(), 100)
})

可以使用tests/testthat/setup.R全局设置测试的选项。

最新更新