Search code examples
rtestinginfinite-loop

How can I test an infinite loop bug in R


I have a bug in my R code that causes an infinite loop. I'd like to write a test that checks I have fixed this bug.

foo <- function () {
  while (TRUE) sleep(1) # oops!
}

# I want something like:
expect_completes_within(foo(), seconds = 10)

Is there any existing solution? Is there a way to interrupt execution and throw an error after a given time?


Solution

  • R.utils::withTimeout(foo(), timeout = 10) # Stop foo() after 10 seconds.
    

    Solution has already been found here, where also code in base R has been provided.