小编Dec*_*ave的帖子

通过比较字符串测试R中的警告(最好的主意?)

我正在研究一个R包,我需要一些帮助来编写R测试函数,这些函数用于检查是否在C端代码上抛出正确的警告然后在R端捕获.让我给你一些关于我正在做的工作的背景:

  1. 我写的大部分内容都是在C方面完成的.另外,我在C中有一个if语句类型的宏,允许编码器以字符串的形式向R传递警告.基本前提是if(statement_true)pass_warning_to_R("要传递的警告字符串").我想要做的是测试是否在通过编写使用tryCatch块的R文件期望/需要它们时抛出这些警告.
  2. 到目前为止,我写了类似的东西:

    counter <- 0
    tryCatch({
    
    function_im_testing()
    
    }, warning = function(war) {
         # Check if warning is as expected and if so increment counter
         if(toString(war)=="The warning I'm expecting/testing for"){
            print(toString(war))
            counter <- counter + 1
         }
    
    }, error = function(err) {
          print(toString(err))
    
    }, finally = {
    print("Leaving tryCatch")
    })
    
    # Stop if the 3 warnings we expected aren't present
    stopifnot(counter == 3)
    
    Run Code Online (Sandbox Code Playgroud)

这是我正在使用的方法,到目前为止,我甚至无法通过尝试获取toString(war)和"警告我期望/测试"来获得if语句.事情.除此之外,这种方法非常草率和不可靠,这使我相信有更好的方法.那么,有没有更好的方法来做到这一点?

warnings r

6
推荐指数
1
解决办法
162
查看次数

如何在R中的callCallingHandlers中抛出错误时继续运行

我正在为一个R函数编写一个测试用例,该函数测试是否在函数中的某个点抛出并正确捕获错误,并且在执行withCallingHandlers期间抛出错误时,我遇到一些麻烦(......).我正在使用这种方法:

counter <- 0
withCallingHandlers({
testingFunction(df0, df1)
testingFunction(df2, df3)
testingFunction(df4, df5)

}, warning=function(war){
    print(paste(war$message))
}, error=function(err){
    print(paste(err$message))
    if(err$message == paste("The function should throw this error message",
                              "at the right time.")){
        counter <<- counter + 1
    }

})

stopifnot(counter == 2)
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是脚本在第一个错误(成功)被捕获后退出,我不知道如何处理错误,以便在捕获之后,withCallingHandlers继续执行下一部分.我知道它与重启对象有关,但我不确定如何正确使用它们.有没有人知道如何操作上面的代码,以便即使捕获错误,执行withCallingHandlers(...)仍然继续?

error-handling r

5
推荐指数
2
解决办法
1316
查看次数

标签 统计

r ×2

error-handling ×1

warnings ×1