Skip to content

A function that produces both output and error #80

@otoomet

Description

@otoomet

Consider the function:

root <- function(x) {
   if(x < 0) {
      cat("You cannot compute root of such numbers\n")
      print(x)
      stop("Root of negative number")
   }
   sqrt(x)
}

What is the best way to test the error behavior in such a function?

  • If I do tinytest::expect_error(root(-2)) the test passes but I also get output on screen. I'd like the tests to run with no clutter.
  • If I test output tinytest::expect_output(root(-2)) I get an error
  • If I wrap error in output tinytest::expect_stdout(tinytest::expect_error(root(-2))) I am not quite sure what I am testing, the test still passes if I remove stop.

While I can easily put the value inside the error message in this example, it may be more tricky with complex object with multi-line printout. Is it considered a good habit that complete output of error message should be spit out by stop itself, and not complemented with ordinary printing?

Thoughts/suggestions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions