I'd like to test that a python 3 coro fails with a particular exception, but this functionality doesn't seem to be implemented.
async with self.assertRaises(TestExceptionType):
await my_func()
as the unit test fails like this:
...
File "/Users/...../tests.py", line 144, in go
async with self.assertRaises(TestExceptionType):
AttributeError: __aexit__
So my question is: should this work? And if not, what's the best way to assert a failing async function?
There are two ways you can use assertRaises: using keyword arguments. Just pass the exception, the callable function and the parameters of the callable function as keyword arguments that will elicit the exception. Make a function call that should raise the exception with a context.
assertRaises(exception, callable, *args, **kwds) Test that an exception (first argument) is raised when a function is called with any positional or keyword arguments. The test passes if the expected exception is raised, is an error if another exception is raised, or fails if no exception is raised.
The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.
Just use classic old good with
around await
call:
with self.assertRaises(TestExceptionType):
await my_func()
It works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With