Skip to content
Foxipa
Code Completion 4 Challenges

Complete the asynchronous unittest code

Practise coroutine test methods, awaited exception checks, async cleanup, and await-specific mock assertions.

Intermediate ~10 min read

Challenge 1

Create an async test method and assert the awaited function result.

python Your answer
import unittest

async def fetch_total():
    return 12

class TestTotal(unittest.IsolatedAsyncioTestCase):
    

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer

Challenge 2

Await the invalid operation inside the expected-exception context.

python Your answer
import unittest

async def parse_value(text):
    raise ValueError("invalid")

class TestParse(unittest.IsolatedAsyncioTestCase):
    async def test_invalid(self):
        with self.assertRaises(ValueError):
            

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer

Challenge 3

Register the async close method so the test framework runs it during cleanup.

python Your answer
import unittest

class Session:
    def __init__(self):
        self.closed = False

    async def close(self):
        self.closed = True

class TestSession(unittest.IsolatedAsyncioTestCase):
    async def asyncSetUp(self):
        self.session = Session()
        

    async def test_session_is_open(self):
        self.assertFalse(self.session.closed)

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer

Challenge 4

Verify that the asynchronous reader was awaited exactly once with the user ID.

python Your answer
import unittest
from unittest.mock import AsyncMock

async def load_profile(reader, user_id):
    return await reader(user_id)

class TestProfile(unittest.IsolatedAsyncioTestCase):
    async def test_reader(self):
        reader = AsyncMock(return_value={"name": "Ada"})
        profile = await load_profile(reader, 7)
        self.assertEqual(profile, {"name": "Ada"})
        

if __name__ == "__main__":
    unittest.main(argv=["exercise"], exit=False)

Press Ctrl⌘Enter to check your answer