Bird
Raised Fist0
PyTesttesting~20 mins

Async fixtures (pytest-asyncio) - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Async Fixture Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of async fixture usage in pytest
What is the output of running this pytest test with an async fixture?
PyTest
import pytest
import asyncio

@pytest.fixture
async def async_resource():
    await asyncio.sleep(0.1)
    return 'resource_ready'

@pytest.mark.asyncio
async def test_async_fixture(async_resource):
    assert async_resource == 'resource_ready'
    print(async_resource)
ATest fails with AssertionError
BTest passes and prints 'resource_ready'
CTest raises RuntimeError due to event loop
DTest is skipped due to missing marker
Attempts:
2 left
💡 Hint
Remember that pytest-asyncio supports async fixtures and test functions with the @pytest.mark.asyncio decorator.
assertion
intermediate
1:30remaining
Correct assertion for async fixture return value
Given an async fixture that returns a dictionary {'status': 'ok', 'code': 200}, which assertion correctly verifies the 'code' key in a pytest async test?
PyTest
import pytest

@pytest.fixture
async def api_response():
    return {'status': 'ok', 'code': 200}

@pytest.mark.asyncio
async def test_api_code(api_response):
    # Which assertion is correct here?
    pass
Aassert api_response['code'] == 200
Bassert api_response['code'] != 200
Cassert api_response.get('code') is '200'
Dassert api_response.code == 200
Attempts:
2 left
💡 Hint
Dictionaries use bracket notation to access keys, and '==' compares values correctly.
🔧 Debug
advanced
2:00remaining
Identify the cause of RuntimeError in async fixture test
Why does this pytest async test raise RuntimeError: This event loop is already running?
PyTest
import pytest
import asyncio

@pytest.fixture
async def async_data():
    await asyncio.sleep(0.1)
    return 42

def test_sync_using_async_fixture(async_data):
    assert async_data == 42
AThe fixture does not return a coroutine
BThe fixture is missing @pytest.mark.asyncio decorator
CThe test function is not async and tries to use an async fixture synchronously
DThe test function is missing a call to asyncio.run()
Attempts:
2 left
💡 Hint
Async fixtures must be used in async test functions or with proper event loop management.
🧠 Conceptual
advanced
1:30remaining
Purpose of async fixtures in pytest-asyncio
What is the main benefit of using async fixtures in pytest-asyncio?
AThey allow setup and teardown code to run asynchronously, improving test performance when dealing with async resources
BThey automatically convert synchronous fixtures to async functions
CThey enable running tests without an event loop
DThey replace the need for mocking in tests
Attempts:
2 left
💡 Hint
Think about why async code needs async setup and cleanup.
framework
expert
2:30remaining
Correct pytest-asyncio fixture and test integration
Which option shows the correct way to define and use an async fixture with pytest-asyncio to test an async function that returns 'done' after a delay?
PyTest
import pytest
import asyncio

async def async_func():
    await asyncio.sleep(0.05)
    return 'done'

# Choose the correct fixture and test code
A
@pytest.fixture
def fixture_func():
    return asyncio.run(async_func())

@pytest.mark.asyncio
def test_func(fixture_func):
    assert fixture_func == 'done'
B
@pytest.fixture
async def fixture_func():
    return async_func()

def test_func(fixture_func):
    assert fixture_func == 'done'
C
@pytest.fixture
async def fixture_func():
    result = async_func()
    return result

@pytest.mark.asyncio
async def test_func(fixture_func):
    assert await fixture_func == 'done'
D
@pytest.fixture
async def fixture_func():
    result = await async_func()
    return result

@pytest.mark.asyncio
async def test_func(fixture_func):
    assert fixture_func == 'done'
Attempts:
2 left
💡 Hint
Async fixtures must await async calls and tests must be async with the marker.

Practice

(1/5)
1. What is the main purpose of using async def in pytest fixtures with pytest-asyncio?
easy
A. To allow the fixture to perform asynchronous setup and cleanup operations
B. To make the fixture run faster by using multiple threads
C. To automatically retry the fixture if it fails
D. To convert the fixture into a synchronous function

Solution

  1. Step 1: Understand async def in pytest fixtures

    Using async def allows the fixture to run asynchronous code, which is necessary for async setup or cleanup tasks.
  2. Step 2: Compare with other options

    Options A, B, and C describe unrelated behaviors: synchronous conversion, threading, retries, which are not the purpose of async def in fixtures.
  3. Final Answer:

    To allow the fixture to perform asynchronous setup and cleanup operations -> Option A
  4. Quick Check:

    async def in fixtures = async setup/cleanup [OK]
Hint: Async fixtures enable async setup and cleanup [OK]
Common Mistakes:
  • Thinking async def makes tests run in parallel
  • Confusing async with threading
  • Assuming async def retries tests automatically
2. Which of the following is the correct way to define an async fixture using pytest-asyncio?
easy
A. async def my_fixture(): yield 'data'
B. def my_fixture(): yield 'data'
C. async def my_fixture(): return 'data'
D. def my_fixture(): return 'data'

Solution

  1. Step 1: Identify async fixture syntax

    Async fixtures must be defined with async def and use yield to allow setup and cleanup.
  2. Step 2: Evaluate options

    async def my_fixture(): yield 'data' correctly uses async def and yield. def my_fixture(): yield 'data' is synchronous. async def my_fixture(): return 'data' uses return which does not support cleanup. def my_fixture(): return 'data' is synchronous and uses return.
  3. Final Answer:

    async def my_fixture(): yield 'data' -> Option A
  4. Quick Check:

    Async fixture = async def + yield [OK]
Hint: Async fixtures use async def and yield, not return [OK]
Common Mistakes:
  • Using return instead of yield in async fixtures
  • Defining fixture without async def
  • Mixing synchronous and asynchronous syntax
3. Given the following code, what will be printed when running the test?
import pytest
import asyncio

@pytest.fixture
async def async_resource():
    print('Setup')
    yield 'resource'
    print('Cleanup')

@pytest.mark.asyncio
def test_example(async_resource):
    print(f'Test using {async_resource}')
medium
A. Test using resource\nSetup\nCleanup
B. Setup\nTest using resource\nCleanup
C. Setup\nCleanup\nTest using resource
D. Test using resource only

Solution

  1. Step 1: Understand async fixture execution order

    The fixture prints 'Setup' before yielding the resource, then the test runs, printing 'Test using resource', and finally the fixture prints 'Cleanup' after the test finishes.
  2. Step 2: Match output sequence

    The output order is 'Setup', then 'Test using resource', then 'Cleanup', matching Setup\nTest using resource\nCleanup.
  3. Final Answer:

    Setup\nTest using resource\nCleanup -> Option B
  4. Quick Check:

    Fixture setup -> test -> fixture cleanup = Setup, Test, Cleanup [OK]
Hint: Fixture prints before yield, cleanup prints after yield [OK]
Common Mistakes:
  • Assuming cleanup runs before test
  • Confusing yield with return
  • Ignoring async execution order
4. What is wrong with this async fixture code?
import pytest

@pytest.fixture
async def resource():
    data = await get_data()
    return data

Assuming get_data() is an async function.
medium
A. Fixture should not call async functions
B. Fixture must not be async if it uses await
C. Fixture must be decorated with @pytest.mark.asyncio
D. Async fixtures must use yield, not return, to allow cleanup

Solution

  1. Step 1: Check async fixture structure

    Async fixtures that need cleanup must use yield to separate setup and teardown phases.
  2. Step 2: Analyze the code

    This fixture uses return, so it cannot perform cleanup after the test. Using yield is required for cleanup.
  3. Final Answer:

    Async fixtures must use yield, not return, to allow cleanup -> Option D
  4. Quick Check:

    Async fixture cleanup requires yield, not return [OK]
Hint: Use yield in async fixtures for cleanup, not return [OK]
Common Mistakes:
  • Using return instead of yield in async fixtures
  • Thinking async fixtures can't await
  • Adding @pytest.mark.asyncio to fixtures instead of tests
5. You want to write an async fixture that opens a database connection before tests and closes it after. Which code snippet correctly implements this using pytest-asyncio?
hard
A. @pytest.fixture async def db_conn(): conn = open_db() yield conn conn.close()
B. async def db_conn(): conn = await open_db() yield conn await conn.close()
C. @pytest.fixture async def db_conn(): conn = await open_db() yield conn await conn.close()
D. @pytest.fixture async def db_conn(): conn = await open_db() return conn

Solution

  1. Step 1: Identify correct fixture decorator and async syntax

    The fixture must be decorated with @pytest.fixture and defined as async def to support async setup and cleanup.
  2. Step 2: Check for proper use of yield and await

    @pytest.fixture async def db_conn(): conn = await open_db() yield conn await conn.close() correctly awaits open_db(), yields the connection, and awaits conn.close() after the test. async def db_conn(): conn = await open_db() yield conn await conn.close() misses the decorator. @pytest.fixture async def db_conn(): conn = open_db() yield conn conn.close() misses awaits. @pytest.fixture async def db_conn(): conn = await open_db() return conn uses return, so no cleanup.
  3. Final Answer:

    @pytest.fixture async def db_conn(): conn = await open_db() yield conn await conn.close() -> Option C
  4. Quick Check:

    Async fixture with @pytest.fixture + async def + yield + await cleanup [OK]
Hint: Always decorate async fixtures with @pytest.fixture and use yield [OK]
Common Mistakes:
  • Forgetting @pytest.fixture decorator
  • Using return instead of yield for cleanup
  • Not awaiting async calls in fixture