2013-07-11 21 views
8

testthat包中的expect_error()的正確用法是什麼?我試圖從幫助中調整示例,但是在錯誤消息中使用括號時會失敗。如何正確使用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 ')'' 

ř版本3.0.1(2013年5月16日)

+0

的可能的複製[功能預計\ _that從testthat運行到錯誤](http://stackoverflow.com/questions/28266954/function-expect-that-from- testthat-runs-into-error) –

回答

3

第二個參數是一個正則表達式。所以,你應該給出一個有效的正則表達式,例如,這將爲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.?\\(?") 
}) 
+0

我明白了,謝謝。是否有一些功能來自動查看錯誤字符串? –

10

從版本0.8(發佈2014年2月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)