我如何测试一个函数 returns 是否是一条消息
How can I test if a function returns a message
背景: 在 R 中,包 "testit" (here) 具有 has_warning
和 has_error
两种功能,但我我正在寻找 returns 逻辑 TRUE/FALSE if has_message.
的函数
WHY:识别何时 webElem$submitElement()
来自 RSelenium
包 returns 一条 RSelenium 消息,因为 selenium 消息未分类为R 中的警告或错误。
有没有办法在 R 中测试函数 returns 是否是消息?
理想情况如下:
#Ideally a function like this made up one:
has_message(message("Hello ","World!"))
[1] TRUE
has_message(print("Hello World!"))
[1] FALSE
您可以使用 tryCatch
:
has_message <- function(expr) {
tryCatch(
invisible(capture.output(expr)),
message = function(i) TRUE
) == TRUE
}
has_message(message("Hello World!"))
# TRUE
has_message(print("Hello World!"))
# FALSE
has_message(1)
# FALSE
用 invisible(capture.output())
计算 tryCatch
中的表达式以抑制 print
或其他输出。当没有消息存在时,我们需要最终 == TRUE
到 return FALSE
,否则对于最后一个示例,将没有输出。
背景: 在 R 中,包 "testit" (here) 具有 has_warning
和 has_error
两种功能,但我我正在寻找 returns 逻辑 TRUE/FALSE if has_message.
WHY:识别何时 webElem$submitElement()
来自 RSelenium
包 returns 一条 RSelenium 消息,因为 selenium 消息未分类为R 中的警告或错误。
有没有办法在 R 中测试函数 returns 是否是消息?
理想情况如下:
#Ideally a function like this made up one:
has_message(message("Hello ","World!"))
[1] TRUE
has_message(print("Hello World!"))
[1] FALSE
您可以使用 tryCatch
:
has_message <- function(expr) {
tryCatch(
invisible(capture.output(expr)),
message = function(i) TRUE
) == TRUE
}
has_message(message("Hello World!"))
# TRUE
has_message(print("Hello World!"))
# FALSE
has_message(1)
# FALSE
用 invisible(capture.output())
计算 tryCatch
中的表达式以抑制 print
或其他输出。当没有消息存在时,我们需要最终 == TRUE
到 return FALSE
,否则对于最后一个示例,将没有输出。