[英]How to test if ggplot was printed?
Let's consider very basic function:让我们考虑非常基本的 function:
plot_ggplot <- function() {
print(ggplot() + aes(x = 1:100, y = 1:100) + geom_point())
}
Is there any possibility to create sensible unit for such defined function?是否有可能为这样定义的 function 创建明智的单元? I know that we can easily create unit testing when print is not included.
我知道当不包括打印时我们可以轻松地创建单元测试。 Maybe is there possibility to check if something appears in plot window in R?
也许有可能检查 R 中的 plot window 中是否出现某些东西?
I don't want to redefine the function because it's part of much bigger function.我不想重新定义 function,因为它是更大的 function 的一部分。
One possibility is to capture the device as a raster and check if all values are white, but I don't know how devices act in a testthat environment.一种可能性是将设备捕获为光栅并检查所有值是否都是白色的,但我不知道设备在测试环境中的行为。 You'd also have to
dev.off()
after every print and restart cap <- ragg::agg_capture()
for every test, I think.我认为,您还必须在每次打印后进行
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
Created on 2021-01-29 by the reprex package (v0.3.0)由代表 package (v0.3.0) 于 2021 年 1 月 29 日创建
EDIT: You can probably automate the resetting as part of the has_printed()
function, but you'd have to be careful with superassignment (here be dragons).编辑:您可能可以将重置作为
has_printed()
function 的一部分进行自动化,但您必须小心超级赋值(这里是龙)。
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
Created on 2021-01-29 by the reprex package (v0.3.0)由代表 package (v0.3.0) 于 2021 年 1 月 29 日创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.