Python Master Course V2 — 111. Software Testing Foundations and Reliable Assertions
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 12: TESTING AND QUALITY · 111 / 200
Software Testing Foundations and Reliable Assertions
Intermediate–advanced · 90–120 minutes · Prerequisites: Python functions, exceptions, classes and Lesson 110.
Video lesson
Video not yet available; the full written lesson is provided below.
Learning outcomes
- Distinguish unit, integration and end-to-end testing.
- Apply Arrange–Act–Assert to deterministic tests.
- Identify valid, invalid, boundary and regression cases.
- Assert exceptions and exact decimal calculations.
- Build an independently testable invoice function and unittest suite.
1. Detailed conceptual guide
Scope and confidence
Unit tests exercise the smallest useful behavior in isolation. Integration tests verify collaborating components such as code and a database. End-to-end tests check complete user workflows. Passing tests demonstrate the selected contract for selected scenarios; they do not prove the absence of defects.
Arrange–Act–Assert
Arrange the input and controlled dependencies, act by calling the unit under test, then assert a precise outcome. A well-designed test fails for an understandable reason. Plain print statements show observations but do not tell automation whether results are correct.
Representative input partitions
Use specification-derived cases: normal inputs, exact thresholds, values immediately above and below thresholds, empty data, malformed values and failures from external dependencies. When fixing a bug, preserve its smallest reproducing input as a regression test. Avoid copying the production algorithm into the expected-value calculation, because that can duplicate the same mistake.
Exact and approximate values
Many financial requirements define exact decimal values and explicit rounding. Construct Decimal values from strings and write down rounding mode in the contract. For physical measurements, tolerant floating-point comparisons may be appropriate. Choose based on the domain, not convenience.
Reliable suites
Use deterministic clocks, sample records, predictable file paths and network-free unit cases. Assertions can be disabled under Python’s optimized mode, so production input validation must use if conditions and explicit exceptions. Separate I/O from calculations and make tests easy to rerun on developer machines and CI.
2. Six runnable examples
Run each example independently under Python 3.10+. Outputs shown are expected from the source, not results of executing code on the live site.
Example 1: Arrange–Act–Assert
def net(gross, fee):
return gross - fee
actual = net(100, 15)
assert actual == 85
print(actual)
Expected output:
85
Separate setup, execution and a precise assertion; a print alone is not a test.
Example 2: Boundary partitions
def clamp(n):
return max(0, min(10, n))
for x, expected in [(-1, 0), (0, 0), (5, 5), (10, 10), (20, 10)]:
assert clamp(x) == expected
print("five boundary cases passed")
Expected output:
five boundary cases passed
Test below the range, at the exact lower endpoint, inside the range, at the exact upper endpoint, and above the range. The inclusive endpoints 0 and 10 must be preserved.
Example 3: Expected exceptions
import unittest
case = unittest.TestCase()
with case.assertRaisesRegex(ValueError, "positive"):
raise ValueError("positive amount required")
print("rejection tested")
Expected output:
rejection tested
An exception is correct behavior when required validation rejects invalid input.
Example 4: Exact decimal assertions
from decimal import Decimal
total = Decimal("0.10") + Decimal("0.20")
assert total == Decimal("0.30")
print(total)
Expected output:
0.30
Decimal from strings avoids binary float representation errors.
Example 5: Regression table
def normalized(value):
return value.strip().casefold()
cases = [(" Asha ", "asha"), ("RAVI", "ravi"), (" ÉCOLE ", "école")]
for raw, clean in cases:
assert normalized(raw) == clean
print(len(cases), "cases passed")
Expected output:
3 cases passed
Retain examples of previously repaired formatting bugs.
Example 6: Invariants and stable order
def unique(items):
return list(dict.fromkeys(items))
result = unique(["a", "b", "a", "c"])
assert result == ["a", "b", "c"]
assert len(result) == len(set(result))
print(result)
Expected output:
['a', 'b', 'c']
Check both a concrete output and a general invariant.
3. Fully worked project: invoice discounts
Requirement: accept finite, nonnegative decimal amounts and a discount rate from 0 to 1. Apply the reduction and round HALF_UP to two decimal places. Reject invalid input rather than suppress errors. This sample is educational, not a legal tax or invoicing policy.
Step 1: Implement the business rule
# Save as invoice.py
from decimal import Decimal, InvalidOperation, ROUND_HALF_UP
def final_amount(amount, discount):
try:
base = Decimal(str(amount))
rate = Decimal(str(discount))
except InvalidOperation as exc:
raise ValueError("invalid decimal input") from exc
if not base.is_finite() or not rate.is_finite():
raise ValueError("non-finite input")
if base < 0 or not 0 <= rate <= 1:
raise ValueError("out-of-range input")
return (base * (1 - rate)).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP
)
Step 2: Write automated checks
# Save as test_invoice.py
import unittest
from decimal import Decimal
from invoice import final_amount
class InvoiceTests(unittest.TestCase):
def test_regular(self):
self.assertEqual(final_amount("100", "0.10"), Decimal("90.00"))
def test_zero(self):
self.assertEqual(final_amount("0", "0.5"), Decimal("0.00"))
def test_rounding(self):
self.assertEqual(final_amount("10.05", "0.10"), Decimal("9.05"))
def test_bad_rate(self):
with self.assertRaisesRegex(ValueError, "out-of-range input"):
final_amount("10", "1.5")
def test_zero_discount(self):
self.assertEqual(final_amount("42", "0"), Decimal("42.00"))
def test_full_discount(self):
self.assertEqual(final_amount("42", "1"), Decimal("0.00"))
def test_negative_amount(self):
with self.assertRaisesRegex(ValueError, "out-of-range input"):
final_amount("-1", "0")
def test_negative_rate(self):
with self.assertRaisesRegex(ValueError, "out-of-range input"):
final_amount("10", "-0.01")
def test_non_finite(self):
cases = [("NaN", "0"), ("Infinity", "0"),
("10", "NaN"), ("10", "-Infinity")]
for amount, discount in cases:
with self.subTest(amount=amount, discount=discount):
with self.assertRaisesRegex(ValueError, "non-finite input"):
final_amount(amount, discount)
def test_malformed_decimal(self):
for amount, discount in [("not-a-number", "0"), ("10", "invalid")]:
with self.subTest(amount=amount, discount=discount):
with self.assertRaisesRegex(ValueError, "invalid decimal input"):
final_amount(amount, discount)
if __name__ == "__main__":
unittest.main()
Step 3: Execute in the same folder
python -m unittest -v test_invoice.py
Expected: 10 tests run and finish with OK, with variable elapsed time. The suite covers the original four cases, both inclusive discount endpoints, negative values, non-finite values and malformed decimal text. The two parameterized methods use subtests; unittest reports 10 test methods.
Failure injection and test design
Temporarily change (1 – rate) to (1 + rate): the regular discount case should fail. Revert the change. The suite now includes negative amount, NaN and rate greater than one. Add an independently calculated case for a different rounding threshold and check that the injected defect is caught. In a professional system, keep monetary rules isolated from database/network operations and version the business policy for auditability.
4. Common mistakes, security and performance
Do not accept printed output as an automated test, compare floating-point money as if exact, mutate shared test state, suppress validation errors, or assume coverage percentage establishes correctness. Prefer small and fast unit cases, then complement them with integration and end-to-end checks. Use artificial sample values instead of real customer financial data or credentials.
Debug by preserving the smallest failing input and traceback, inspecting expected and actual values, correcting the root cause, and retaining the case as a regression test.
5. Five practice exercises with model answers
Try each question before opening the answer. Hints are optional.
1. Check the discount endpoints
Add tests for a 100% discount and for no discount using an amount of 42. What exact Decimal results should each assertion expect?
Hint
The rate contract includes both 0 and 1.
Show answer and explanation
A rate of 1 returns Decimal("0.00"); a rate of 0 returns Decimal("42.00").
Add self.assertEqual(final_amount("42", "1"), Decimal("0.00")) and self.assertEqual(final_amount("42", "0"), Decimal("42.00")) inside InvoiceTests. These endpoint cases catch comparisons that accidentally exclude valid boundary values.
2. Assert the negative-amount error
Write a test rejecting final_amount("-1", "0"). Which exception and message does the original function promise?
Hint
Read the out-of-range validation branch before choosing the expected exception.
Show answer and explanation
Expect ValueError with the message “out-of-range input”.
Use self.assertRaisesRegex(ValueError, "out-of-range input") around the call. A missing exception fails the test, and a different exception is an error. The function separately reports malformed decimal text and non-finite inputs; do not treat every failure as interchangeable.
3. Make time-dependent tests deterministic
Why can a test using the current clock pass today and fail tomorrow? How should you test a rule that changes at midnight?
Hint
Control the input clock rather than waiting for a real date boundary.
Show answer and explanation
The system date, timezone and boundary timing vary. Inject a clock or pass the date explicitly.
Arrange fixed instants immediately before, exactly at and after the defined boundary. Then assert the documented result for each. This tests the rule without depending on when or where the suite runs.
4. Preserve a useful regression case
A rounding bug previously returned 9.04 for final_amount("10.05", "0.10"). What regression assertion should remain after the fix?
Hint
Calculate the unrounded decimal amount independently from the specification.
Show answer and explanation
Assert final_amount("10.05", "0.10") == Decimal("9.05").
The discount leaves 9.045, which rounds HALF_UP to 9.05 at two places. Keep this minimal reproducing input and its fixed expected value; copying the implementation into the expected-value calculation could reproduce the same defect.
5. Design an integration check
Give one integration test connecting the invoice calculation to storage without using real customer data.
Hint
An integration test checks cooperating components, not only the calculator.
Show answer and explanation
Calculate a synthetic invoice, store its Decimal total in an isolated test database, then retrieve and compare it with the expected value.
For example, final_amount("100", "0.10") must produce Decimal("90.00"). Verify the stored amount and the associated synthetic invoice ID. Create controlled records and clean them up so repeated test runs do not share state.
6. Five topic-specific questions and explanations
Try each question before opening the answer. Hints are optional.
1. Choose the smallest testing scope
Which test isolates final_amount with fixed inputs: a unit test, a database integration test, a browser end-to-end test or an acceptance workflow?
Hint
Look for the case that does not require collaborating systems.
Show answer and explanation
A unit test.
It exercises the calculator behavior in isolation. Database integration and complete browser workflows provide different kinds of confidence; they do not replace focused unit checks.
2. Apply Arrange-Act-Assert
You set amount="100" and discount="0.10", call final_amount, then compare with Decimal("90.00"). Which step belongs to Arrange, Act and Assert?
Hint
Separate setup, execution and the precise check.
Show answer and explanation
Arrange: choose the inputs. Act: call final_amount. Assert: compare the result with Decimal("90.00").
A clear test exposes the requirement and the cause of a failure. Printing 90.00 alone does not tell an automated suite whether the contract was satisfied.
3. Verify an error contract
Which is the strongest check for a negative amount: print the exception, sleep before calling, assertRaisesRegex(ValueError, "out-of-range input"), or catch Exception and continue?
Hint
A good check must fail if the promised rejection does not happen.
Show answer and explanation
assertRaisesRegex(ValueError, "out-of-range input").
It checks the expected exception type and message. Printing has no pass/fail assertion, sleeping is unrelated, and catching every exception can hide programming errors.
4. Choose exact decimal construction
For this lesson’s exact decimal contract, which is appropriate: Decimal("0.10"), Decimal(0.10), binary float equality, or ignoring rounding?
Hint
Construct Decimal from the intended decimal text.
Show answer and explanation
Decimal("0.10"), with the specified ROUND_HALF_UP rule.
Decimal(0.10) starts from an already approximate binary float. Decimal strings preserve the intended input representation. Approximate comparisons belong to contracts that permit numerical tolerance.
5. Identify a regression test
A repaired bug excluded discount rate 1. Which test best guards against recurrence: final_amount("42", "1") == Decimal("0.00"), a random screenshot, a timing delay or checking a color?
Hint
Retain the smallest input that previously violated the contract.
Show answer and explanation
The exact full-discount assertion.
It ties the old failure to a specific expected result and fails if the endpoint is rejected again. Add other cases for broader coverage, but keep the original reproducer.
Mastery checkpoint
Explain testing scopes and AAA, reproduce all six snippets, implement the invoice calculator, run the 10 passing tests, add two independent regression cases, and justify monetary precision and deterministic setup. No video, certificate or automatic learner tracking is claimed.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.