在testthat中测试确切的字符串 [英] Test for exact string in testthat

查看:100
本文介绍了在testthat中测试确切的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试我的一个功能是否给出了特定的消息(或警告或错误).

I'd like to test that one of my functions gives a particular message (or warning, or error).

good <- function() message("Hello")
bad <- function() message("Hello!!!!!")

我希望第一个期望成功,第二个失败.

I'd like the first expectation to succeed and the second to fail.

library(testthat)
expect_message(good(), "Hello", fixed=TRUE)
expect_message(bad(), "Hello", fixed=TRUE)

不幸的是,他们俩此刻都过去了.

Unfortunately, both of them pass at the moment.

为了澄清:这只是一个最小的示例,而不是我要测试的确切消息.如果可能的话,我想通过为我要测试的每条新消息提供适当的正则表达式来避免增加测试脚本的复杂性(可能还包括错误).

For clarification: this is meant to be a minimal example, rather than the exact messages I'm testing against. If possible I'd like to avoid adding complexity (and probably errors) to my test scripts by needing to come up with an appropriate regex for every new message I want to test.

推荐答案

您可以使用^$锚点来指示字符串必须以您的模式开头和结尾.

You can use ^ and $ anchors to indicate that that the string must begin and end with your pattern.

expect_message(good(), "^Hello\\n$")
expect_message(bad(), "^Hello\\n$")
#Error: bad() does not match '^Hello\n$'. Actual value: "Hello!!!!!\n"

需要\\n来匹配message添加的新行.

The \\n is needed to match the new line that message adds.

由于没有换行符,因此警告更简单一些:

For warnings it's a little simpler, since there's no newline:

expect_warning(warning("Hello"), "^Hello$")

对于错误,要难一点:

good_stop <- function() stop("Hello")
expect_error(good_stop(), "^Error in good_stop\\(\\) : Hello\n$")

请注意,所有正则表达式元字符(即. \ | ( ) [ { ^ $ * + ?)都需要转义.

Note that any regex metacharacters, i.e. . \ | ( ) [ { ^ $ * + ?, will need to be escaped.

或者,从弗里克先生的回答中借用此处,您可以将消息转换为字符串,然后使用expect_identical

Alternatively, borrowing from Mr. Flick's answer here, you could convert the message into a string and then use expect_true, expect_identical, etc.

messageToText <- function(expr) {
  con <- textConnection("messages", "w")
  sink(con, type="message")
  eval(expr)
  sink(NULL, type="message")
  close(con)
  messages
}

expect_identical(messageToText(good()), "Hello")
expect_identical(messageToText(bad()), "Hello") 
#Error: messageToText(bad()) is not identical to "Hello". Differences: 1 string mismatch

这篇关于在testthat中测试确切的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆