How to Test Flask Routes and Handle 404 Errors
Get the project source code below, and follow along with the lesson material.
Download Project Source CodeTo set up the project on your local machine, please follow the directions provided in the README.md
file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.
Testing
In the last chapter we created a single test the model in tests/test_product.py
. We can go in and add functional tests to ensure that pages we've added work as expected as well as one for our handling of 404s.
Since we'll often be creating a new book, in this test suite we have turned that logic into a function (called sample_book
), and use it as a fixture in our test suites.
from yumroad.models import db, Product
@pytest.fixture
def sample_book(name="Sherlock Homes", description="a house hunting real estate agent"):
We've already seen some testing of the model, but we can add in testing for our routes to ensure each of the pages load and that the 404s work correctly by adding in three more tests. Here is the full test file once we are done.
from flask import url_for
import pytest
This lesson preview is part of the Fullstack Flask: Build a Complete SaaS App with Flask course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.
Get unlimited access to Fullstack Flask: Build a Complete SaaS App with Flask, plus 70+ \newline books, guides and courses with the \newline Pro subscription.