繁体   English   中英

如何正确使用testthat expect_error()?

[英]How to use testthat expect_error() correctly?

testthat包中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(")

这导致:

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

从版本0.8(2014-02-20发布)开始,您可以将参数传递给grep 允许在调用中使用fixed = TRUE ,因此字符串不会被视为正则表达式。

所以你可以使用:

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

第二个参数是正则表达式。 所以你应该给出一个有效的正则表达式,例如,这将适用于3个函数:

## 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.?\\(?")
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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