3.3 — Testing Your Data

Check that what you save is what you load back.

Why This Matters

A feature can look like it works and still lose data. The most important test for a saved app is: save it, load it, and compare.

The Idea

A test checks one thing and says PASS or FAIL. assert stops the program with an error if the condition is False. Add a message after the comma so you know what failed.

def test_round_trip():
    original = {"apple": {"qty": 4, "price": 0.50}}
    save_data(original, "test_round_trip.json")
    loaded = load_data("test_round_trip.json")
    assert loaded == original, "Data changed after save and load"
    print("PASS: round trip")

test_round_trip()

Use a test file name. Don't test with your real save file. Your tests shouldn't be able to damage your real data.

Your Test Table

Write the table first, and fill in Expected before you run anything. Then record what actually happened.

#What I'm testingInputExpectedActualPass?
1Save then load gives the same dataA small dictionarySame as before
2Missing file starts emptyNo save fileEmpty data, no crash
3Quantity typed as text"five"Asks again, no crash
4Negative quantity-5Rejected with a message
5Empty name(nothing)Rejected with a message

Try It

  1. Write test_round_trip and run it. It should pass.
  2. Break your save function on purpose (for example, skip the last record). Run the test and watch it fail.
  3. Put the bug back, run the test again, and record both results.

Practice Notebook

Work through more examples, in different contexts, in a Jupyter notebook. Every exercise has a check cell that tells you when your code is right.

Download the notebook (3.3)

How to open it: open the file in VS Code, pick a Python kernel, and run the cells from top to bottom with Shift + Enter.

Common Mistakes

  • Testing only the easy path. Bad input and missing files are where apps crash.
  • Filling in Actual after the fact, so it always matches Expected. Record what really happened, even when it's a fail.
  • Testing with your real data file. Use a separate test file name.

You're Done With This Lesson When…

At least one round-trip test passes, and you've seen one test fail on purpose.