Consider a FastAPI test setup where a client fixture is defined with different scopes. What happens when the fixture scope is set to function versus module?
import pytest from fastapi.testclient import TestClient from myapp import app @pytest.fixture(scope="function") def client(): return TestClient(app) # In tests, client is used to make requests
Think about how pytest fixture scopes control the lifetime of the fixture object.
Setting scope='function' means pytest creates a new fixture instance for each test function, ensuring no shared state. Setting scope='module' creates one instance per module, so tests share the same client.
Given this fixture and test code, what will be the value of counter['count'] after running both tests?
import pytest counter = {'count': 0} @pytest.fixture(scope='module') def shared_counter(): counter['count'] += 1 return counter def test_one(shared_counter): assert shared_counter['count'] == 1 def test_two(shared_counter): assert shared_counter['count'] == 1
Remember that scope='module' means the fixture runs once per module, so the increment happens once.
The fixture runs once per module, so counter['count'] increments once before tests run. Both tests share the same dictionary, so after both tests, the count remains 1 during tests but after both tests, the value is 1. However, since the fixture runs once, the count increments once only. The tests expect 1, so they pass. The final value after tests is 1.
Identify the fixture definition that will cause a syntax error when used in FastAPI tests with pytest.
Check the function definition syntax carefully.
Option C is missing parentheses in the function definition (def client:), which causes a syntax error. All other options have correct syntax.
Examine the fixture below. Why do tests using this fixture share state unexpectedly?
import pytest class Resource: def __init__(self): self.value = 0 resource = Resource() @pytest.fixture(scope='module') def shared_resource(): return resource def test_a(shared_resource): shared_resource.value += 1 assert shared_resource.value == 1 def test_b(shared_resource): assert shared_resource.value == 0
Think about how returning a global object affects test isolation.
The fixture returns the same global resource object for all tests in the module. When test_a modifies value, test_b sees the changed value, causing unexpected shared state.
In FastAPI testing, you want to organize your database fixtures to ensure each test runs with a clean state but also keep tests fast. Which approach best balances isolation and performance?
Consider how transaction rollbacks can speed up tests while keeping data isolated.
Using a module scoped fixture to create the test database once and then rolling back transactions after each test keeps tests isolated and fast. Creating a fresh database per test (function scope) is slow. Session scope without cleanup causes data leaks. Reusing connections without cleanup causes flaky tests.