Merck/r2rtf

Blank `Rplots.pdf` generated when running snapshot tests interactively from RStudio

nanxstats opened this issue · 4 comments

To reproduce the issue:

usethis::create_package("zzz/")
usethis::use_testthat()

Run usethis::use_r("myfun") and put this function into it:

#' @export
myfun <- function(path) {
  head(datasets::iris) |>
    r2rtf::rtf_body() |>
    r2rtf::rtf_encode() |>
    r2rtf::write_rtf(file = path)
}

Run usethis::use_test("myfun") to create this test:

test_that("myfun snapshot", {
  path <- tempfile(fileext = ".rtf")
  myfun(path)

  local_edition(3)
  expect_snapshot_file(path, "myfun.rtf")
})

Run devtools::document() and devtools::load_all().

Clicking the "Run Tests" button or the "Test" button in the Build panel in RStudio will generate a blank, redundant tests/testthat/Rplots.pdf, while no such Rplots.pdf is generated when running devtools::test() or devtools::test_active_file() in the R console.

Reproduced under macOS, Windows, and Posit Cloud.

The culprit is in these two places where graphics::par() and graphics::strwidth() were called:

text_cex <- attr(tbl, "text_font_size") / graphics::par("ps")

r2rtf/R/rtf_strwidth.R

Lines 110 to 115 in 307c112

x$width <- graphics::strwidth(x$text,
units = "inches",
cex = x$cex[1],
font = x$font[1],
family = as.character(x$family[1])
)

By replacing them both with a constant number, the problem goes away. Looks like by calling these functions in graphics, a PDF device is somehow triggered when running the tests in RStudio interactively.

This unit test using graphics::strwidth() also needs side effect isolation, otherwise, Rplots.pdf will be generated:

size8italic <- round(graphics::strwidth("This is a long sentence",
units = "inches",
cex = 2 / 3,
font = 3,
family = "Times"
), 5)
bold <- round(graphics::strwidth("third",
units = "inches",
cex = 2 / 3,
font = 2,
family = "Times"
), 5)

It seems it only happens while running unit test. I did not see the RPlots.pdf is created by running the code above in an interactive R sessions.

Guess a graphic device is initiated when devtools::test() detected graphics package is used. As I do see a RPlots.pdf file is created if we call pdf().

I am OK to live with it.

I should have been clearer - this only happens when you click the "Run Tests" button above the code editor or the "Test" button in the Build panel in RStudio, but not when you send the code into the R console.

Regardless, I'd say it will be productive to get this fixed, because every package that have tests with underlying code using r2rtf will get this unavoidable side effect - and it can be confusing and annoying. For example, see previous discussions:

Merck/metalite.ae#75
Merck/metalite.ae#73