Martiusweb / asynctest

Enhance the standard unittest package with features for testing asyncio libraries
https://asynctest.readthedocs.org/
Apache License 2.0
309 stars 41 forks source link

How to properly use assertAsyncRaises #143

Open axc450 opened 4 years ago

axc450 commented 4 years ago

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)
axc450 commented 4 years ago

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)
Martiusweb commented 4 years ago

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 true that the doc is very light though, I'll update it.

axc450 commented 4 years ago

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!