Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to properly use assertAsyncRaises #143

Open
axc450 opened this issue Nov 8, 2019 · 3 comments
Open

How to properly use assertAsyncRaises #143

axc450 opened this issue Nov 8, 2019 · 3 comments

Comments

@axc450
Copy link

axc450 commented Nov 8, 2019

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
Copy link
Author

axc450 commented Nov 8, 2019

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
Copy link
Owner

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.

@axc450
Copy link
Author

axc450 commented Nov 8, 2019

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants