2013-07-11 11 views
8

Qual è l'uso corretto di expect_error() nel pacchetto testthat? Ho provato ad adattare l'esempio di aiuto, ma questo fallisce quando uso parentesi nel messaggio di errore.Come utilizzare testthat expect_error() correttamente?

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(") 

Ciò comporta:

> 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 versione 3.0.1 (2013-05-16)

+0

Possibile duplicato del [funzione si aspettano \ _that da testthat corre in errore] (http://stackoverflow.com/questions/28266954/function-expect-that-from- testthat-runs-into-error) –

risposta

3

Il secondo argomento è un'espressione regolare. Così si dovrebbe dare un'espressione regolare valida, ad esempio, questo lavoro per 3 funzioni:

## 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

Vedo, grazie. C'è qualche funzione per eseguire l'autoescape della stringa di errore? –

10

A partire dalla versione 0.8 (rilasciata 2014/02/20) si potrebbe passare gli argomenti a grep. Ciò consente di utilizzare fixed = TRUE in chiamata in modo che la stringa non venga trattata come espressione regolare ma letteralmente.

Così si potrebbe usare:

# 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) 
Problemi correlati