Introduction
Testing helps make sure your Flask app works correctly. It finds problems early so users have a better experience.
Testing helps make sure your Flask app works correctly. It finds problems early so users have a better experience.
from flask import Flask import unittest class MyTestCase(unittest.TestCase): def setUp(self): self.app = Flask(__name__).test_client() def test_home(self): response = self.app.get('/') self.assertEqual(response.status_code, 200)
Use unittest.TestCase to create test classes.
setUp runs before each test to prepare the app.
def test_home(self): response = self.app.get('/') self.assertEqual(response.status_code, 200)
def test_404(self): response = self.app.get('/notfound') self.assertEqual(response.status_code, 404)
This test checks if the home page returns status 200 and contains the welcome message.
from flask import Flask import unittest app = Flask(__name__) @app.route('/') def home(): return 'Welcome to Flask!' class FlaskTestCase(unittest.TestCase): def setUp(self): self.app = app.test_client() def test_home_page(self): response = self.app.get('/') self.assertEqual(response.status_code, 200) self.assertIn(b'Welcome to Flask!', response.data) if __name__ == '__main__': unittest.main()
Tests help catch errors early and save time fixing bugs later.
Write small tests for each part of your app to find problems easily.
Run tests often while coding to keep your app working well.
Testing makes your Flask app reliable and user-friendly.
Use unittest to write simple tests for routes and responses.
Run tests regularly to catch bugs before users do.
test_client() on the app instance to create a test client.app.test_client(), which is the correct method.client = app.test_client()
response = client.get('/')
print(response.status_code)response.status_code will be 200.client = app.test_client()
response = client.get('/login')
assert response.status == 200status_code to hold the HTTP status number, not status.response.status_code == 200 to be valid.response.status_code == 302.Pass the test and this pattern moves unknown