0
0
Flaskframework~30 mins

Test fixtures with pytest in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Test fixtures with pytest in Flask
📖 Scenario: You are building a small Flask web app that has a single route returning a greeting message. You want to write tests for this app using pytest. To make your tests clean and reusable, you will use pytest fixtures to set up the Flask test client.
🎯 Goal: Create a Flask app and write a pytest fixture that provides a test client. Then write a test function that uses this fixture to check the greeting route returns the expected message.
📋 What You'll Learn
Create a Flask app with a route /hello that returns 'Hello, Flask!'
Write a pytest fixture named client that sets up the Flask test client
Write a test function named test_hello that uses the client fixture
In the test function, send a GET request to /hello and assert the response data is 'Hello, Flask!'
💡 Why This Matters
🌍 Real World
Using pytest fixtures to set up test clients is common in web development to write clean, reusable tests for Flask apps.
💼 Career
Understanding how to write tests with fixtures is important for backend developers to ensure code quality and maintainability.
Progress0 / 4 steps
1
Create the Flask app with a /hello route
Create a Flask app named app and add a route /hello that returns the string 'Hello, Flask!'.
Flask
Need a hint?

Use Flask(__name__) to create the app. Use @app.route('/hello') to define the route.

2
Add a pytest fixture named client for the test client
Import pytest and create a fixture named client that returns app.test_client(). Use the @pytest.fixture decorator.
Flask
Need a hint?

Use @pytest.fixture above the client function. Return app.test_client() inside it.

3
Write a test function using the client fixture
Write a test function named test_hello that takes client as a parameter. Inside, send a GET request to /hello using client.get and store the response in response.
Flask
Need a hint?

Define test_hello with client as argument. Use client.get('/hello') to get the response.

4
Assert the response data is 'Hello, Flask!'
In the test_hello function, add an assertion that response.data equals b'Hello, Flask!' (bytes literal).
Flask
Need a hint?

Use assert response.data == b'Hello, Flask!' to check the response content.