Exercise: Shipping Cost Tests

Write the pytest tests for Crafty Corner's working shipping rules, from its prices by weight and zone to free shipping, rush orders, errors and shipping labels, and prove they're good by catching three bugs the check plants in copies of the code.

Journeyman · Python · Updated

By

Crafty Corner's shipping code works today. It prices a parcel by its weight and zone, ships orders of $50 or more free, adds a fee for rush orders, refuses parcels it can't send, and writes a shipping label for every order. Nobody wrote tests for it, though, so the next person who changes it could break shipping and not find out until a customer does. This time the code 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 code, 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-python-shipping-cost-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-python-shipping-cost-tests.git

Git makes a folder, exercise-python-shipping-cost-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:

  • shipping.py: Crafty Corner's shipping rules, three functions with a docstring each. It works: don't change it.
  • quotes.py: prints the shipping for five of today's orders, so you can see the rules at work.
  • tests/test_shipping.py: your tests. It has one worked example.
  • check.py and check/: the check, with its three planted-bug copies of shipping.py. You don't need to change them, and it's more fun not to read the copies until you're done.
  • README.md: the rules and the list of behaviors your tests should cover.
  • requirements.txt and pytest.ini: the package the tests need, and where pytest finds the tests and the code.

What to do

The rules your tests protect, with every weight in whole pounds:

Function What it does
shipping_cost(pounds, zone) The first pound costs $4.50 in zone 1, $6.00 in zone 2 and $8.50 in zone 3; each pound after it $1.25. A parcel weighs 1 to 70 pounds; any other weight, or a zone that isn't 1, 2 or 3, raises a ValueError.
order_shipping(order_total, pounds, zone, rush=False) Orders of $50.00 or more ship free; below that, the order pays shipping_cost. A rush order pays $12.00 more, even when it ships free.
save_label(path, order_id, pounds, zone, rush=False) Writes the label to the file at path: Crafty Corner order 1042, then 3 lb to zone 2, then RUSH for a rush order.

The worked example in tests/test_shipping.py shows the shape of a test:

def test_1_shipping_cost_3_pounds_to_zone_2_is_8_50():
    assert shipping_cost(3, 2) == 8.5
  1. Read the README's list of behaviors. There are twelve, numbered, each with the exact call and the exact answer or error to expect. Behavior 1 is the worked example.
  2. Test shipping_cost: the smallest and biggest parcels, the two weights one pound past each limit, and a zone that doesn't exist (behaviors 2 to 5).
  3. Test order_shipping: an everyday order, the cent below free shipping and exactly $50.00, and two rush orders, one that pays shipping and one that ships free (behaviors 6 to 10).
  4. Test save_label: a label with two lines and a rush label with three, each written into a tmp_path folder (behaviors 11 and 12).

Name each test after its behavior's number and what it checks, such as test_8_order_of_exactly_50_ships_free.

Check your work

While you write, run your tests:

pytest

Every test you write should pass, because the code works. If one fails, work out its expected value again by hand 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 shipping.py, then once with each of three copies that has a bug planted in it. One copy starts free shipping above $50, one charges a zone that doesn't exist like zone 3, and one leaves the rush fee off orders that ship free. 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 an order of exactly $50.00: it ships free.

In your textbook, planting small bugs in working code to see whether the tests notice is called mutation testing.

Hints

  • Work out each expected value by hand, from the README's rules. A test that copies whatever the code returns proves nothing.
  • Bugs hide at the edges. Free shipping starts at $50.00, so test $49.99 and $50.00, as Testing Edge Cases and Errors does. The same goes for 1 and 70 pounds, and 0 and 71.
  • An error is part of the rule. with pytest.raises(ValueError, match="...") makes sure the call inside it raises a ValueError whose message has those words.
  • Several examples, one test. @pytest.mark.parametrize runs one test for each example in its list.
  • A file needs a folder. Give the label tests the tmp_path fixture and write into it, as Fixtures and Temporary Files does: label = tmp_path / "label-1042.txt", then label.read_text(encoding="utf-8") reads it back.

When you're done

Every test is green with pytest, and python check.py prints:

Checking your tests against the working shipping.py and three copies with a bug planted in each.

1) your tests pass on the working shipping.py: yes
2) your tests catch planted bug 1, free shipping that starts above $50: yes
3) your tests catch planted bug 2, a zone that doesn't exist, charged like zone 3: yes
4) your tests catch planted bug 3, the rush fee left off orders that ship free: yes

All 4 checks pass: your tests catch every planted bug.

And python quotes.py shows the rules at work:

Crafty Corner: today's shipping
Order 1040: $32.00, 3 lb to zone 2, standard: $8.50 shipping
Order 1041: $49.99, 3 lb to zone 2, standard: $8.50 shipping
Order 1042: $50.00, 3 lb to zone 2, standard: $0.00 shipping
Order 1043: $32.00, 3 lb to zone 2, rush: $20.50 shipping
Order 1044: $64.00, 3 lb to zone 2, rush: $12.00 shipping

Now open the three copies in check/planted-bugs/ and find each bug. Which of your tests caught it? A test of a $64 rush order catches the third bug, but a test of a $32 rush order doesn't: what does that tell you about testing a rule on both sides of a boundary?

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.

  1. On GitHub, click +, then New repository. Name it (for example exercise-python-shipping-cost-tests), choose Public, and click Create repository. Leave out the README: your folder already has one.

  2. 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-python-shipping-cost-tests.git
    git add .
    git commit -m "My tests"
    git push -u origin main
    
  3. Paste your repo's address, such as https://github.com/your-name/exercise-python-shipping-cost-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 code works, and prove your proof is good: tests that try the edges, the errors and the files a program writes are the ones that catch a broken rule before a customer does.

Key terms

Related