函数expect_that从testthat遇到错误

Nus*_*sig 4 r testthat

任何人都可以帮助我解释为什么 expect_that 如果[]添加到停止消息不起作用,即f1工作但f2不工作.

library(testthat)
f1 <- function(x){
  if(  x >= 1 ){
    stop("error 1")
  }
}
expect_that(f1(x=1.4), throws_error("error 1"))
f2 <- function(x){
  if(  x >= 1 ){
    stop("error [1]")
  }
}
expect_that(f2(x=1.4), throws_error("error [1]"))
Run Code Online (Sandbox Code Playgroud)

Ben*_*ker 7

expect_that正在寻找一个正则表达式来匹配错误,所以你需要转义方括号,以便它们按字面解释而不是作为模式定义:

expect_that(f2(x=1.4), throws_error("error \\[1\\]"))
Run Code Online (Sandbox Code Playgroud)

似乎工作.

或者您可以指定fixed=TRUE:

expect_that(f2(x=1.4), throws_error("error [1]", fixed = TRUE))
Run Code Online (Sandbox Code Playgroud)