Bird
Raised Fist0
Flaskframework~20 mins

Test fixtures with pytest in Flask - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Pytest Fixture Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What is the output when using a pytest fixture to create a Flask test client?

Given the following pytest fixture and test, what will be the output when running the test?

Flask
import pytest
from flask import Flask

@pytest.fixture
def client():
    app = Flask(__name__)

    @app.route('/')
    def home():
        return 'Hello, Flask!'

    with app.test_client() as client:
        yield client

def test_home(client):
    response = client.get('/')
    return response.data.decode()
A"Hello, Flask!"
B"<html><body>Hello, Flask!</body></html>"
CTypeError: 'Response' object is not callable
D"404 Not Found"
Attempts:
2 left
💡 Hint

Think about what the route returns and how the test client fetches it.

❓ state_output
intermediate
2:00remaining
What is the value of the counter after two tests using a session-scoped fixture?

Consider this pytest fixture with session scope and two tests using it. What is the final value of counter['count'] after both tests run?

Flask
import pytest

counter = {'count': 0}

@pytest.fixture(scope='session')
def count_fixture():
    counter['count'] += 1
    yield
    counter['count'] += 1

def test_one(count_fixture):
    pass

def test_two(count_fixture):
    pass
A1
B2
C3
D4
Attempts:
2 left
💡 Hint

Remember session scope means the fixture runs once per test session.

📝 Syntax
advanced
2:00remaining
Which pytest fixture code will cause a SyntaxError?

Identify which fixture code snippet will cause a syntax error when run.

A
import pytest

@pytest.fixture
def sample():
    return [x for x in range(5) if x % 2 != 0]
B
import pytest

@pytest.fixture
def sample():
    return [x for x in range(5) if x % 2 == 0]
C
import pytest

@pytest.fixture
def sample():
    return [x for x in range(5)]
D
import pytest

@pytest.fixture
def sample():
    return [x for x in range(5) if x % 2 = 0]
Attempts:
2 left
💡 Hint

Look carefully at the condition inside the list comprehension.

🔧 Debug
advanced
2:00remaining
Why does this pytest fixture cause a test to fail with AttributeError?

Given this fixture and test, why does the test fail with AttributeError: 'NoneType' object has no attribute 'get'?

Flask
import pytest
from flask import Flask

@pytest.fixture
def client():
    app = Flask(__name__)

    @app.route('/')
    def home():
        return 'Hi'

    client = app.test_client()
    return client

def test_home(client):
    response = client.get('/')
    assert response.data == b'Hi'
AThe test client is not created properly with app.test_client().
BThe route '/' is missing a return statement.
CThe fixture does not return or yield the client, so test receives None.
DThe test function is missing the @pytest.mark.usefixtures decorator.
Attempts:
2 left
💡 Hint

Check what the fixture returns or yields.

🧠 Conceptual
expert
2:00remaining
How does pytest fixture scope affect resource setup and teardown in Flask testing?

Consider a Flask app tested with pytest fixtures of different scopes: function, module, and session. Which statement best describes how fixture scope affects resource setup and teardown?

AFunction scope fixtures run setup and teardown once per test function, module scope once per module, and session scope once per entire test session.
BAll fixture scopes run setup and teardown once per test function regardless of scope.
CModule scope fixtures run setup and teardown once per test function, function scope once per module, and session scope once per test function.
DSession scope fixtures run setup and teardown once per test function, module scope once per session, and function scope once per module.
Attempts:
2 left
💡 Hint

Think about how often you want to create and destroy resources during testing.

Practice

(1/5)
1. What is the main purpose of a fixture in pytest when testing a Flask app?
easy
A. To write the main application logic
B. To handle user input in the Flask app
C. To set up and tear down resources needed for tests automatically
D. To deploy the Flask app to a server

Solution

  1. Step 1: Understand what fixtures do in pytest

    Fixtures prepare the environment for tests by setting up resources before tests run and cleaning them after.
  2. Step 2: Identify the role of fixtures in Flask testing

    Fixtures help create test clients, databases, or other resources needed for Flask tests automatically.
  3. Final Answer:

    To set up and tear down resources needed for tests automatically -> Option C
  4. Quick Check:

    Fixtures = setup and cleanup [OK]
Hint: Fixtures prepare test resources automatically [OK]
Common Mistakes:
  • Confusing fixtures with application code
  • Thinking fixtures handle user input
  • Assuming fixtures deploy the app
2. Which of the following is the correct way to define a pytest fixture for a Flask test client?
easy
A. @pytest.fixture def client(): app = Flask(__name__) yield app.test_client()
B. @pytest.fixture def client(): app = Flask(__name__) app.test_client()
C. def client(): app = Flask(__name__) yield app.test_client()
D. @pytest.fixture def client(): app = Flask(__name__) return app

Solution

  1. Step 1: Check the use of @pytest.fixture decorator

    The @pytest.fixture decorator is required to mark a fixture. One option lacks it.
  2. Step 2: Identify correct use of yield for setup and teardown

    @pytest.fixture def client(): app = Flask(__name__) yield app.test_client() uses yield to provide the test client and allows cleanup after tests, which is best practice.
  3. Final Answer:

    @pytest.fixture\ndef client():\n app = Flask(__name__)\n yield app.test_client() -> Option A
  4. Quick Check:

    Use @pytest.fixture and yield for fixtures [OK]
Hint: Use @pytest.fixture and yield to define fixtures [OK]
Common Mistakes:
  • Omitting @pytest.fixture decorator
  • Returning instead of yielding
  • Not yielding or returning the test client
3. Given this fixture and test code, what will be printed when running the test?
@pytest.fixture
def sample():
    print('Setup')
    yield 'data'
    print('Teardown')

def test_example(sample):
    print(f'Test received: {sample}')
medium
A. Setup\nTest received: data\nTeardown
B. Test received: data\nSetup\nTeardown
C. Setup\nTeardown\nTest received: data
D. Test received: data

Solution

  1. Step 1: Understand fixture execution order

    Before the test runs, the fixture prints 'Setup', then yields 'data' to the test.
  2. Step 2: Analyze test function output and fixture teardown

    The test prints 'Test received: data'. After test finishes, fixture resumes and prints 'Teardown'.
  3. Final Answer:

    Setup\nTest received: data\nTeardown -> Option A
  4. Quick Check:

    Fixture setup -> test -> fixture teardown [OK]
Hint: Fixture prints before yield, teardown prints after [OK]
Common Mistakes:
  • Assuming teardown runs before test
  • Ignoring yield pauses fixture
  • Thinking test runs before setup
4. Identify the error in this pytest fixture code for a Flask app:
@pytest.fixture
def client():
    app = Flask(__name__)
    client = app.test_client()
    return client
    print('Cleanup done')
medium
A. Fixture must use 'yield' instead of 'return' always
B. Missing '@pytest.fixture' decorator
C. 'app.test_client()' is not a valid method
D. The 'print' statement after 'return' will never execute

Solution

  1. Step 1: Check code after return statement

    Code after 'return' is unreachable, so 'print' will never run.
  2. Step 2: Confirm other parts are correct

    The decorator is present, 'app.test_client()' is valid, and 'return' is allowed but limits cleanup.
  3. Final Answer:

    The 'print' statement after 'return' will never execute -> Option D
  4. Quick Check:

    Code after return is unreachable [OK]
Hint: Code after return is ignored; use yield for cleanup [OK]
Common Mistakes:
  • Thinking print runs after return
  • Assuming return disallows fixture
  • Confusing method names
5. You want to create a fixture that sets up a temporary database for Flask tests and ensures it is cleaned up after all tests in the module run. Which fixture scope and structure is best?
hard
A. @pytest.fixture(scope='function') def temp_db(): db = setup_temp_db() yield db teardown_temp_db(db)
B. @pytest.fixture(scope='module') def temp_db(): db = setup_temp_db() yield db teardown_temp_db(db)
C. @pytest.fixture(scope='session') def temp_db(): db = setup_temp_db() return db
D. @pytest.fixture(scope='module') def temp_db(): db = setup_temp_db() return db teardown_temp_db(db)

Solution

  1. Step 1: Choose fixture scope for module-wide setup

    Scope 'module' runs once per module, ideal for shared DB setup across tests.
  2. Step 2: Use yield to allow teardown after all tests

    Yield pauses fixture to run tests, then runs teardown after all tests complete.
  3. Final Answer:

    @pytest.fixture(scope='module')\ndef temp_db():\n db = setup_temp_db()\n yield db\n teardown_temp_db(db) -> Option B
  4. Quick Check:

    Module scope + yield for setup and cleanup [OK]
Hint: Use scope='module' and yield for setup/cleanup [OK]
Common Mistakes:
  • Using function scope causes repeated setup
  • Returning without yield skips cleanup
  • Placing cleanup code after return
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard