Testing warnings in R by comparing strings (best idea?) -
i'm working on r package , need writing r test functions meant check whether correct warning being thrown on c-side code , caught on r side. let me give background on i'm working on exactly:
- most of i'm writing done on c side. in addition, have if-statement type macro in c allows coder pass warning r in form of string. basic premise if(statement_true) pass_warning_to_r("warning string pass"). i'd test whether these warnings being thrown when expect/need them writing r file uses trycatch blocks.
so far i've written similar this:
counter <- 0 trycatch({ function_im_testing() }, warning = function(war) { # check if warning expected , if increment counter if(tostring(war)=="the warning i'm expecting/testing for"){ print(tostring(war)) counter <- counter + 1 } }, error = function(err) { print(tostring(err)) }, = { print("leaving trycatch") }) # stop if 3 warnings expected aren't present stopifnot(counter == 3)
this method i'm using and, far, haven't been able if statement execute trying tostring(war) , "warning i'm expecting/testing for" same thing. this, in addition fact method pretty sloppy , unreliable, leads me believe there's better way. so, there better approach doing this?
usually warnings you'd allow evaluation continue; trycatch
used stop evaluation. instead use withcallinghandlers
handler warnings want, , invokes 'mufflewarning' restart. message of error / warning can extracted conditionmessage
counter <- 0l withcallinghandlers({ function_im_testing() }, warning = function(w) { if (conditionmessage(w) == "the warning i'm expecting/testing for") counter <<- counter + 1l invokerestart("mufflewarning") })
since you're writing own package, makes sense create warnings can identified in more robust way, e.g., following returns condition can used in warning
, has class 'bad_input' can used in withcallinghandlers
.
bad_input <- function(...) { w <- simplewarning(...) class(w) <- c("bad_input", class(w)) w }
to used warning(bad_input("your input bad"))
, producing output with
fun <- function() { warning("oops") warning(bad_input("your input bad")) "done" }
like
> fun() [1] "done" warning messages: 1: in fun() : oops 2: input bad > counter <- 0l > withcallinghandlers(fun(), bad_input = function(w) { + counter <<- counter + 1l + invokerestart("mufflewarning") + }) [1] "done" warning message: in fun() : oops > counter [1] 1
Comments
Post a Comment