【问题标题】:Test saving ggplots测试保存ggplots
【发布时间】:2021-01-09 15:31:09
【问题描述】:

我正在为 ggplots 创建一堆测试。我包括检查标签、输出对象是否为 ggplot 等内容。但我不知道如何测试该图是否使用testthatggsave 保存。你知道怎么做吗?

【问题讨论】:

  • help("file.exists")?
  • 这是一个很好的提示!该解决方案的缺点是我必须提供文件名。到目前为止,我的文件正在保存,因此在测试时执行此操作非常复杂。您是否有其他不包括文件名的想法? ;))
  • 测试是否已保存意味着测试特定文件是否存在。我不明白如何在不使用文件名的情况下轻松做到这一点。也许在保存操作之前和之后检查目录中的图形(例如 png)文件的数量?我认为这不是最理想的。

标签: r unit-testing ggplot2 testthat


【解决方案1】:

这是一种基于文件大小的测试方法。如果文件不存在,则为 NA,如果文件存在,则应为 > 0。

library(testthat)
library(ggplot2)

test_that("plot is saved to file", {
  file <- tempfile(fileext = ".png")
  expect_equal(file.size(file), NA_real_)
  
  plot <- ggplot(mtcars, aes(wt, mpg)) +
    geom_point()
  
  ggsave(file, plot, "png")
  
  expect_true(file.size(file) > 0)
  
  unlink(file)
})

【讨论】:

    猜你喜欢
    • 2014-11-19
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 2016-09-29
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多