I’m writing some tests for an R package and would like to have R CMD check verify that functions display the correct warnings for certain inputs. But I can’t figure out how to capture the warning output so that I can test it.
So if I have a function like:
throwsWarning<-function(x){
if(x>0){
warning('Argument "x" is greater than zero, results may be incorrect')
}
# do something useful ...
}
I’d want a something in my test file like:
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')
}
So far I’ve found possible partial solutions by changing options so that warnings are treated as errors and the surrounding with a trycatch block. Also considered testing value of last.warning, but that seems dangerous if the warning is not thrown (would test previous value). Seems like there must be an easy way to do this that I’m missing?
The testthat package has an
expect_warningandgives_warningfunction that you can use.From the examples, you would do something like this:
So,
gives_warningis regular expression that is matched against the warning that is supposed to be emitted. If the regex does not match (or no warning is thrown), then a red flag is raised.Equally, using the shorter
expect_warning: