2013-07-11 16 views
8

Jakie jest prawidłowe użycie pakietuw pakiecie? Próbowałem dostosować przykład z pomocy, ale to się nie powiedzie, gdy używam nawiasów w komunikacie o błędzie.Jak poprawnie używać testu 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(") 

Wynika to z:

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

+0

Możliwy duplikat [funkcja spodziewać \ _that z testthat prowadzi do błędu] (http://stackoverflow.com/questions/28266954/function-expect-that-from- testthat-runs-into-error) –

Odpowiedz

3

Drugi argument jest wyrażeniem regularnym. Więc należy podać poprawne wyrażenie regularne, na przykład, to będzie działać przez 3 funkcje:

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

Rozumiem, dziękuję. Czy jest jakaś funkcja autoesowania łańcucha błędów? –

10

Od wersji 0.8 (wydana 2014-02-20) można przekazywać argumenty do grep. To pozwala używać fixed = TRUE w wywołaniu, więc ciąg nie jest traktowany jako wyrażenie regularne, ale dosłownie.

Więc można użyć:

# 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) 
Powiązane problemy