Exercise: Concert Tickets API Tests
Write the TestClient tests for Starlight Stage's working tickets API, from its shows to buying tickets, its errors and refunds, and prove they're good by catching three bugs the check plants in copies of the API.
Journeyman · FastAPI · REST API · Updated
Starlight Stage's tickets API works today. Fans can list the shows, buy 1 to 8 tickets at a time, get a clear error when a show is sold out, and get a refund. Nobody wrote tests for it, though, so the next person who changes it could break ticket sales and not find out until a fan does. This time the API is finished and the tests are yours to write. And to show your tests are worth having, a check plants three real bugs in copies of the API, one at a time, and tells you whether your tests caught each one.
Get the exercise code
Open this lesson's GitHub repository, github.com/ask-codey/exercise-fastapi-concert-tickets-api-tests, also linked from the Exercise box beside the lesson. Clone it into your python-course folder. In VS Code's terminal:
cd ~/python-course
git clone https://github.com/ask-codey/exercise-fastapi-concert-tickets-api-tests.git
Git makes a folder, exercise-fastapi-concert-tickets-api-tests, with the exercise code inside. Get the Exercise Code with Git walks through cloning step by step, if you'd like a reminder. Open that folder in VS Code (File > Open Folder), open its terminal with Terminal > New Terminal, and make the exercise's virtual environment, the same three steps as in the exercises before. On Windows (PowerShell):
python -m venv .venv
.venv\Scripts\Activate.ps1
pip install -r requirements.txt
On a Mac (zsh):
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
The prompt starts with (.venv) once the virtual environment is on. The folder holds:
main.py: makes the app and adds the error handlers and the two routers. The comment at its top lists every request the API answers. It works: don't change it.routers/shows.pyandrouters/tickets.py: the shows, buying tickets, and refunds.errors.py: Starlight Stage's own exceptions, and the handlers that give every error the one shape. Ready to use.data.py: the three shows and the tickets sold, kept in memory, andreset_data(), which puts them back the way they start.tests/test_tickets_api.py: your tests. It resets the data before every test and has one worked example.check.pyandcheck/: the check, with its three planted-bug copies of the API's files. You don't need to change them, and it's more fun not to read the copies until you're done.README.md: the show data, the error shape, and the list of behaviors your tests should cover.requirements.txtandpytest.ini: the packages, at exact versions, and where pytest finds the tests and the app.
What to do
The API your tests protect, with Starlight Stage's three shows:
| Request | What it answers |
|---|---|
GET /shows, GET /shows/2 |
200 with every show, or with one show: The Velvet Owls (id 1, $25, 40 seats left), Midnight Brass Band (id 2, $32, 4 seats left) or Juniper Lane (id 3, $18, sold out). 404 for a show that isn't there. |
POST /shows/2/tickets with {"quantity": 2} |
201 with the new ticket, whose total is the price times the quantity plus a $2 booking fee, and 2 fewer seats left. 422 for a quantity that isn't 1 to 8, 409 for more tickets than the seats left, 404 for a show that isn't there. |
DELETE /tickets/1 |
A refund: 204 with no body, and the seats go back to the show. 404 for a ticket that isn't there. |
Every error has the one shape: status, title, detail and, for a 422, problems. The worked example in tests/test_tickets_api.py shows the shape of a test:
def test_1_get_shows_answers_200_with_all_3_shows():
response = client.get("/shows")
assert response.status_code == 200
assert response.json() == STARTING_SHOWS
- Read the README's list of behaviors. There are twelve, numbered, each with the exact request and the exact status code and body to expect. Behavior 1 is the worked example.
- Test the shows: one show, and a show that isn't there (behaviors 2 and 3).
- Test buying tickets: two everyday orders, the last seats of a show, one ticket too many, a sold-out show, three bad quantities and a show that isn't there (behaviors 4 to 10). After each order, check what it did to the seats.
- Test refunds: a refund that gives the seats back, and a ticket that isn't there (behaviors 11 and 12).
Name each test after its behavior's number, what it sends and what it expects, such as test_7_buying_5_tickets_for_show_2_answers_409_and_leaves_the_4_seats_alone.
Check your work
While you write, run your tests:
pytest
Every test you write should pass, because the API works. If one fails, work out its expected value again from the README: the test is the part to fix.
Then see how good your tests are:
python check.py
It runs your tests four times: once with the working API, then once with each of three copies that has a bug planted in it. One copy answers a ticket sale with the wrong status code, one lets the seats go below zero, and one has a refund that never gives the seats back. A bug counts as caught when at least one of your tests fails on its copy. At the start, check 1 passes (the worked example passes) and checks 2 to 4 don't: that's expected, because one test can't catch three bugs yet. A check that isn't passing yet says what kind of test it's missing, for example Test a refund, then ask for the show again: its seats come back.
Hints
- Work out each expected value by hand, from the README. A test that copies whatever the API answers proves nothing.
- Check the status code and the body. A ticket that sells with the wrong status code still looks right in the body, as Testing an API with TestClient showed.
- Check what changed with a second request. After an order or a refund,
client.get("/shows/2")and its.json()["seats_left"]show what really happened to the seats. - A refused order changes nothing. After a 409 or a 422, the seats are still what they were, as Testing Errors, with a Fresh Start for Every Test checks.
- Bugs hide at the edges. Show 2 has 4 seats left, so try 4 and 5, not only 2.
- One test, three bad values.
@pytest.mark.parametrize("quantity", [0, 9, "two"])runs the test once for each. - A refund needs a ticket first. The fixture resets the data before each test, so a refund test buys its ticket first, and that ticket's id is 1.
When you're done
Every test is green with pytest, and python check.py prints:
Checking your tests against the working API and three copies with a bug planted in each.
1) your tests pass on the working API: yes
2) your tests catch planted bug 1, a wrong status code: yes
3) your tests catch planted bug 2, seats that can go below zero: yes
4) your tests catch planted bug 3, a refund that never gives the seats back: yes
All 4 checks pass: your tests catch every planted bug.
Now open the three copies in check/planted-bugs/ and find each bug. Which of your tests caught it? A test that buys 5 tickets for show 2 catches the second bug, but a test that buys 2 doesn't: what does that tell you about testing right at the edge of a rule?
Submit your exercise
The exercise is how you finish this lesson. When your work is done, put it on GitHub in a repo of your own, then submit that repo's address here. Hand In Your Work with Git walks through each step.
On GitHub, click +, then New repository. Name it (for example
exercise-fastapi-concert-tickets-api-tests), choose Public, and click Create repository. Leave out the README: your folder already has one.In VS Code's terminal, in your exercise folder, send your work to your new repo. Point your copy at your own repo, then commit and push:
git remote set-url origin https://github.com/your-name/exercise-fastapi-concert-tickets-api-tests.git git add . git commit -m "My tests" git push -u origin mainPaste your repo's address, such as
https://github.com/your-name/exercise-fastapi-concert-tickets-api-tests, into Submit your exercise on this page. The site checks that the repo is public and holds your commits, and then the lesson is complete.
Changed something after you submitted? Push it, and submit again: your latest submission is the one that counts.
So what
You can now prove an API works, and prove your proof is good: tests that check every status code, every error and every change to the data are the ones that catch a broken endpoint before a fan does.