Tests that catch real mistakes
Turn expectations into repeatable checks, including unhappy paths.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 13 minutes; optional deep dive: 8 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Test normal, empty and boundary inputs
- Write assertions
- Explain what a passing test does not prove
A test connects input to an observable result
A test compares an observable result with a stated expectation. Running code without checking its result cannot establish that the promised behavior occurred.
Understand first
A repeatable test can catch a regression when implementation changes. Start with functions, comparisons and booleans. Pick expected results from the contract before running the implementation so the test is not merely repeating its answer.
Words you will see
- Assertion
- A condition that must hold; assert raises AssertionError when it is false in ordinary non-optimised test execution.
- Regression
- A previously working behavior broken by a change.
- Observable result
- An outcome a caller can inspect, such as a return value, exception or documented mutation.
Arrange, act and assert against a reason
The remainder operator % gives zero for even integers. The first call uses 4 and must return the actual boolean True; is True checks that exact boolean identity, not merely a truthy value. The next call requires False for 3. Zero also has remainder zero, so it is even despite not being positive.
Each assert raises if its requirement is broken, and later lines do not run after an unhandled failure. The success print is reached only if these three checks pass. The string itself is not a test result receipt for edited code; actual execution in the shared runner is the evidence.
Turn a failure into a focused debugging question
If zero fails but four passes, inspect a positivity condition rather than assuming modulo is broken. Reproduce the smallest failing input, read the traceback's source location, compare expected and actual values, and change one relevant condition. Rerun the failing case and nearby cases after the fix.
A hard-coded function returning True always would fail the odd case. A function accepting only positive even values would fail zero. These cases distinguish plausible wrong implementations, but they do not prove every integer or every argument type works. Public checks are learning feedback, not certification or exhaustive grading.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return value % 2 == 0Calculate a boolean from divisibility by two.
assert is_even(4) is TrueCheck an ordinary even integer.
assert is_even(3) is FalseReject the plausible always-True implementation.
assert is_even(0) is TrueInclude the nonpositive boundary and reject a positivity restriction.
print("3 checks passed")Display the marker only after all three assertions complete.
Arrange input, act by calling the code and assert the result. A test should fail when the intended behaviour breaks. Tests that only execute a function without checking its result give weak evidence.
Conceptual test evidence, not proof of mastery or a live trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- ArrangeChoose 4, 3 and the boundary value 0.
- ActCall is_even for each chosen input.
- AssertCompare each result with the required boolean.
- EvidenceThree passing cases support these examples, not all imaginable inputs.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Try a plausible bug.
Try: Replace the return with return value > 0 and value % 2 == 0.
The zero assertion fails and the success marker is not printed.
Extend the signed boundary.
Try: Add assert is_even(-2) is True before the success print.
The original function passes: negative even integers also have remainder zero.
Before you move on
Would these three checks reject a function that always returns True? Which case matters?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Yes. is_even(3) must be False, so the odd case fails. The two even cases alone would not reject the always-True implementation.
Choose cases from the contract
A contract-based test case targets one rule or boundary of the interface. Exception behavior and ownership are observable requirements, not optional extras.
Understand first
An ordinary success case cannot show whether a function handles emptiness, repeated values or rejected input correctly. Derive cases from each promise, then compare the promised result rather than implementation details.
Words you will see
- Boundary case
- An input at or near a rule's limit, such as an empty collection.
- Ownership check
- A check that caller-controlled values were changed or preserved as promised.
- Negative test
- A test expecting a specified rejection, not a negative numeric value.
Check both the value and the absence of unwanted edits
The function must return the first item without consuming the caller's list. The repeated tea fixture makes duplication visible; the second assert checks the whole list after the call. A wrong pop(0) implementation returns the right item but fails the preservation requirement.
For an empty list, the contract says ValueError. A try call alone would pass when the function incorrectly returned None. The else suite runs only when no exception was raised by the try suite, so it explicitly fails that missing-error path. An unexpected exception type propagates instead of counting as a pass.
Use expected results that separate plausible implementations
An only-one-item test would not catch returning the last item instead of the first if those were equal. Add distinct items when that distinction matters. Repeated inputs are useful for count and deduplication policies, not a replacement for every other case.
Test through the public result and documented effects rather than a helper's local variable names or an exact implementation sequence. A refactoring that preserves the contract should not break these tests. This program requires no external fixture files; the data is created fresh in the editor.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
if not items:Choose an explicit rejection for empty input.
raise ValueError("No items")Report the contract's expected error.
return items[0]Read without removing the first slot.
items = ["tea", "tea"]Arrange a repeated-value fixture.
assert items == ["tea", "tea"]Check ownership after the function call.
first([])Exercise the empty boundary.
raise AssertionError("Expected ValueError")Fail if the rejection did not happen.
Include empty, single-element, repeated, negative and boundary values where meaningful. If code must reject invalid input, test the exception too. Do not assert only internal details that callers cannot observe.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Make the ownership bug observable.
Try: Replace return items[0] with return items.pop(0).
The list-preservation assertion fails before the success marker.
Test a missing exception.
Try: Replace raise ValueError("No items") with return None.
The test's else branch raises Expected ValueError, rejecting the silent result.
Before you move on
Will a function returning None for [] pass the exception check as written?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. With no exception, the try's else suite raises AssertionError. A missing rejection is therefore observable rather than silently accepted.
Keep tests independent
An independent test creates the state it needs and does not rely on an earlier test changing shared data. A fixture is the known input state prepared for a test.
Understand first
Tests should pass regardless of which other unrelated tests ran first. Shared mutable fixtures can make a correct test fail in a suite or hide a defect. Know whether the function intentionally mutates before choosing your ownership assertion.
Words you will see
- Fixture
- The known starting data and resources prepared for a test.
- Isolation
- Keeping one test's state changes from changing another test's starting conditions.
- Unit test
- A focused test of a small behavior without external system dependencies.
Fresh inputs make repeated evidence comparable
add_label deliberately appends to its input and returns the same list. check_once creates ['draft'] each time, so two calls test the same starting contract. is labels verifies identity while equality verifies contents; neither check alone establishes both properties.
If labels lived as a shared global and was not reset, the second run would append a second review. That is fixture contamination, not evidence that append is nondeterministic. Prefer fresh setup to relying on test order or a previous test's cleanup.
Separate small logic from integrations
A real file or database integration test also needs explicit setup, cleanup and supported resources. Keep it separate from deterministic in-memory unit cases so a network outage is not mislabeled as a calculation failure. Inject a clock or a data provider when varying that dependency is part of the behavior.
This example does not mock a filesystem or claim a database was used. It exercises only Python lists in one run. Fresh fixtures cost memory for each active test, but make failures easier to reproduce; reusing expensive integration resources requires a deliberate reset protocol rather than implicit sharing.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
labels.append("review")Perform the documented mutation.
return labelsReturn the very same object.
labels = ["draft"]Create a fresh fixture inside every check call.
result = add_label(labels)Act on this check's owned fixture.
assert result is labelsVerify the returned identity.
assert labels == ["draft", "review"]Verify the final contents.
check_once()Each of the two calls independently repeats the same contract.
Tests that mutate shared global data can pass alone and fail together. Build fresh fixtures per test. Separate deterministic unit tests from file, network and database integration tests.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Expose a wrong return identity.
Try: Change return labels to return labels.copy().
The identity assertion fails even though the lists compare equal.
Make each test perform two actions.
Try: Add a second add_label(labels) call before the asserts.
The expected contents fail because review is now appended twice.
Before you move on
Would returning labels.copy() after appending satisfy this particular contract?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Contents would match, but result is labels would fail. This interface promises the original list, so identity is a deliberate observable requirement.
Where this idea earns its place
A useful test would fail if required behaviour broke. Merely executing a function or checking a score generated by that same function can provide weak evidence. Define observable outcomes and boundary policies before writing assertions so the test expresses the contract rather than copying the implementation.
Follow the mechanism step by step
Arrange inputs and dependencies, act through the public operation and assert the resulting value, state or declared error. Keep mutable fixtures independent between tests. A small pure function can usually be tested without mocks; external filesystem, clock, network or database boundaries may require controlled fixtures or integration tests.
Work through a concrete application
For is_even, include zero, a positive odd value and a negative even value if integers of either sign are supported. For a list transformation, test empty, one item and duplicates, then compare the input before and after when non-mutation is promised. Explain why each case can catch a different plausible wrong implementation.
Failure cases and misleading shortcuts
A mock returning the expected result can accidentally replace the behaviour you intended to test. Broad snapshots may pass while a key invariant is wrong. Coverage tells you which lines ran, not whether the assertions establish correctness. A test that depends on execution order or real waiting may be unstable even if the application is correct.
Cost, ownership and alternatives
Use fast focused unit tests for logic and bounded integration tests for real adapters. Property tests explore invariants over many inputs; mutation tests assess whether deliberately wrong logic is detected. These techniques complement examples rather than allowing every integration or security question to be reduced to a coverage percentage.
Verify the contract
Run a test that intentionally fails to confirm the assertion and runner are active. Test exceptions and cleanup, not only returned values. Record runtime and dependency assumptions when a test covers implementation-specific behaviour. Keep production credentials and real learner data out of fixtures and diagnostic output.
Transfer question: What would be a stronger property for a sorting function than one expected array?
The result is ordered according to the agreed key and preserves the input multiset, including duplicates. Also test stability if promised and input ownership if sorting should be non-mutating. One sorted example cannot establish all those properties.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Test a clamp
Return a value bounded to [0, 100]. Check below, within and above the range.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided: implement a tested clamp
Return an exact integer bounded to the inclusive interval 0 through 100.
The contract
- Input is an exact int; bool and all other types raise TypeError.
- Return 0 below zero, 100 above one hundred, or the unchanged integer within the interval. No mutation, I/O or retained state.
- Repeated calls are independent. This is a clamp, not validation that rejects out-of-range integers; no ordering or deduplication applies.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- interior
assert clamp_score(40) == 40
- below
assert clamp_score(-2) == 0
- above
assert clamp_score(120) == 100
- endpoints and repeats
assert [clamp_score(v) for v in (0,100,0,100)] == [0,100,0,100]
- invalid types and absent
for value in (True, None, "20", 20.0): try: clamp_score(value) except TypeError: continue raise AssertionError("Wrong type accepted") - ownership and idempotence
value = [20] try: clamp_score(value) except TypeError: assert value == [20] else: raise AssertionError("List accepted") for number in (-10,0,10,100,110): result = clamp_score(number) assert type(result) is int and 0 <= result <= 100 and clamp_score(result) == result
Why are both concrete expectations and idempotence useful?
Idempotence alone accepts constant-zero. Concrete interior and bound cases rule out several plausible mutants. This uses a fixed number of control operations and O(1) extra references, with comparison costs dependent on integer size.
Guided: fix an ownership regression
Return the first supplied value without consuming the caller's list.
The contract
- Input is a list of any values. If empty raise ValueError; otherwise return the exact object at index zero.
- Do not alter, reorder or copy the items, and do not mutate the outer list. Repeated values remain present.
- No I/O or retained state; repeated calls observe the same first object unless the caller changes the list. This is a borrowed result, not a deep copy.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- distinct order
assert peek_first(["tea","bread"]) == "tea"
- empty
try: peek_first([]) except ValueError: pass else: raise AssertionError("Missing ValueError") - false value
assert peek_first([0,2]) == 0
- repeats and preservation
items = ["a","a"] assert peek_first(items) == "a" and items == ["a","a"]
- borrowed identity
child = [] items = [child, [1]] result = peek_first(items) assert result is child and items[0] is child and items == [[],[1]]
- independent calls
items = ["z","a"] assert peek_first(items) == "z" and peek_first(items) == "z" and items == ["z","a"] and peek_first(["b"]) == "b"
Can a caller mutate the returned nested list?
Yes, because the contract returns a borrowed reference. That would change the caller-owned element; it is not the helper secretly mutating it. Indexing and the emptiness check take O(1) time and O(1) extra space for lists.
Transfer: write a checker that rejects defects
Change roles: implement a contract checker rather than the clamp itself.
The contract
- Input is a callable. Invoke it on exactly -1, 0, 40, 100, 101 in that order, once per value. Expected exact int results are 0, 0, 40, 100, 100.
- Return the fresh list of input values where the callable returns a wrong value or non-exact-int, or raises an ordinary Exception. Continue checking later inputs after a failure; do not catch BaseException.
- No I/O or global cache. Correct callable returns a fresh []; preserve caller-owned objects except for the required callable invocations. Duplicate wrong outputs still produce separate source cases.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- correct and fresh
function = lambda x: max(0,min(x,100)) a = failing_cases(function) b = failing_cases(function) assert a == [] and b == [] and a is not b
- missing lower bound
assert failing_cases(lambda x: min(x,100)) == [-1]
- missing upper bound
assert failing_cases(lambda x: max(0,x)) == [101]
- constant and bool
assert failing_cases(lambda x: 0) == [40,100,101] and failing_cases(lambda x: False) == [-1,0,40,100,101]
- exceptions continue
seen = [] def candidate(value): seen.append(value) if value == 0: raise ValueError("broken") return max(0,min(value,100)) assert failing_cases(candidate) == [0] and seen == [-1,0,40,100,101] - exact call ownership and control errors
seen = [] def candidate(value): seen.append(value) return value assert failing_cases(candidate) == [-1,101] and seen == [-1,0,40,100,101] def cancelled(value): raise KeyboardInterrupt() try: failing_cases(cancelled) except KeyboardInterrupt: pass else: raise AssertionError("BaseException swallowed")
Why is catch Exception acceptable in this checker but not in an input parser?
The checker deliberately classifies ordinary candidate failures as test feedback. A production parser must not disguise unknown bugs as valid data. Exactly five calls use O(1) checker space and steps beyond the candidate's own work; this still is not exhaustive grading.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneAssertions and production validation differ
Production validation rejects invalid requests explicitly. Test assertions express developer expectations, but assert statements can be removed by Python optimisation.
Understand first
External input must remain validated under every supported execution mode. Keep explicit raise checks in production and use a test framework to collect test evidence. Browser examples can call unittest assertion methods directly without shell commands or child processes.
Words you will see
- Optimisation mode
- An interpreter mode, such as Python -O, that can omit assert statements.
- Test runner
- A tool that discovers, executes and reports a collection of tests.
- assertRaises
- A unittest context that fails if the specified exception is not raised.
Validation must not disappear
positive checks value <= 0 and explicitly raises ValueError. That branch remains part of the function when assert statements are disabled. Replacing it with assert value > 0 would both change the error type and allow invalid values through in optimised execution.
The unittest TestCase instance provides ordinary methods. assertEqual checks a result, and assertRaises observes exactly the expected failure type. Neither method is a Python assert statement removed by -O. The fixture prints a success marker only after both checks complete.
Framework methods are not full-suite orchestration
This small program calls two methods directly, so it demonstrates checking rather than test discovery or runner summaries. A local project should organise discovered unittest cases and use an approved runner that reports which tests passed, failed or errored. Do not launch python -O or a second interpreter from a browser lesson.
Production validation errors describe invalid requests; test failures describe a mismatch with an expected contract. Keep those roles distinct. The sample intentionally accepts any value supporting the comparison; a stricter numeric type policy would need additional validation and tests, not an unexplained claim that an annotation enforces it.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
import unittestLoad standard-library checking tools.
if value <= 0:Validate the required positive domain.
raise ValueError("Expected positive")Reject invalid values explicitly, independently of assert.
case = unittest.TestCase()Create an assertion-method provider for this small example.
case.assertEqual(positive(2), 2)Check a successful return.
with case.assertRaises(ValueError):Require a ValueError from the scoped call.
positive(0)Exercise the nonpositive boundary.
print("2 unittest checks passed")Display the marker after both checks succeed.
Python can remove assert statements with optimisation flags. Use explicit exceptions for production validation. For a test suite, use unittest or another reviewed runner that reports failures and test discovery correctly.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Add another valid boundary.
Try: Add case.assertEqual(positive(1), 1) before the print.
The check passes; update the marker to 3 checks if you keep the new test.
Demonstrate the wrong rejection type.
Try: Replace raise ValueError("Expected positive") with raise TypeError("Wrong type").
assertRaises(ValueError) does not accept TypeError, so the run fails visibly.
Before you move on
If a deployment enables -O, does this function still reject zero?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Yes. Its explicit if/raise branch remains. A validation rule implemented only with the assert statement could disappear in that mode.
Beyond examples
A property test checks a rule over a family of inputs. A mutation check deliberately changes correct behavior to see whether the chosen tests notice.
Understand first
A handful of expected outputs can miss an entire class of mistakes. State broader rules, then try a plausible broken implementation. Testing the tests gives useful evidence about which defects your chosen cases actually detect.
Words you will see
- Property
- A requirement that should hold for a family of valid inputs.
- Idempotent
- Applying an operation again leaves its already-transformed result unchanged.
- Mutant
- A deliberately changed implementation used to probe a test's sensitivity.
Combine properties so they constrain the behavior
A clamp must return a value between zero and one hundred, preserve already in-range values, and be idempotent. checks tries five fixed values around the boundaries. The valid clamp satisfies each property. broken omits the lower bound and returns -1 for -1, so the range condition rejects it.
Idempotence alone is weak: a function always returning zero is also idempotent. The preservation requirement rejects that function for 40. Properties complement example expectations; they need a reason grounded in the contract, not just an attractive mathematical name.
Use failure evidence without overclaiming
This is a fixed deterministic sweep, not a third-party property-testing framework or proof over all integers. A generated-input framework can explore more cases and shrink a failure to a small counterexample, but still depends on the specified properties and input strategy.
Mutation testing asks whether intentional defects are caught. One rejected mutant says nothing about unrelated defects. Coverage counts executed lines, not the strength of assertions. After a failure, keep the smallest useful regression input and explain which requirement it protects. All work here is local computation; no installation, timing measurements or processes are involved.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return max(0, min(value, 100))Bound both sides in the correct implementation.
return min(value, 100)Deliberately omit the lower bound in the mutant.
for value in (-1, 0, 40, 100, 101):Choose a small boundary-focused family.
result = function(value)Exercise whichever implementation was supplied.
if not (0 <= result <= 100 and function(result) == result):Require range and idempotence together.
if 0 <= value <= 100 and result != value:Require in-range inputs to remain unchanged.
print(checks(clamp))Display True for this sweep of the correct clamp.
print(checks(broken))Display False for the known lower-bound defect.
Property-based tests check invariants over generated cases; mutation testing asks whether intentionally broken code is caught. Neither a large coverage percentage nor a green example proves every input is correct.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Try the other missing bound.
Try: Change broken to return max(0, value).
The 101 case rejects it; the lower cases now pass.
Try a constant result.
Try: Change broken to return 0.
The preservation property rejects the 40 case even though range and idempotence hold.
Before you move on
Would range and idempotence alone reject a function returning zero for every input?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. Zero is in range and remains zero on a second call. The in-range preservation property is needed to reject that plausible wrong alternative.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.