r-lib / testthat

An R 📦 to make testing 😀
https://testthat.r-lib.org
Other
868 stars 313 forks source link

Support compressed snapshot files #1949

Open MLopez-Ibanez opened 2 months ago

MLopez-Ibanez commented 2 months ago

I would like to store my snapshot files compressed with .xz, so it would be great to have something like compare_file_text_compressed.

This is what I have implemented:

compare_file_text_compressed <- function(old, new)
{
  if (compare_file_binary(old, new))
    return(TRUE)
  old <- base::readLines(withr::local_connection(gzfile(old, open = "r")), warn = FALSE)
  new <- base::readLines(withr::local_connection(gzfile(new, open = "r")), warn = FALSE)
  identical(old, new)
}

save_csv_xz <- function(code, pattern)
{
  path <- tempfile(fileext = ".csv.xz")
  res <- code
  write.table(file = withr::local_connection(xzfile(path, "w")),
    res, row.names = FALSE, col.names=FALSE, sep=",")
  path
}

expect_snapshot_csv_xz <- function(name, code)
{
  # skip_on_ci() # Skip for now until we implement this: https://github.com/tidyverse/ggplot2/blob/main/tests/testthat/helper-vdiffr.R
  name <- paste0(name, ".csv.xz")
  # Announce the file before touching `code`. This way, if `code`
  # unexpectedly fails or skips, testthat will not auto-delete the
  # corresponding snapshot file.
  testthat::announce_snapshot_file(name = name)
  path <- save_csv_xz(code)
  testthat::expect_snapshot_file(path, name = name, compare = compare_file_text_compressed)
}