我很难从expect_silent()函数中理解检验函数的以下行为。
当测试代码返回任何输出(例如错误或警告)时,expect_silent()应该失败:
library(testthat)
test_that("expect_silent works as expected", {
expect_silent( {
stop()
} )
} )
#> Error: Test failed: 'expect_silent works as expected'
#> *
#> 1: expect_silent({
#> stop()
#> }) at <text>:5
#> 2: quasi_capture(enquo(object), evaluate_promise)
#> 3: capture(act$val <- eval_bare(get_expr(quo), get_env(quo)))
#> 4: withr::with_output_sink(temp, withCallingHandlers(withVisible(code), warning = handle_warning,
#> message = handle_message))
#> 5: force(code)
#> 6: withCallingHandlers(withVisible(code), warning = handle_warning, message = handle_message)
#> 7: withVisible(code)
#> 8: eval_bare(get_expr(quo), get_env(quo))
#> 9: stop() at <text>:6(以上是预期的行为:expect_silent()检测stop()产生的错误,测试失败。)
但是,由于某些原因,它似乎没有检测到ggplot2表达式中发生的错误。例如,以下ggplot2代码由于拼写错误而产生错误:
library(ggplot2)
ggplot(diamonds, aes(x = carrot, y = price)) +
geom_point()
#> Error in FUN(X[[i]], ...): object 'carrot' not found但是expect_silent()似乎没有检测到错误:
test_that("expect_silent fails when ggplot2 throws an error", {
expect_silent( {
ggplot(diamonds, aes(x = carrot, y = price)) +
geom_point()
} )
} )(不产生任何产出。)
我是否误解了expect_silent()的目的?这让我非常头疼,因为我试图用它来测试ggplot2扩展。
发布于 2018-12-13 15:34:41
试着从ggplot中捕获输出,然后测试它是否可以打印:
library(ggplot2)
library(testthat)
# First test should succeed (no output)
test_that("silent when ggplot2 succeeds", {
working.plot <- ggplot(diamonds, aes(x = carat, y = price)) + geom_point()
expect_silent(print(working.plot))
} )
# Second test should fail
test_that("fails when ggplot2 throws an error", {
broken.plot <- ggplot(diamonds, aes(x = carrot, y = price)) + geom_point()
expect_silent(print(broken.plot))
} )第二个测试失败了大量输出,我在下面对其进行了缩减:
Error: Test failed: 'expect_silent fails when ggplot2 throws an error'
* object 'carrot' not found更新-2018年12月15日
关于为什么print()是必要的,您的评论:
ggplot()函数返回一个类ggplot的对象。ggplot2包重载print()函数,因此它不会将对象打印到R会话终端中的STDOUT,而是打印图表。R会话终端中的交互模式假设大多数命令通过print()函数运行。
在自己的环境中对测试进行评估的测试。测试表明环境是非交互的,因此运行在print()函数假设中的情况不再成立。您可以用基本R附带的interactive()函数来测试这一点,它应该在R会话终端中报告TRUE,在test_that()调用中报告FALSE。
https://stackoverflow.com/questions/53761025
复制相似问题