简体   繁体   中英

Parentheses in error message cause expect_error test to fail

Why doesn't this test pass?

my_fun <- function(x){
  if(x > 1){stop("my_fun() must be called on values of x less than or equal to 1")}
  x
}

library(testthat)
expect_error(my_fun(2),
             "my_fun() must be called on values of x less than or equal to 1")

It returns the error message:

Error: error$message does not match "my_fun() must be called on values of x less than or equal to 1". Actual value: "my_fun() must be called on values of x less than or equal to 1"

If you remove the () from both the function and the test, the test does pass, leading me to think it's something about the parentheses.

In expect_error , you are passing a regular expression, not just a string. Parentheses are special characters in regular expressions and must be escaped. (Parentheses are used for grouping in regular expressions). To handle the parens, just change expect_error to the below:

expect_error(my_fun(2),
             "my_fun\\(\\) must be called on values of x less than or equal to 1")

Or more generally, specify fixed = TRUE to test the string as an exact match:

expect_error(my_fun(2),
             "my_fun() must be called on values of x less than or equal to 1",
             fixed = TRUE)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM