"""Tests for the language claims the book makes. These do not test the tour script. They test Python, independently, so that a reader who distrusts a sentence in the book can run one test and settle it. python -m unittest discover -s code -t code -v """ from __future__ import annotations import copy import unittest from dataclasses import dataclass, field from typing import Final, Iterator, Protocol, runtime_checkable import tour class TestBinding(unittest.TestCase): def test_assignment_aliases_rather_than_copies(self) -> None: a = [1, 2, 3] b = a b.append(4) self.assertIs(a, b) self.assertEqual(a, [1, 2, 3, 4]) def test_shallow_copy_shares_children(self) -> None: nested = [[1], [2]] shallow = copy.copy(nested) shallow[0].append(99) self.assertEqual(nested, [[1, 99], [2]]) def test_deep_copy_shares_nothing(self) -> None: nested = [[1], [2]] deep = copy.deepcopy(nested) deep[0].append(99) self.assertEqual(nested, [[1], [2]]) def test_equal_values_are_not_the_same_object(self) -> None: self.assertEqual([1], [1]) self.assertIsNot([1], [1]) class TestImmutability(unittest.TestCase): def test_final_is_not_enforced_at_runtime(self) -> None: limit: Final = 10 limit = 11 # a type checker rejects this line; the interpreter does not self.assertEqual(limit, 11) def test_tuple_rejects_assignment(self) -> None: with self.assertRaises(TypeError): (1, 2, 3)[0] = 9 # type: ignore[index] class TestNone(unittest.TestCase): def test_or_default_swallows_falsy_values(self) -> None: def with_or(given: int | None) -> int: return given or -1 self.assertEqual(with_or(None), -1) self.assertEqual(with_or(0), -1, "this is the bug, demonstrated") def test_is_none_preserves_falsy_values(self) -> None: def safe(given: int | None) -> int: return given if given is not None else -1 self.assertEqual(safe(None), -1) self.assertEqual(safe(0), 0) def test_dict_get_supplies_a_default(self) -> None: self.assertEqual({"a": 1}.get("b", 7), 7) class TestTruthiness(unittest.TestCase): def test_empty_containers_are_falsy(self) -> None: for value in (None, False, 0, 0.0, "", [], {}, set(), ()): with self.subTest(value=value): self.assertFalse(bool(value)) def test_nonempty_containers_are_truthy(self) -> None: for value in (1, -1, "0", [0], {"a": 0}): with self.subTest(value=value): self.assertTrue(bool(value)) class TestFunctions(unittest.TestCase): def test_mutable_default_is_shared_between_calls(self) -> None: def broken(item: int, into: list[int] = []) -> list[int]: into.append(item) return into self.assertEqual(broken(1), [1]) self.assertEqual(broken(2), [1, 2]) def test_none_sentinel_fixes_it(self) -> None: def fixed(item: int, into: list[int] | None = None) -> list[int]: into = [] if into is None else into into.append(item) return into self.assertEqual(fixed(1), [1]) self.assertEqual(fixed(2), [2]) def test_keyword_only_arguments_are_enforced(self) -> None: def f(a: int, *, b: int = 0) -> int: return a + b self.assertEqual(f(1, b=2), 3) with self.assertRaises(TypeError): f(1, 2) # type: ignore[misc] def test_there_is_no_overloading(self) -> None: def g(x: int) -> str: return "first" def g(x: int) -> str: # noqa: F811 - the point of the test return "second" self.assertEqual(g(1), "second") class TestClasses(unittest.TestCase): def test_dataclass_supplies_eq_and_repr(self) -> None: spec = tour.LayerSpec("stem", 16) self.assertEqual(spec, tour.LayerSpec("stem", 16)) self.assertIn("LayerSpec(name='stem'", repr(spec)) def test_default_factory_gives_each_instance_its_own_list(self) -> None: one, two = tour.LayerSpec("a", 1), tour.LayerSpec("b", 2) one.tags.append("pruned") self.assertEqual(two.tags, []) def test_mutable_class_default_is_rejected(self) -> None: with self.assertRaises(ValueError): @dataclass class Broken: tags: list[str] = [] # type: ignore[assignment] def test_underscore_does_not_make_an_attribute_private(self) -> None: class Holder: def __init__(self) -> None: self._internal = 1 self.__mangled = 2 holder = Holder() self.assertEqual(holder._internal, 1) self.assertFalse(hasattr(holder, "__mangled")) self.assertEqual(holder._Holder__mangled, 2) # type: ignore[attr-defined] def test_protocols_are_structural(self) -> None: @runtime_checkable class HasLength(Protocol): def __len__(self) -> int: ... self.assertIsInstance([1, 2], HasLength) self.assertIsInstance(tour.LayerSpec("stem", 16), HasLength) def test_property_is_accessed_without_parentheses(self) -> None: self.assertIs(tour.LayerSpec("stem", 16).is_wide, True) self.assertIs(tour.LayerSpec("head", 3).is_wide, False) def test_dunder_call_makes_an_instance_callable(self) -> None: class Doubler: def __call__(self, v: int) -> int: return v * 2 self.assertTrue(callable(Doubler())) self.assertEqual(Doubler()(21), 42) class TestErrors(unittest.TestCase): def test_else_runs_only_when_nothing_was_raised(self) -> None: order: list[str] = [] try: order.append("try") except ValueError: order.append("except") else: order.append("else") finally: order.append("finally") self.assertEqual(order, ["try", "else", "finally"]) def test_raise_from_records_the_cause(self) -> None: with self.assertRaises(tour.ShapeError) as caught: try: int("nope") except ValueError as exc: raise tour.ShapeError("bad width") from exc self.assertIsInstance(caught.exception.__cause__, ValueError) def test_context_manager_runs_teardown(self) -> None: with tour.timed("load") as log: log.append("work") self.assertEqual(log, ["enter load", "work", "exit load"]) def test_context_manager_runs_teardown_after_an_exception(self) -> None: log: list[str] = [] with self.assertRaises(RuntimeError): with tour.timed("load") as log: raise RuntimeError("boom") self.assertEqual(log[-1], "exit load") class TestGenerators(unittest.TestCase): def test_calling_a_generator_runs_no_body(self) -> None: ran: list[str] = [] def noisy() -> Iterator[int]: ran.append("yes") yield 1 gen = noisy() self.assertEqual(ran, []) next(gen) self.assertEqual(ran, ["yes"]) def test_a_generator_is_consumed_once(self) -> None: stream = tour.batches([1, 2, 3, 4, 5], 2) self.assertEqual(list(stream), [[1, 2], [3, 4], [5]]) self.assertEqual(list(stream), []) def test_batches_covers_every_item(self) -> None: items = list(range(7)) flattened = [n for chunk in tour.batches(items, 3) for n in chunk] self.assertEqual(flattened, items) class TestTourRuns(unittest.TestCase): def test_every_lesson_executes_quietly(self) -> None: self.assertEqual(tour.main(["--quiet"]), 0) if __name__ == "__main__": unittest.main(verbosity=2)