function expect_that from testthat runs into error

老子叫甜甜 提交于 2019-12-10 17:49:52

问题


Can anybody help me and explain why expect_that doesn't work if [] is added to the stop message, i.e. f1 works but f2 doesn't.

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

回答1:


expect_that is looking for a regular expression to match the error, so you need to escape the square-brackets so that they are interpreted literally rather than as a pattern definition:

expect_that(f2(x=1.4), throws_error("error \\[1\\]"))

seems to work.

Or you can specify fixed=TRUE:

expect_that(f2(x=1.4), throws_error("error [1]", fixed = TRUE))


来源:https://stackoverflow.com/questions/28266954/function-expect-that-from-testthat-runs-into-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!