sky*_*end 6 warnings unit-testing r package
我正在为R包编写一些测试,并希望R CMD check验证函数是否显示某些输入的正确警告.但我无法弄清楚如何捕获警告输出,以便我可以测试它.
所以,如果我有一个像这样的功能:
throwsWarning<-function(x){
if(x>0){
warning('Argument "x" is greater than zero, results may be incorrect')
}
# do something useful ...
}
Run Code Online (Sandbox Code Playgroud)
我想在我的测试文件中有一些东西,比如:
warningOutput <-try( throwsWarning(1))
if (warningOutput!='Argument "x" is greater than zero, results may be incorrect'){
stop('function "throwsWarning" did not produce correct warning when x>0')
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经通过更改找到了可能的部分解决方案,options以便将警告视为错误,并将周围视为trycatch块.也被认为是测试值last.warning,但如果没有抛出警告(将测试之前的值),这似乎很危险.似乎必须有一个简单的方法来做到这一点,我错过了?
该testthat包有一个expect_warning和gives_warning您可以使用的功能.
从示例中,您可以执行以下操作:
R> library(testthat)
R> expect_that(warning("this is a warning"), gives_warning("is a"))
## This does not raise an error, but:
R> expect_that(warning("this is a warning"), gives_warning("nope"))
Error: warning("this is a warning") does not match 'nope'. Actual value:
this is a warning
Run Code Online (Sandbox Code Playgroud)
因此,gives_warning正则表达式与应该发出的警告匹配.如果正则表达式不匹配(或者没有抛出警告),则引发红色标记.
同样,使用较短的expect_warning:
R> expect_warning(warning("this is a warning"), "is a")
Run Code Online (Sandbox Code Playgroud)