簡體   English   中英

錯誤消息中的括號會導致Expect_error測試失敗

[英]Parentheses in error message cause expect_error test to fail

為什么這個測試沒有通過?

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

它返回錯誤消息:

錯誤:錯誤$消息不匹配“必須在x小於或等於1的值上調用my_fun()”。 實際值:“必須在x小於或等於1的值上調用my_fun()”

如果您同時從函數和測試中刪除() ,則測試通過,導致我認為這與括號有關。

expect_error ,您傳遞的是正則表達式,而不僅僅是字符串。 括號是正則表達式中的特殊字符,必須轉義。 (括號用於分組正則表達式)。 要處理parens,只需將expect_error更改為以下內容:

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

或更籠統地說,指定fixed = TRUE以測試字符串是否完全匹配:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM