How asynctest.TestCase.setUp can be overridden by both async and sync methods?

232 views Asked by At

I am writing a unit test that inherits from asynctest.TestCase and would like to create some mixins that perform an asynchronous setUp before each test case:

import asynctest

class Mixin1(object):
    async def setUp(self): 
        await super(Mixin1, self).setUp()

class MyTest(Mixin1, asynctest.TestCase):
    async def setUp(self): 
        await super(MyTest, self).setUp()

The problem I am seeing is that Mixin1 ends up invoking asynctest.TestCase.setUp which happens to be a non-async method and we're getting:

TypeError: object NoneType can't be used in 'await' expression

Obviously, I can just change Mixin1 to make a blocking call to setUp, but then it would fail if I introduce a second mixin that is async.

I ended up writing all my setUp calls like this, but it feels there must be a better way:

async def setUp(self):
    # do stuff
    setUp = super(Mixin1, self).setUp
    if asyncio.iscoroutine():
        await setUp()
    else:
        setUp()

Is there a better way to chain the setUp calls?

1

There are 1 answers

0
WBAR On

I would like propose a little fix to your solution which makes it working:

async def setUp(self):
    # do stuff
    setUp = super().setUp
    if asyncio.iscoroutinefunction(setUp):
        await setUp()
    else:
        setUp()