Martiusweb/asynctest

How to properly use assertAsyncRaises

Opened this issue · 3 comments

Hi,

Im having a bit of trouble using assertAsyncRaises. I have read the docs and tried various things:

def x(a, b):
    raise ValueError


self.assertRaises(ValueError, x, 1, 2)

Here is how I would usually write a test for the dummy function x.
Using asynctest:

async def x(a, b):
    raise ValueError

# None of the below seem to even run
self.assertAsyncRaises(ValueError, x, 1, 2)
self.assertAsyncRaises(ValueError, x(1, 2))
self.assertAsyncRaises(ValueError, await x(1, 2))
self.assertAsyncRaises(ValueError, lambda y:  x(1, 2))
await self.assertAsyncRaises(ValueError, x, 1, 2)

I would except just the first/last example should work; I would assume it would look something like this under the hood:

async def assertAsyncRaises(self, exception, f, *args, **kwargs):
    with self.assertRaises(exception) as c:
        await f(*args, **kwargs)

Additionally, the below works:

with self.assertRaises(ValueError):
    await x(1, 2)

But this only works when in isolation in its own test.
You cant do something like this:

# Lets just say x() is designed to add 2 numbers

result = await x(1, 2)
self.assertEqual(x, 3)

with self.assertRaises(ValueError):
    await x(None, 2)

Hello,

self.assertAsyncRaises accepts an awaitable as argument so you should write:

await self.assertAsyncRaises(ValueError, x(1, 2))

It's actually a very simple shorthand: https://asynctest.readthedocs.io/en/latest/_modules/asynctest/case.html#TestCase.assertAsyncRaises

assertAsyncRaises don't accept the coroutine function + args for several reasons:

  • it's not necessary, since passing the coroutine instance is sufficient,
  • we can pass any awaitable (an object, a future, etc), and the signature is the same.

It's true that the doc is very light though, I'll update it.

Thanks!
I also had an issue with my tests not properly resetting my environment, so I think that may have caused some of the confusion. Ignore anything here that makes no sense 🙂

I think just an example added to the docs would be great!