【问题标题】:How to test if ggplot was printed?如何测试是否打印了ggplot?
【发布时间】:2021-05-03 08:37:42
【问题描述】:
让我们考虑非常基本的功能:
plot_ggplot <- function() {
print(ggplot() + aes(x = 1:100, y = 1:100) + geom_point())
}
有没有可能为这样定义的函数创建合理的单元?我知道当不包括打印时我们可以轻松地创建单元测试。也许有可能检查 R 的绘图窗口中是否出现某些内容?
我不想重新定义函数,因为它是更大函数的一部分。
【问题讨论】:
标签:
r
unit-testing
ggplot2
testthat
【解决方案1】:
一种可能性是将设备捕获为光栅并检查所有值是否都是白色的,但我不知道设备在测试环境中的行为方式。我认为,您还必须在每次打印后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 年 1 月 29 日创建