Consider this Flask app and test client code snippet. What will be the printed output?
from flask import Flask, jsonify app = Flask(__name__) @app.route('/hello') def hello(): return jsonify(message='Hello, Test!') with app.test_client() as client: response = client.get('/hello') print(response.json)
Check what response.json returns when the endpoint returns a JSON response.
The response.json property parses the JSON response body and returns a Python dictionary. The endpoint returns {'message': 'Hello, Test!'}, so that is printed.
Given this Flask app and test client POST request, what is the value of response.status_code?
from flask import Flask, request app = Flask(__name__) @app.route('/submit', methods=['POST']) def submit(): data = request.json if data and 'name' in data: return 'Received', 201 return 'Bad Request', 400 with app.test_client() as client: response = client.post('/submit', json={'name': 'Alice'}) print(response.status_code)
Look at the return status code when the JSON contains the 'name' key.
The route returns status code 201 when the JSON contains the 'name' key. The test client sends {'name': 'Alice'}, so the status code is 201.
Examine this Flask test client code. Why does it raise an error?
from flask import Flask app = Flask(__name__) @app.route('/test') def test(): return 'OK' with app.test_client() as client: response = client.post('/test') print(response.status_code)
Check the allowed HTTP methods for the route.
The route '/test' only allows GET requests by default. Sending a POST request causes a 405 Method Not Allowed error.
Choose the correct code snippet to send a PUT request with JSON data {'id': 1} using Flask's test client.
from flask import Flask app = Flask(__name__) with app.test_client() as client: # Choose the correct option to send PUT with JSON pass
Use the test client parameter that automatically serializes JSON.
The json parameter automatically serializes the dictionary and sets the content type. Other options either pass a string incorrectly or pass data without serialization.
When using Flask's app.test_client() to simulate requests, which statement about the application context is true?
Think about how Flask manages context during simulated requests.
Flask's test client automatically manages the app context for each request, pushing it before and popping it after, allowing access to flask.g and current_app during the request.