簡體   English   中英

如何正確使用testthat expect_error()?

[英]How to use testthat expect_error() correctly?

testthat包中expect_error()的正確用法是什么? 我試圖從幫助中調整示例,但是當我在錯誤消息中使用括號時,這會失敗。

library(testthat)

# Works
tmp1 <- function() stop("Input is not correct")
    expect_error(tmp1(),"Input is not correct")

# Does not work
tmp2 <- function() stop("Input (x) is not correct")
    expect_error(tmp2(),"Input (x) is not correct")

# Does not work
tmp3 <- function() stop("Input(")
    expect_error(tmp3(),"Input(")

這導致:

> library(testthat)
> 
> # Works
> tmp1 <- function() stop("Input is not correct")
> expect_error(tmp1(),"Input is not correct")
> # Does not work
> tmp2 <- function() stop("Input (x) is not correct")
> expect_error(tmp2(),"Input (x) is not correct")
Error: tmp2() does not match 'Input (x) is not correct'. Actual value: 
Error in tmp2() : Input (x) is not correct
> # Does not work
> tmp3 <- function() stop("Input(")
> expect_error(tmp3(),"Input(")
Error in grepl("Input(", "Error in tmp3() : Input(\n", fixed = FALSE,  : 
  invalid regular expression 'Input(', reason 'Missing ')''

R版本3.0.1(2013-05-16)

從版本0.8(2014-02-20發布)開始,您可以將參數傳遞給grep 允許在調用中使用fixed = TRUE ,因此字符串不會被視為正則表達式。

所以你可以使用:

# Works
tmp1 <- function() stop("Input is not correct")
expect_error(tmp1(), "Input is not correct", fixed=TRUE)

# Works
tmp2 <- function() stop("Input (x) is not correct")
expect_error(tmp2(), "Input (x) is not correct", fixed=TRUE)

# Works
tmp3 <- function() stop("Input(")
expect_error(tmp3(), "Input(", fixed=TRUE)

第二個參數是正則表達式。 所以你應該給出一個有效的正則表達式,例如,這將適用於3個函數:

## this works for 3 , error message containing Input
lapply(list('tmp1','tmp2','tmp3'),function(x){
   expect_error(do.call(x,list()),"Input.*")
})

## this works for 3 also, but more complicated regular expression
lapply(list('tmp1','tmp2','tmp3'),function(x){
  expect_error(do.call(x,list()),"Input.?\\(?")
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM