r-lib / testthat

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

How to handle quit in tested method #1905

Closed alexander793 closed 10 months ago

alexander793 commented 10 months ago

Hi there, I have some methods that return a certain error code with quit(status = error_code) and I would like to test that these methods return exactly the expected codes.\ When running such a method inside a testthat test, the R terminal quits.

Is there an expect-method to test that a method returns a certain exit code?

Example: To be tested method bar in file foo.R

bar <- function() {
  print("Do something...")
  quit(status = 1)
}

Desired Test:

testthat("bar returns exit code 1", {
  expect_quit_status(bar(), 1)
})
hadley commented 10 months ago

I'd strongly recommend against calling quit() in a function since this is rather hostile to your user. If you really do want to do this, then you could use local_mocked_binding() to temporarily make quit() do something other than quitting.