0
0
Flaskframework~5 mins

Testing routes and responses in Flask

Choose your learning style9 modes available
Introduction

Testing routes and responses helps you check if your web app pages work correctly. It makes sure users get the right pages and messages.

You want to check if a webpage loads without errors.
You want to confirm a form submission returns the expected message.
You want to verify that a URL returns the correct status code like 200 or 404.
You want to test if redirects happen properly after actions.
You want to catch bugs early before users see them.
Syntax
Flask
with app.test_client() as client:
    response = client.get('/your-route')
    assert response.status_code == 200
    assert b'Expected content' in response.data

Use app.test_client() to simulate requests without running the server.

Response data is bytes, so compare with b'string'.

Examples
Check if the home page loads successfully with status code 200.
Flask
with app.test_client() as client:
    response = client.get('/')
    assert response.status_code == 200
Test a POST request to '/submit' and check if the response contains 'Thank you'.
Flask
with app.test_client() as client:
    response = client.post('/submit', data={'name': 'Alice'})
    assert b'Thank you' in response.data
Verify that a missing page returns a 404 status code.
Flask
with app.test_client() as client:
    response = client.get('/not-found')
    assert response.status_code == 404
Sample Program

This Flask app has two routes: a home page and a greeting page that accepts a name via POST. The test client simulates requests to check the status codes and response texts.

Flask
from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the home page!'

@app.route('/greet', methods=['POST'])
def greet():
    name = request.form.get('name', 'Guest')
    return f'Hello, {name}!'

# Testing routes
if __name__ == '__main__':
    with app.test_client() as client:
        # Test GET /
        response = client.get('/')
        print('GET / status:', response.status_code)
        print('GET / data:', response.data.decode())

        # Test POST /greet
        response = client.post('/greet', data={'name': 'Alice'})
        print('POST /greet status:', response.status_code)
        print('POST /greet data:', response.data.decode())
OutputSuccess
Important Notes

Always decode response.data from bytes to string for easy reading.

Use assertions in real tests to automate checking instead of print statements.

Testing routes helps catch errors before users do.

Summary

Testing routes checks if your web pages respond correctly.

Use app.test_client() to simulate requests without running the server.

Check status codes and response content to verify behavior.