Cleaning up temporary files after testing not working as expected

Hi,

The setup is that I am trying to test an R package which requires another external software to be installed and running in the shell. I am downloading the latest software from Github in tests/testthat/setup.R so that it runs once for all tests, and then using a helper function in tests/testthat/helper-oms.R to execute the command in the shell for each test (and kill the process once each test ends).

I am trying to follow the advice from the testthat documentation here: Test fixtures • testthat

While I debug, I am downloading the files to my desktop, but eventually I will use tempdir() instead.

In general, this is working, however the code withr::defer(unlink(oms_path), teardown_env()) in setup.R is not removing the file at oms_path after all tests complete and the following message is produced in the Build pane: No deferred expressions to run. Any idea why the unlinking isn't working to cleanup files?

# setup.R
local_install_openmpp <- function() {
  url <- 'https://github.com/openmpp/main/releases/latest/download/openmpp_mac_arm64_20241226.tar.gz'
  file <- fs::path_file(url)
  dir <- '/Users/matt/Desktop/'
  path <- paste(dir, file, sep = '/')
  download.file(url, path)
  untar(path, exdir = dir)
  unlink(path)
  new_path <- fs::path_ext_remove(fs::path_ext_remove(path))
  new_path
}

oms_path <- local_install_openmpp()

withr::defer(unlink(oms_path, recursive = TRUE), teardown_env())
# helper-oms.R
local_initiate_oms <- function(path) {
  pid <-
    withr::with_dir(
      new = path,
      code = sys::exec_background(cmd = './bin/oms', std_out = FALSE)
    )
  Sys.sleep(1)
  withr::defer_parent(tools::pskill(pid))
  pid
}
# test-connections.R
test_that("API connection succeeds", {
  local_initiate_oms(oms_path)
  use_OpenMpp_local()
  expect_no_error(get_models())
  expect_no_error(get_models_list())
})

FWIW, replacing my entire setup.R with the example shown at the link above doesn't work either...

# setup.R
# Run before any test
write.csv(mtcars, "/Users/matt/Desktop/mtcars.csv")

# Run after all tests
withr::defer(unlink("/Users/matt/Desktop/mtcars.csv"), teardown_env())

This works fine for me. Can you create a reproducible example? E.g. put your package in public repository and show the commands to run to reproduce your issue?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.