Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you use self.assertRaises as an async context manager?

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?

like image 322
acrophobia Avatar asked Sep 14 '16 13:09

acrophobia


People also ask

How do you use self assertRaises in Python?

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.

How do you handle exceptions in unit test Python?

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.

How do you test try and except in Python?

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.


1 Answers

Just use classic old good with around await call:

with self.assertRaises(TestExceptionType):
    await my_func()

It works.

like image 179
Andrew Svetlov Avatar answered Sep 21 '22 18:09

Andrew Svetlov