如何测试是否打印了ggplot?

How to test if ggplot was printed?

让我们考虑非常基本的功能:

plot_ggplot <- function() { 
    print(ggplot() + aes(x = 1:100, y = 1:100) + geom_point())
}

是否有可能为这样定义的函数创建合理的单位?我知道当不包括打印时,我们可以轻松地创建单元测试。也许有可能检查 R 中的情节 window 中是否出现某些内容?

我不想重新定义函数,因为它是更大函数的一部分。

一种可能性是将设备捕获为光栅并检查所有值是否都是白色,但我不知道设备在 testthat 环境中的行为。您还必须在每次打印后 dev.off() 并重新启动 cap <- ragg::agg_capture() 我认为每次测试。

library(ggplot2)

cap <- ragg::agg_capture()

has_printed <- function(x = cap()) {
  !all(x == "white")
}

plot_ggplot <- function() { 
  print(ggplot() + aes(x = 1:100, y = 1:100) + geom_point())
}

has_printed()
#> [1] FALSE

plot_ggplot()

has_printed()
#> [1] TRUE

dev.off()
#> png 
#>   2
cap <- ragg::agg_capture()

has_printed()
#> [1] FALSE

reprex package (v0.3.0)

于 2021-01-29 创建

编辑:您可以将重置作为 has_printed() 函数的一部分自动执行,但是您必须小心超赋值(这里是龙)。

library(ggplot2)

cap <- ragg::agg_capture()

has_printed <- function(x = cap()) {
  out <- !all(x == "white")
  dev.off()
  cap <<- ragg::agg_capture()
  return(out)
}

plot_ggplot <- function() { 
  print(ggplot() + aes(x = 1:100, y = 1:100) + geom_point())
}

has_printed()
#> [1] FALSE

plot_ggplot()

has_printed()
#> [1] TRUE

has_printed()
#> [1] FALSE

reprex package (v0.3.0)

于 2021-01-29 创建