Treat a test as an executable statement of expected behavior.
What It Does and Why It Matters
A useful test prepares a known input, runs a small piece of code and checks a specific result. Assertions should fail clearly when behavior changes. Prefer one focused expectation per scenario and independent test data so failures can be understood without tracing an entire application.
Tests document expected behavior; passing tests cannot prove the absence of every bug.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
def apply_discount(price: float, percent: float) -> float:
return price * (1 - percent / 100)
def test_discount():
assert apply_discount(100, 20) == 80
test_discount()
print("Test passed")
How the Code Works
- The definition of apply_discount, test_discount creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
Expected output:
Test passed
For the demonstrated inputs, Python displays 'Test passed'. This result follows from the operation described above; change one input at a time to understand which rule matters.
Second Example: Compare Two Cases
Use a different input or a related operation to observe an important difference. The two examples help separate the general rule from one particular result.
assert 2+2==4
print("Calculation verified")
Expected output:
Calculation verified
Where You Would Use This
Start with an independently checkable requirement and test both normal and boundary inputs. A passing assertion documents only the cases that were exercised. Keep tests deterministic so a failure identifies a real change rather than environmental noise.
Practice Exercise
Add a second test for a zero-percent discount and one for an invalid negative percentage.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Writing tests that print output but never assert what the output should be.
- Checking only the easiest input and missing a relevant error or boundary case.
Key Takeaways
- Treat a test as an executable statement of expected behavior.
- A useful test prepares a known input, runs a small piece of code and checks a specific result.
- Add a second test for a zero-percent discount and one for an invalid negative percentage.