Test a function throws an error

When writing tests for a package, one might want to test that a function with a given invalid input throws an error as expected. Looking at UnitTest module, I didn't find any assertThrows function. What is the idiomatic way of testing this?

Off the top of my head, I would try something like this

use UnitTest;
use UnitTest.TestError; // needed to define the custom AssertionError

proc fun(x : int) throws {
  if x > 0 then throw new IllegalArgumentError("received input: " + x : string);
  else return 3;
}


proc testFun(test : borrowed Test) throws {
  try {
    fun(3);
    throw new owned AssertionError("function was expected to throw an error");
  } catch e: IllegalArgumentError {
    test.assertEqual(e.message(), "received input: 3");
  }
}

UnitTest.main();

comments? suggestions on other approaches?

Hi Luca —

I'm not expert in the UnitTest package, but with a quick check, I think you're correct that there is not existing functionality for this. This issue seems to confirm that: Method for asserting Errors in UnitTest · Issue #17277 · chapel-lang/chapel · GitHub. Note that this package module was developed as part of a Google Summer of Code project, and that has not seen a lot of enhancements since then.

My intuition for workarounds would be similar to what you've sketched out here: to use a manual try...catch within a test routine. I'd be curious what your results are, and it might be worthwhile to post them to that issue as well (and give it an upvote if you like the direction being proposed there).

-Brad

Thanks for the pointer! I commented on the github issue