gpt4 book ai didi

r - 如何正确使用testthat Expect_error()?

转载 作者:行者123 更新时间:2023-12-03 13:27:00 25 4
gpt4 key购买 nike

expect_error()软件包中testthat的正确用法是什么?我试图从帮助中改编示例,但是当我在错误消息中使用方括号时,此操作将失败。

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)

最佳答案

第二个参数是一个正则表达式。因此,您应该提供一个有效的正则表达式,例如,这将对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.?\\(?")
})

关于r - 如何正确使用testthat Expect_error()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17590409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com