Fixtures, mocks and stronger tests
Build independent tests and verify more than a happy-path example.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 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.
- Explain fixtures should own their state
- Apply mock a boundary, not the behaviour you need to prove
- Reason about coverage and async tests
Fixtures should own their state
A fixture is the known starting state for a test. Fresh mutable fixtures keep one test's changes from becoming another test's input.
Understand first
Tests should pass regardless of which independent test ran first. Use small in-memory factories here instead of shared globals or real files, accounts or databases.
Words you will see
- Fixture
- The starting data and resources a test needs.
- Isolation
- Keeping one test's state changes from leaking into another.
- Nested ownership
- Whether containers inside another container are shared or separate.
Create the inside as well as the outside
fixture constructs a new list containing a new dictionary containing a new tags list on every call. left and right therefore have independent mutable paths. Appending edited through left changes only its own nested tags.
The first print shows left's edit and the second shows right's empty tags. Copying one outer global list would not suffice if both lists still referred to the same dictionary. Decide which level must be independent before choosing a copying strategy.
Keep setup relevant and bounded
A factory makes ownership visible and easy to repeat. setUp in unittest can call that factory for each test. A fixture should contain enough data to expose the rule, not a large unexplained production dump.
Deepcopy is useful for some data graphs but may hide resource and identity assumptions. Files and sockets need deliberate creation and cleanup, not blind copying. This browser fixture contains only local Python objects and needs no external resources.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return [{'name': 'draft', 'tags': []}]Allocate a new outer list, dictionary and tags list each call.
left = fixture()Build the state for one test.
right = fixture()Build an independent state for another test.
left[0]['tags'].append('edited')Mutate a nested list to reveal any accidental sharing.
Create fresh mutable inputs for each test. Shared global fixtures can make order affect results. Use temporary files and controlled clocks for integration boundaries; do not write tests against a production database or real user account.
Conceptual fixture ownership, not a measured heap view
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- First callCreate outer list A, record A and tags A.
- Second callCreate outer list B, record B and tags B.
- MutationAppending through A reaches tags A only; B's tags remain empty.
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.
Edit the other branch.
Try: Append 'reviewed' to right[0]['tags'] before printing.
Each fixture shows only its own tag.
Expose shallow sharing.
Try: Replace right = fixture() with right = left.copy().
Both prints show edited because only the outer list was copied.
Before you move on
If a fresh third fixture is created after left is edited, what tags should it contain?
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
An empty list. The function builds its literals each call; it does not copy the edited left object or remember earlier calls.
Mock a boundary, not the behaviour you need to prove
A test double replaces a boundary with controlled behaviour so a test can examine the real consumer without using an external service.
Understand first
Use a local function to stand in for a network read. Keep the transformation under test real. Otherwise the test may only prove that a fake returned the answer it was told to return.
Words you will see
- Test double
- A controlled replacement for one dependency in a test.
- Boundary
- The point where application logic calls an external dependency.
- Interaction assertion
- A check of how a dependency was used, when that use is part of the contract.
Replace the read, not the transformation
load_label receives a reader, calls it with api, and strips and uppercases its result. fake_read records the requested key and supplies text with outer spaces. The printed API therefore depends on the real strip-and-uppercase behaviour.
The recorded ['api'] shows exactly one read for the required key. This call count is relevant here because the contract says one read. In other tests, asserting every implementation detail can make harmless refactors fail.
Local tests do not prove the real adapter
The fake has no network and no delay, so the result is deterministic. A production adapter still needs separate contract or integration tests for serialization, errors, timeouts and cleanup. Passing this example does not prove a service exists or is reachable.
unittest.mock can provide richer call assertions, but a tiny explicit function is easier to read for one boundary. Inject failure deliberately when error propagation matters. Do not catch all exceptions and substitute an empty response, because that hides the failure being tested.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
return read('api').strip().upper()Perform the real logic using one injected read.
calls = []Keep boundary observations local to this example.
calls.append(key)Record which input the consumer requested.
print(load_label(fake_read))Run the actual consumer with a deterministic dependency.
A unit test may substitute a network client, but a test that mocks the function under test proves little. Add contract/integration tests for the real adapter. Assert calls only when the interaction itself is part of the contract.
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.
Vary boundary data.
Try: Change the fake return to ' worker '.
The result becomes WORKER and the requested key remains api.
Expose duplicate interactions.
Try: Add read('api') before the return in load_label.
The call list now has two entries, violating a one-read contract even if the label looks correct.
Before you move on
If a fresh fake returns ' queue ', should an assertion expecting API pass?
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. The real consumer should return QUEUE. A test that still passes may have replaced the consumer itself or omitted a meaningful value assertion.
A deterministic exception test
An exception assertion checks that an operation fails in the expected way. A recorded test result distinguishes assertion failures from unexpected errors.
Understand first
Use unittest when a standard-library runner is enough. Include empty input and expected exceptions, not just ordinary values. The test runner must record success rather than hiding exceptions outside the test.
Words you will see
- Assertion
- A check that raises a test failure when a required condition is false.
- Expected exception
- A declared error type that a particular input should produce.
- TestResult
- The unittest object recording tests run, failures and errors.
Read the runner's evidence
ParseTests inherits unittest.TestCase. runTest enters assertRaises(ValueError), so int('not-a-number') must raise that type. If it returns normally the test fails; an unrelated exception is an error. The second assertion checks the empty-sum identity, zero.
The manually created TestResult avoids default runner output and remains deterministic. Running one test records testsRun as 1. With neither failed assertions nor unexpected errors the printed counts are 1 0 0.
Expected failure is narrow, not suppressed
assertRaises should cover only the operation expected to fail. A huge context could pass because a later unrelated line raises the same exception. Inspect exception messages only when the message itself is a stable contract.
A successful test proves these checks on these inputs, not all parsing behaviour. pytest offers another runner and richer fixture conventions, but it is not installed by this example. Plain asserts are also useful in public browser checks; use an actual test runner for a maintained suite.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
with self.assertRaises(ValueError):Require one specific failure category inside this small scope.
int('not-a-number')Trigger the documented conversion failure.
self.assertEqual(sum([]), 0)Check an independent empty-input result.
ParseTests().run(result)Record the executed test in the explicit result object.
The standard-library runner records an expected exception and an empty-input assertion without relying on third-party packages.
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.
Remove the expected failure.
Try: Replace 'not-a-number' with '12'.
The recorded failure count becomes 1 because conversion now succeeds.
Break the empty-case assertion.
Try: Change the expected sum from 0 to 1.
One assertion failure is recorded while testsRun remains 1.
Before you move on
If a fresh test changes int('not-a-number') to int('12'), what result category changes?
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
The expected exception is absent, so assertRaises records a failure. The runner still runs one test; a run count alone is not success.
Where this idea earns its place
Fixtures make a test's prerequisites explicit and repeatable. They should own the resources and mutable state they create, then clean only those resources. A shared dictionary or open connection reused carelessly can make one test alter another's starting point and conceal an order dependency.
Follow the mechanism step by step
Mocks replace selected boundaries; they do not prove that the real adapter behaves the same way. A unit test can verify a retry policy with a scripted fake, while an integration fixture server verifies actual status, timeout and body handling. Keep both layers so confidence is tied to what was truly executed.
Work through a concrete application
Create a fresh input graph for every ownership-sensitive test. For a parser, vary valid and invalid records while asserting exact classification. For time-dependent rules, inject a clock. For concurrent transitions, coordinate events or barriers so the intended interleaving is established rather than hoping a sleep is long enough.
Failure cases and misleading shortcuts
A mock that accepts any arguments may hide an invalid request shape. Over-specifying every internal helper call makes harmless refactoring fail tests. Property generation can also produce meaningless inputs unless the generator respects the domain assumptions or deliberately tests their rejection.
Cost, ownership and alternatives
A broad property suite costs more execution time and may need shrinking or reproducible seeds to make failures actionable. Integration databases and workers need bounded startup, deadlines and cleanup. Separate unavailable infrastructure from an application assertion failure rather than reporting both as a normal wrong-answer result.
Verify the contract
Add tests that run independently and in a varied order. Check that resources close after exceptions and that injected failures retain the correct error. Validate representative real-adapter behaviour in addition to fakes. A successful unittest fixture or pytest example does not establish that an entire packaged application is installable.
Transfer question: When should an interaction assertion be part of a test?
When the interaction is itself required behaviour, such as not charging twice or sending an idempotency key. Avoid asserting incidental helper call counts that are irrelevant to the public contract, since they make tests brittle without protecting the intended outcome.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Rebuild: A deterministic exception test
Without copying the worked code, reproduce its observable contract: The standard-library runner records an expected exception and an empty-input assertion without relying on third-party packages. Then change one boundary input and explain the result.
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.
Build independent nested fixtures
Build a fresh list of records from a list of names. Each record has exactly name and an independent empty tags list; separate calls must not share mutable state.
The contract
- Input is a list of strings; preserve order and repeated names.
- Return a fresh list of dicts with exactly name and tags. Every tags list must be a new empty list.
- Do not change names. Calls, records and tags must have independent mutable ownership. No I/O.
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.
- one
source = ['Ada'] before = source.copy() result = fresh_fixture(source) assert type(result) is list and result == [{'name': 'Ada', 'tags': []}] assert source == before and result is not source assert type(result[0]) is dict and type(result[0]['tags']) is list - empty
source = [] before = source.copy() result = fresh_fixture(source) assert type(result) is list and result == [] assert source == before and result is not source
- repeated independent records
source = ['x', 'x'] before = source.copy() result = fresh_fixture(source) assert type(result) is list and result == [{'name': 'x', 'tags': []}, {'name': 'x', 'tags': []}] assert source == before and result is not source assert result[0] is not result[1] and result[0]['tags'] is not result[1]['tags'] result[0]['tags'].append('a') assert result[1]['tags'] == [] - separate calls
source = ['x'] left = fresh_fixture(source) right = fresh_fixture(source) assert type(left) is list and type(right) is list and left == right == [{'name': 'x', 'tags': []}] assert left is not right and left[0] is not right[0] and left[0]['tags'] is not right[0]['tags'] left[0]['tags'].append('a') assert right[0]['tags'] == [] and source == ['x'] - blank name
source = [''] before = source.copy() result = fresh_fixture(source) assert type(result) is list and result == [{'name': '', 'tags': []}] assert source == before and result is not source - order and keys
source = ['b', 'a'] before = source.copy() result = fresh_fixture(source) assert type(result) is list and result == [{'name': 'b', 'tags': []}, {'name': 'a', 'tags': []}] assert source == before and result is not source assert all(type(row) is dict and set(row) == {'name', 'tags'} for row in result) assert result[0]['tags'] is not result[1]['tags']
Why is a fresh outer list insufficient?
Nested dicts and lists could still be shared. The factory creates all mutable levels in O(n) construction work and O(n) containers, reusing immutable string names safely.
Run independent callback cases
Call a supplied function once with a fresh shallow copy of each list case and collect its results. A callback may mutate its case list without editing the caller's case lists.
The contract
- Input is a list of lists of immutable integers; cases can repeat the same list object.
- Call operation once per position, in order, with an independent shallow list copy. Collect exact results in a new list.
- Preserve outer and inner inputs; callback errors propagate. Nested mutable elements are outside this contract. No I/O.
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.
- sums
source = [[1, 2], [], [4]] result = run_cases(source, sum) assert type(result) is list and result == [3, 0, 4] and result is not source and source == [[1, 2], [], [4]]
- empty no calls
source = [] calls = [] result = run_cases(source, lambda case: calls.append(case)) assert type(result) is list and result == [] and result is not source and calls == [] and source == []
- mutating callback
source = [[1, 2], [3]] result = run_cases(source, lambda case: case.pop()) assert type(result) is list and result == [2, 3] and result is not source and source == [[1, 2], [3]]
- repeated alias
shared = [1] source = [shared, shared] def mutate(case): case.append(9) return len(case) result = run_cases(source, mutate) assert type(result) is list and result == [2, 2] and result is not source assert shared == [1] and source[0] is source[1] is shared - callback copy identity
source = [[1], [1]] seen = [] def observe(case): seen.append(case) return case result = run_cases(source, observe) assert type(result) is list and result == [[1], [1]] and result is not source assert result[0] is seen[0] and result[1] is seen[1] assert seen[0] is not source[0] and seen[1] is not source[1] and seen[0] is not seen[1] and source == [[1], [1]] - empty case
source = [[], []] result = run_cases(source, len) assert type(result) is list and result == [0, 0] and result is not source and source == [[], []]
Why restrict elements to immutable integers?
A shallow list copy isolates outer edits, not edits to nested mutable elements. Work is proportional to total copied elements plus callback cost, and retained results and callback-owned copies determine peak storage.
Transfer: report independent sorting properties
Instead of running fixed cases, compare a supplied candidate list with the original integer list. Return independent booleans for order, multiplicity and freshness; a candidate need not be correct.
The contract
- Inputs are lists of integers, possibly the same object. Do not mutate either input.
- Return a fresh dict with exactly ordered, same_items and fresh, each an exact bool.
- Order is nondecreasing; same_items includes duplicate counts; freshness is identity, not equality. Empty lists are ordered. No I/O.
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
left = [2, 1, 1] right = [1, 1, 2] result = sort_properties(left, right) assert type(result) is dict and result == {'ordered': True, 'same_items': True, 'fresh': True} assert all(type(x) is bool for x in result.values()) and result is not left and result is not right assert left == [2, 1, 1] and right == [1, 1, 2] - lost duplicate
left = [2, 1, 1] right = [1, 2] result = sort_properties(left, right) assert type(result) is dict and result == {'ordered': True, 'same_items': False, 'fresh': True} assert all(type(x) is bool for x in result.values()) and left == [2, 1, 1] and right == [1, 2] - wrong order
left = [1, 2] right = [2, 1] result = sort_properties(left, right) assert type(result) is dict and result == {'ordered': False, 'same_items': True, 'fresh': True} assert all(type(x) is bool for x in result.values()) and left == [1, 2] and right == [2, 1] - same object
source = [1, 2] result = sort_properties(source, source) assert type(result) is dict and result == {'ordered': True, 'same_items': True, 'fresh': False} assert all(type(x) is bool for x in result.values()) and source == [1, 2] - empty distinct
left = [] right = [] result = sort_properties(left, right) assert type(result) is dict and result == {'ordered': True, 'same_items': True, 'fresh': True} assert all(type(x) is bool for x in result.values()) and left == [] and right == [] - invented item and fresh report
left = [1] right = [1, 2] result = sort_properties(left, right) other = sort_properties(left, right) assert type(result) is dict and result == {'ordered': True, 'same_items': False, 'fresh': True} assert all(type(x) is bool for x in result.values()) and result is not other assert left == [1] and right == [1, 2]
Why not compare sets?
Sets discard multiplicity and would accept lost duplicates. Counter uses expected linear work under ordinary bounded-cost integer hashing, potentially worse with collisions, and O(u) distinct-key storage; order checking is linear.
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 milestoneProperties and mutations
A property describes a rule that should hold across many inputs. Multiple properties are needed when one rule permits a wrong algorithm.
Understand first
A sorted output must be ordered and preserve item counts. Checking only order accepts a function that always returns an empty list. Small exhaustive cases give deterministic evidence without optional property-testing packages.
Words you will see
- Property
- A rule applied to a family of inputs.
- Multiset
- Items together with how many times each occurs, ignoring order.
- Mutation test
- A deliberate bug introduced to check whether tests reject it.
Combine independent requirements
The product call generates every length-three tuple over 0 and 1, so there are eight cases. Each tuple becomes a fresh list. sorted creates an ordered list, and adjacent comparisons check order without assuming a particular example.
Counter compares multiplicities, catching an implementation that drops repeated values. The final assertion checks that the original values equal the untouched tuple. These rules complement each other: order alone would accept empty output and a multiset alone would accept unchanged unsorted input.
Bound the evidence honestly
Eight binary cases cover repeats and different small orders, but not every integer, length or implementation failure. Add targeted boundary and invalid-input examples. Hypothesis can explore and shrink many cases, but is a separate optional tool rather than a browser dependency.
Try changing sorted(values) to sorted(set(values)) as a mutation: order remains valid, but Counter fails on repeated input. A useful mutation is plausible and meaningfully wrong, not only a syntax error. Passing these public checks is feedback, not proof of mastery.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
for items in product((0, 1), repeat=3):Enumerate all eight small cases without random sampling.
result = sorted(values)Exercise the operation on a fresh list.
assert Counter(result) == Counter(values)Detect lost or invented repeated items.
checked += 1Count only cases whose properties all succeeded.
A sorting property might require ordered output with the same multiset of items, not just one expected array. A mutation test intentionally changes a comparison to see whether tests catch it. Property-based tooling such as Hypothesis and fixture tooling such as pytest are optional dependencies, not silently installed runtimes.
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.
Inject a realistic bug.
Try: Replace sorted(values) with sorted(set(values)).
An assertion fails when duplicates are lost, even though output remains ordered.
Expand the finite domain.
Try: Change product((0, 1), repeat=3) to product((-1, 0, 1), repeat=3).
The count becomes 27. This expands evidence but is still a bounded family.
Before you move on
Would a fresh wrong sorter returning [0, 1] for [1, 0, 1] satisfy both main properties?
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. It is ordered but loses one occurrence of 1, so the Counter comparison rejects it.
Coverage and async tests
Coverage measures which code ran, not whether meaningful assertions were made. Repeated calls and cleanup need their own behavioural checks.
Understand first
Use controlled coordination instead of real sleeps for timing-sensitive tests. Here a small local cleanup example tests both the returned value and release after a declared failure, without threads or a clock.
Words you will see
- Coverage
- Evidence that a line or branch executed during a test run.
- Cleanup
- Releasing owned state or resources when work finishes or fails.
- finally
- A block that runs when leaving try, including during exception propagation.
Observe release on both paths
use marks state as open and returns ready inside try on success. Its finally resets the flag before the caller receives the result. On the second call fail=True raises ValueError, but the same release step happens while that error propagates.
The example catches only the deliberately introduced ValueError to display a fixture observation. It does not replace the error with a successful result. Both paths print False for the resource flag after leaving use.
Turn requirements into observations
A line could execute without any test checking that the flag became False. Conversely, testing only the success branch misses exception cleanup. Coverage helps find unvisited code, while value, error and state assertions explain what correct behaviour means.
For asynchronous resources also test cancellation and shutdown ordering with controlled events or a fake clock. A real sleep makes tests slow and race-prone. This example does not claim to model an event loop; it isolates a cleanup invariant with deterministic local state.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
state['open'] = TrueAcquire the conceptual local resource.
raise ValueError('fixture failure')Create one declared failure path.
finally:Run release while leaving either path.
state['open'] = FalseRestore the ownership invariant before control reaches the caller.
Coverage reports executed lines, not correct behaviour. Test cancellation, timeout, invalid data, repeated calls and cleanup where relevant. Avoid sleep-based race tests; coordinate using events/barriers and assert invariant outcomes.
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.
Show a cleanup defect.
Try: Replace the final assignment in finally with pass.
Both observations show True; return values alone would miss the leak.
Repeat the successful path.
Try: Add another print(use(), state['open']).
The same ready False outcome repeats because each call releases its state.
Before you move on
If a fresh test checks only the string 'ready', could a missing finally escape detection?
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. The return could remain correct while open stays True. Add a state assertion after success and after an expected failure.
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.