{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "f39d9d77-c336-42ad-a1a3-a4c28be72888",
   "metadata": {},
   "source": [
    "# Unit Testing\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "c62714aa",
   "metadata": {
    "tags": [
     "hide-input",
     "thebe-init"
    ]
   },
   "outputs": [],
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "\n",
    "current = Path.cwd()\n",
    "for parent in [current, *current.parents]:\n",
    "    if (parent / '_config.yml').exists():\n",
    "        project_root = parent  # ← Add project root, not chapters\n",
    "        break\n",
    "else:\n",
    "    project_root = Path.cwd().parent.parent\n",
    "\n",
    "sys.path.insert(0, str(project_root))\n",
    "\n",
    "from shared import thinkpython, diagram, jupyturtle\n",
    "from shared.download import download\n",
    "\n",
    "# Register as top-level modules so direct imports work in subsequent cells\n",
    "sys.modules['thinkpython'] = thinkpython\n",
    "sys.modules['diagram'] = diagram\n",
    "sys.modules['jupyturtle'] = jupyturtle"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "goals-0502",
   "metadata": {},
   "source": [
    "**Learning goals:** By the end of this section you will be able to:\n",
    "\n",
    "- Explain what a unit test is and how it differs from integration and end-to-end tests\n",
    "- Write test functions with plain `assert` and run them with `pytest`, in a notebook and from the command line\n",
    "- Check that code raises the expected exception with `pytest.raises`\n",
    "- Write class-based tests with `unittest.TestCase`, including `setUp` and `tearDown`\n",
    "- Embed examples in docstrings and run them as doctests\n",
    "- Replace external dependencies in tests with `unittest.mock.patch` and `monkeypatch`\n",
    "- Run one test over many inputs with `@pytest.mark.parametrize`\n",
    "- Read a test coverage report and use it to find untested code"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "701137cb",
   "metadata": {},
   "source": [
    "In 5.1 you wrote code to handle errors at runtime. Unit tests are how you verify that code actually works.\n",
    "\n",
    "\"**Unit**\" means the smallest testable piece of code, typically a single function or method. The idea is to test each piece in isolation, independent of the rest of the system.\n",
    "\n",
    "Testing can be seen as a spectrum:\n",
    "| Type | Scope |\n",
    "|---|---|\n",
    "| Unit test | Single function or method |\n",
    "| Integration test | Multiple units working together |\n",
    "| End-to-end test | Entire application flow |\n",
    "\n",
    "As you can see, unit testing is the foundation: if every unit works correctly in isolation, you have much more confidence that the whole system will work when assembled.\n",
    "\n",
    "Unit testing is pre-ship verification: it runs during development to confirm your code behaves correctly before anyone uses it. It doesn't run in production at all. Unit testing answers: \"does my code actually do what I think it does?\"\n",
    "\n",
    "The whole idea of unit testing is a **design and verification** technique: you write tests that define expected behavior, then run them to confirm your code is correct. You do this before you submit it, share it, or build more code on top of it.\n",
    "\n",
    "**Test-driven development (TDD)** takes this further: you write the tests first, then write the code that makes them pass. Many developers instead write tests alongside the code or right after it, and that works well too.\n",
    "\n",
    "**Key benefits:**\n",
    "- Catch bugs before users do\n",
    "- Prevent regressions when you change code\n",
    "- Tests serve as runnable documentation\n",
    "\n",
    "Python has three main testing tools:\n",
    "\n",
    "| Tool | Style | Best for |\n",
    "|------|-------|----------|\n",
    "| `pytest` | Plain `assert`, no class needed | New projects; industry standard |\n",
    "| `unittest` | Class-based (`TestCase`) | Legacy codebases; built into the standard library |\n",
    "| `doctest` | Examples embedded in docstrings | Illustrating function behavior in docstrings |\n",
    "\n",
    "We'll cover them in that order, starting with the one you're most likely to use professionally."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "contents",
   "metadata": {},
   "source": [
    "```{contents}\n",
    ":local:\n",
    ":depth: 2\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f7273290",
   "metadata": {},
   "source": [
    "## `pytest`\n",
    "\n",
    "`pytest` is the most widely used testing framework in Python. It requires no boilerplate classes. In a typical project structure, to use `pytest` for testing, you prepare two files:\n",
    "1. Your actual code (e.g., `calc.py`)\n",
    "2. Your test functions (e.g., `test_calc.py`)\n",
    "\n",
    "You \n",
    "- write plain functions that start with `test_` so that `pytest` can discover the function as a convention \n",
    "- use plain `assert` statements, and \n",
    "- run everything with `pytest` on the command line.\n",
    "\n",
    "**Install**\n",
    "\n",
    "The `pytest` module needs to be installed in the environment. For that, use `pip` in the *terminal* with the *virtual environment* enabled. \n",
    "\n",
    "```bash\n",
    "pip install pytest\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f7273290",
   "metadata": {},
   "source": [
    "```{index} pytest, unit test\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "378f6727",
   "metadata": {},
   "source": [
    "### Inline Assertion Checks\n",
    "\n",
    "Before running `pytest`, let us take a look at how `assert` can be used for testing. You should see the similarity between using asserts manually and the `pytest` framework.\n",
    "\n",
    "Here we demonstrate the test structure using inline assertion checks:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-378f6727",
   "metadata": {},
   "source": [
    "```{index} assertion-based testing\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "6c462061",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test_add_positive PASSED\n",
      "test_add_negative PASSED\n",
      "test_subtract PASSED\n"
     ]
    }
   ],
   "source": [
    "### functions (would be calc.py in, e.g., the project root later)\n",
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "def subtract(a, b):\n",
    "    return a - b\n",
    "\n",
    "### pytest-style test functions (would go in test_calc.py later)\n",
    "def test_add_positive():\n",
    "    assert add(2, 3) == 5\n",
    "\n",
    "def test_add_negative():\n",
    "    assert add(-1, -1) == -2\n",
    "\n",
    "def test_subtract():\n",
    "    assert subtract(10, 4) == 6\n",
    "\n",
    "# Run them manually (simulating pytest discovery)\n",
    "for test_fn in [test_add_positive, test_add_negative, test_subtract]:\n",
    "    test_fn()\n",
    "    print(f'{test_fn.__name__} PASSED')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "546d3790",
   "metadata": {},
   "source": [
    "### Test Files and the `pytest` Command\n",
    "\n",
    "In a real project, your code and your tests live in separate files. `pytest` looks for files named `test_*.py` (or `*_test.py`) and runs every function in them whose name starts with `test_`.\n",
    "\n",
    "For example, suppose the module `calc.py` contains these functions:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-546d3790",
   "metadata": {},
   "source": [
    "```{index} test discovery, pytest command\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "94dc016c",
   "metadata": {},
   "outputs": [],
   "source": [
    "### the code module file: calc.py\n",
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "def subtract(a, b):\n",
    "    return a - b\n",
    "\n",
    "def divide(a, b):\n",
    "    return a / b"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3748880a",
   "metadata": {},
   "source": [
    "The test file imports the functions it tests from the module. Note that you import `calc`, without the `.py` extension."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "573a963e",
   "metadata": {
    "tags": [
     "skip-execution"
    ]
   },
   "outputs": [],
   "source": [
    "### the test file: test_calc.py\n",
    "from calc import add, subtract, divide\n",
    "\n",
    "def test_add():\n",
    "    assert add(2, 3) == 5\n",
    "\n",
    "def test_subtract():\n",
    "    assert subtract(10, 4) == 6\n",
    "\n",
    "def test_divide():\n",
    "    assert divide(10, 2) == 5.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c580076c",
   "metadata": {},
   "source": [
    "From the terminal, in the folder that contains both files, run\n",
    "\n",
    "```bash\n",
    "pytest test_calc.py -v\n",
    "```\n",
    "\n",
    "or, equivalently, `python -m pytest test_calc.py -v`. The output reports that 3 items were `collected` and that each test `PASSED`:\n",
    "\n",
    "```\n",
    "(.venv) [user]@[host]:~/workspace/py/[path]$ pytest test_calc.py -v\n",
    "====================== test session starts ======================\n",
    "platform darwin -- Python 3.13.7, pytest-9.0.3, pluggy-1.6.0 -- /Users/[user]/workspace/py/.venv/bin/python3\n",
    "cachedir: .pytest_cache\n",
    "rootdir: /Users/[user]/workspace/py/[path]\n",
    "plugins: anyio-4.11.0\n",
    "collected 3 items\n",
    "\n",
    "test_calc.py::test_add PASSED                             [ 33%]\n",
    "test_calc.py::test_subtract PASSED                        [ 66%]\n",
    "test_calc.py::test_divide PASSED                          [100%]\n",
    "\n",
    "======================= 3 passed in 0.01s =======================\n",
    "(.venv) [user]@[host]:~/workspace/py/[path]$\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8661d9c9",
   "metadata": {},
   "source": [
    "### `pytest` as Subprocess\n",
    "\n",
    "You can also run `pytest` from inside a Jupyter notebook by writing a test file to disk and running `pytest` as a subprocess:\n",
    "\n",
    "1. Write a `.py` test file to a temporary folder\n",
    "2. Run `pytest` on it with Python's `subprocess` module\n",
    "3. Capture the output and display it in the notebook\n",
    "\n",
    "One of the two tests below fails on purpose, so you can see how `pytest` reports a failure."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-8661d9c9",
   "metadata": {},
   "source": [
    "```{index} subprocess module\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "a3019e43",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m============================= test session starts ==============================\u001b[0m\n",
      "\u001b[1mcollecting ... \u001b[0mcollected 2 items\n",
      "\n",
      "test_temp.py::test_add \u001b[32mPASSED\u001b[0m\u001b[32m                                            [ 50%]\u001b[0m\n",
      "test_temp.py::test_fail \u001b[31mFAILED\u001b[0m\u001b[31m                                           [100%]\u001b[0m\n",
      "\n",
      "=================================== FAILURES ===================================\n",
      "\u001b[31m\u001b[1m__________________________________ test_fail ___________________________________\u001b[0m\n",
      "\n",
      "    \u001b[0m\u001b[94mdef\u001b[39;49;00m\u001b[90m \u001b[39;49;00m\u001b[92mtest_fail\u001b[39;49;00m():\u001b[90m\u001b[39;49;00m\n",
      ">       \u001b[94massert\u001b[39;49;00m \u001b[94m1\u001b[39;49;00m + \u001b[94m1\u001b[39;49;00m == \u001b[94m3\u001b[39;49;00m\u001b[90m\u001b[39;49;00m\n",
      "\u001b[1m\u001b[31mE       assert (1 + 1) == 3\u001b[0m\n",
      "\n",
      "\u001b[1m\u001b[31mtest_temp.py\u001b[0m:6: AssertionError\n",
      "\u001b[36m\u001b[1m=========================== short test summary info ============================\u001b[0m\n",
      "\u001b[31mFAILED\u001b[0m test_temp.py::\u001b[1mtest_fail\u001b[0m - assert (1 + 1) == 3\n",
      "\u001b[31m========================= \u001b[31m\u001b[1m1 failed\u001b[0m, \u001b[32m1 passed\u001b[0m\u001b[31m in 0.04s\u001b[0m\u001b[31m ==========================\u001b[0m\n",
      "\n"
     ]
    }
   ],
   "source": [
    "import subprocess, sys, tempfile\n",
    "from pathlib import Path\n",
    "\n",
    "with tempfile.TemporaryDirectory() as tmp:\n",
    "    # 1. Write the test file to a temporary folder (deleted after the with block)\n",
    "    Path(tmp, \"test_temp.py\").write_text(\"\"\"\n",
    "def test_add():\n",
    "    assert 1 + 1 == 2\n",
    "\n",
    "def test_fail():\n",
    "    assert 1 + 1 == 3\n",
    "\"\"\")\n",
    "\n",
    "    # 2. Run pytest in that folder; --no-header omits machine-specific paths\n",
    "    result = subprocess.run(\n",
    "        [sys.executable, \"-m\", \"pytest\", \"test_temp.py\", \"-v\", \"--no-header\"],\n",
    "        cwd=tmp, capture_output=True, text=True,\n",
    "    )\n",
    "\n",
    "# 3. Display the output in the notebook\n",
    "print(result.stdout)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4fad5e2c",
   "metadata": {},
   "source": [
    "### Jupyter Inline Testing\n",
    "\n",
    "In addition to running the `pytest` testing file in the terminal, you can also run the tests inside the Jupyter notebook using the `ipytest` plugin. \n",
    "\n",
    "Note that `%%ipytest` does the discovering and calling of the test functions automatically within that cell, that's why in the example below you don't see the test functions being called. The workflow is:\n",
    "\n",
    "1. User runs the cell with %%ipytest\n",
    "2. ipytest scans the cell for any function whose name starts with test_\n",
    "3. It calls all of them via `pytest` under the hood\n",
    "4. Reports pass/fail"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-4fad5e2c",
   "metadata": {},
   "source": [
    "```{index} ipytest\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "7b2ae89b",
   "metadata": {},
   "outputs": [],
   "source": [
    "### install ipytest for in-notebook testing\n",
    "### live code may require you to install it again: ModuleNotFoundError: No module named 'ipytest'\n",
    "# %pip install ipytest -q"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "6f52426d",
   "metadata": {},
   "outputs": [],
   "source": [
    "import ipytest\n",
    "ipytest.autoconfig()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "4a73dc4f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m.\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m.\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m                                                                                           [100%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[32m\u001b[32m\u001b[1m2 passed\u001b[0m\u001b[32m in 0.01s\u001b[0m\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "%%ipytest\n",
    "\n",
    "def test_add_positive():\n",
    "    assert add(2, 3) == 5\n",
    "    \n",
    "def test_add_negative():\n",
    "    assert add(-1, -1) == -2"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "pytest-raises-md",
   "metadata": {},
   "source": [
    "### Testing Exceptions with `pytest.raises`\n",
    "\n",
    "In {ref}`Raising Exceptions <ch05-raising-exceptions>` you wrote functions that raise an exception when they receive bad input. That behavior deserves a test too. Put the call inside a `with pytest.raises(...)` block: the test passes only if the block raises the expected exception, and fails if it raises nothing. Add `match=` to also check the error message."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-pytest-raises-md",
   "metadata": {},
   "source": [
    "```{index} pytest.raises()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "pytest-raises-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m.\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m.\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m.\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m                                                                                          [100%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[32m\u001b[32m\u001b[1m3 passed\u001b[0m\u001b[32m in 0.01s\u001b[0m\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "%%ipytest\n",
    "\n",
    "import pytest\n",
    "\n",
    "def divide(a, b):\n",
    "    if b == 0:\n",
    "        raise ValueError(\"b cannot be zero\")\n",
    "    return a / b\n",
    "\n",
    "def test_divide():\n",
    "    assert divide(10, 2) == 5.0\n",
    "\n",
    "def test_divide_by_zero():\n",
    "    with pytest.raises(ValueError):\n",
    "        divide(10, 0)\n",
    "\n",
    "def test_divide_by_zero_message():\n",
    "    with pytest.raises(ValueError, match=\"cannot be zero\"):\n",
    "        divide(10, 0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "bed1beed",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Write pytest-style tests\n",
    "#   Write three test functions for `count_vowels(s)` defined below:\n",
    "#     1. test_count_vowels_typical: a string with multiple vowels (e.g., 'hello')\n",
    "#     2. test_count_vowels_none: a string with no vowels (e.g., 'gym')\n",
    "#     3. test_count_vowels_empty: the empty string should return 0\n",
    "#   Each function should use plain `assert` (no `self`, no class).\n",
    "#   After writing them, call each one to verify they pass.\n",
    "\n",
    "def count_vowels(s):\n",
    "    \"\"\"Return the number of vowels (a, e, i, o, u) in s (case-insensitive).\"\"\"\n",
    "    count = 0\n",
    "    for c in s.lower():\n",
    "        if c in 'aeiou':\n",
    "            count += 1\n",
    "    return count\n",
    "\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "cc6bc28e",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "test_count_vowels_typical PASSED\n",
      "test_count_vowels_none PASSED\n",
      "test_count_vowels_empty PASSED\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "\n",
    "def count_vowels(s):\n",
    "    \"\"\"Return the number of vowels (a, e, i, o, u) in s (case-insensitive).\"\"\"\n",
    "    count = 0\n",
    "    for c in s.lower():\n",
    "        if c in 'aeiou':\n",
    "            count += 1\n",
    "    return count\n",
    "\n",
    "def test_count_vowels_typical():\n",
    "    assert count_vowels('hello') == 2\n",
    "    assert count_vowels('AEIOU') == 5\n",
    "\n",
    "def test_count_vowels_none():\n",
    "    assert count_vowels('gym') == 0\n",
    "    assert count_vowels('rhythm') == 0\n",
    "\n",
    "def test_count_vowels_empty():\n",
    "    assert count_vowels('') == 0\n",
    "\n",
    "for fn in [test_count_vowels_typical, test_count_vowels_none, test_count_vowels_empty]:\n",
    "    fn()\n",
    "    print(f'{fn.__name__} PASSED')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22dec523",
   "metadata": {},
   "source": [
    "## `unittest`\n",
    "\n",
    "Python's standard library includes `unittest`, a class-based testing framework. You'll encounter it in older codebases and it's worth knowing, but for new projects `pytest` is almost always the better choice.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-22dec523",
   "metadata": {},
   "source": [
    "```{index} unittest module, TestCase, assertEqual()\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "s2b-unittest-class-note",
   "metadata": {},
   "source": [
    ":::{note}\n",
    "`unittest` asks you to put your tests inside a **class**. Classes are covered in Chapter 9; for now you only need to copy one pattern:\n",
    "\n",
    "```python\n",
    "class TestSomething(unittest.TestCase):\n",
    "    def test_one_behavior(self):\n",
    "        self.assertEqual(actual, expected)\n",
    "```\n",
    "\n",
    "- `class TestSomething(unittest.TestCase):` creates a group of tests. The name in parentheses tells Python that your class is a kind of `TestCase`, so it gets all the `assertX()` methods.\n",
    "- Each test is a function written inside the class (indented under it). A function that belongs to a class is called a **method**.\n",
    "- Every method takes `self` as its first parameter. `self` is how a test reaches the helpers it inherited, as in `self.assertEqual(...)`. You never pass `self` yourself; `unittest` supplies it when it runs the test.\n",
    "\n",
    "Chapter 9 explains what classes, methods, and `self` really are.\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "eb13754a",
   "metadata": {},
   "source": [
    "In the sample code below, part 2 is how you use `unittest`. You:\n",
    "- subclass `unittest.TestCase`, \n",
    "- write `test_*` methods, and \n",
    "- use **`self.assertX()`** helper methods for assertions.\n",
    "\n",
    "The syntax of `assertEqual()` is `self.assertEqual(actual, expected)`. For example, `assertEqual(first, second)` checks that `first == second`. If not, the test fails with a message showing both values.\n",
    "\n",
    "\n",
    "In part 3, we start with `import io` because **`unittest.TextTestRunner`** writes its output to a file-like stream. By default that goes to `stderr`, which in some notebook environments doesn't display inline with the cell output.\n",
    "\n",
    "`io.StringIO()` is an in-memory text buffer that acts like a file; so the runner writes into it, and then `print(buf.getvalue())` sends the captured text to the notebook's normal output. \n",
    "\n",
    "Without `io` to create `buf`, you'd pass `stream=sys.stderr` (the default), which may appear in a different output area or not at all depending on the environment.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "d1a5885e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test_calculate_grade_edge_cases (__main__.TestGradeCalculation.test_calculate_grade_edge_cases)\n",
      "Test edge cases for grade calculation. ... ok\n",
      "test_calculate_grade_invalid_input (__main__.TestGradeCalculation.test_calculate_grade_invalid_input)\n",
      "Test that invalid inputs raise appropriate exceptions. ... ok\n",
      "test_calculate_grade_normal_cases (__main__.TestGradeCalculation.test_calculate_grade_normal_cases)\n",
      "Test normal grade calculations. ... ok\n",
      "test_letter_grade_conversion (__main__.TestGradeCalculation.test_letter_grade_conversion)\n",
      "Test letter grade assignments. ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 4 tests in 0.000s\n",
      "\n",
      "OK\n",
      "\n",
      "All tests passed.\n"
     ]
    }
   ],
   "source": [
    "import unittest\n",
    "\n",
    "# Example: Testing a simple function with unit tests\n",
    "\n",
    "### part 1: The code we want to test\n",
    "def calculate_grade(score, total_points):\n",
    "    \"\"\"Calculate percentage grade from score and total points.\"\"\"\n",
    "    if total_points <= 0:\n",
    "        raise ValueError(\"Total points must be positive\")\n",
    "    if score < 0:\n",
    "        raise ValueError(\"Score cannot be negative\") \n",
    "    if score > total_points:\n",
    "        raise ValueError(\"Score cannot exceed total points\")\n",
    "    \n",
    "    percentage = (score / total_points) * 100\n",
    "    return round(percentage, 2)\n",
    "\n",
    "def get_letter_grade(percentage):\n",
    "    \"\"\"Convert percentage to letter grade.\"\"\"\n",
    "    if percentage >= 90:\n",
    "        return 'A'\n",
    "    elif percentage >= 80:\n",
    "        return 'B'\n",
    "    elif percentage >= 70:\n",
    "        return 'C'\n",
    "    elif percentage >= 60:\n",
    "        return 'D'\n",
    "    else:\n",
    "        return 'F'\n",
    "\n",
    "### part 2: Unit tests for our functions\n",
    "class TestGradeCalculation(unittest.TestCase):\n",
    "    \"\"\"Test cases for grade calculation functions.\"\"\"\n",
    "    \n",
    "    def test_calculate_grade_normal_cases(self):\n",
    "        \"\"\"Test normal grade calculations.\"\"\"\n",
    "        self.assertEqual(calculate_grade(85, 100), 85.0)\n",
    "        self.assertEqual(calculate_grade(95, 100), 95.0)\n",
    "        self.assertEqual(calculate_grade(50, 100), 50.0)\n",
    "        self.assertEqual(calculate_grade(0, 100), 0.0)\n",
    "    \n",
    "    def test_calculate_grade_edge_cases(self):\n",
    "        \"\"\"Test edge cases for grade calculation.\"\"\"\n",
    "        self.assertEqual(calculate_grade(100, 100), 100.0)\n",
    "        self.assertEqual(calculate_grade(87, 92), 94.57)\n",
    "    \n",
    "    def test_calculate_grade_invalid_input(self):\n",
    "        \"\"\"Test that invalid inputs raise appropriate exceptions.\"\"\"\n",
    "        with self.assertRaises(ValueError):\n",
    "            calculate_grade(85, 0)  # Zero total points\n",
    "        \n",
    "        with self.assertRaises(ValueError):\n",
    "            calculate_grade(-10, 100)  # Negative score\n",
    "        \n",
    "        with self.assertRaises(ValueError):\n",
    "            calculate_grade(110, 100)  # Score exceeds total\n",
    "    \n",
    "    def test_letter_grade_conversion(self):\n",
    "        \"\"\"Test letter grade assignments.\"\"\"\n",
    "        self.assertEqual(get_letter_grade(95), 'A')\n",
    "        self.assertEqual(get_letter_grade(85), 'B')\n",
    "        self.assertEqual(get_letter_grade(75), 'C')\n",
    "        self.assertEqual(get_letter_grade(65), 'D')\n",
    "        self.assertEqual(get_letter_grade(55), 'F')\n",
    "        \n",
    "        # Test boundary conditions\n",
    "        self.assertEqual(get_letter_grade(90), 'A')\n",
    "        self.assertEqual(get_letter_grade(89.9), 'B')\n",
    "\n",
    "### part 3: Run the tests and display results\n",
    "import io\n",
    "buf = io.StringIO()\n",
    "runner = unittest.TextTestRunner(stream=buf, verbosity=2)\n",
    "result = runner.run(unittest.TestLoader().loadTestsFromTestCase(TestGradeCalculation))\n",
    "print(buf.getvalue())\n",
    "if result.wasSuccessful():\n",
    "    print(\"All tests passed.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "80d517be",
   "metadata": {},
   "source": [
    "### When Tests Fail\n",
    "\n",
    "The example above has tests that all pass. But finding failing tests is the whole point. Here's a function with a deliberate bug. It refuses to raise a negative base to a power, returning a string instead of a number. The test suite will expose it.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-80d517be",
   "metadata": {},
   "source": [
    "```{index} failing test\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "7b59593b-fail-test",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test_negative_base_even_exponent (__main__.TestPower.test_negative_base_even_exponent) ... FAIL\n",
      "test_negative_base_odd_exponent (__main__.TestPower.test_negative_base_odd_exponent) ... FAIL\n",
      "test_positive_base (__main__.TestPower.test_positive_base) ... ok\n",
      "\n",
      "======================================================================\n",
      "FAIL: test_negative_base_even_exponent (__main__.TestPower.test_negative_base_even_exponent)\n",
      "----------------------------------------------------------------------\n",
      "Traceback (most recent call last):\n",
      "  File \"/var/folders/g4/v24tl8t172g5d7rzsd63y51w0000gp/T/ipykernel_63222/2752416876.py\", line 14, in test_negative_base_even_exponent\n",
      "    self.assertEqual(my_power(-2, 2), 4)   # (-2)² = 4, not an error string\n",
      "    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^\n",
      "AssertionError: 'Error: negative base' != 4\n",
      "\n",
      "======================================================================\n",
      "FAIL: test_negative_base_odd_exponent (__main__.TestPower.test_negative_base_odd_exponent)\n",
      "----------------------------------------------------------------------\n",
      "Traceback (most recent call last):\n",
      "  File \"/var/folders/g4/v24tl8t172g5d7rzsd63y51w0000gp/T/ipykernel_63222/2752416876.py\", line 17, in test_negative_base_odd_exponent\n",
      "    self.assertEqual(my_power(-3, 3), -27)\n",
      "    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^\n",
      "AssertionError: 'Error: negative base' != -27\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 3 tests in 0.000s\n",
      "\n",
      "FAILED (failures=2)\n",
      "\n",
      "2 failure(s), 0 error(s)\n"
     ]
    }
   ],
   "source": [
    "import io\n",
    "\n",
    "def my_power(base, exponent):\n",
    "    \"\"\"Return base raised to exponent. Bug: rejects negative bases.\"\"\"\n",
    "    if base < 0:\n",
    "        return \"Error: negative base\"   # ← bug: should just compute it\n",
    "    return base ** exponent\n",
    "\n",
    "class TestPower(unittest.TestCase):\n",
    "    def test_positive_base(self):\n",
    "        self.assertEqual(my_power(2, 3), 8)\n",
    "\n",
    "    def test_negative_base_even_exponent(self):\n",
    "        self.assertEqual(my_power(-2, 2), 4)   # (-2)² = 4, not an error string\n",
    "\n",
    "    def test_negative_base_odd_exponent(self):\n",
    "        self.assertEqual(my_power(-3, 3), -27)\n",
    "\n",
    "# Run and print output so the failure is visible in the notebook\n",
    "buf = io.StringIO()\n",
    "runner = unittest.TextTestRunner(stream=buf, verbosity=2)\n",
    "result = runner.run(unittest.TestLoader().loadTestsFromTestCase(TestPower))\n",
    "print(buf.getvalue())\n",
    "if result.wasSuccessful():\n",
    "    print(\"All tests passed.\")\n",
    "else:\n",
    "    print(f\"{len(result.failures)} failure(s), {len(result.errors)} error(s)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "setup-teardown-md",
   "metadata": {},
   "source": [
    "### `setUp` and `tearDown`\n",
    "\n",
    "When several tests need the same starting data, create it in a method named `setUp`. `unittest` calls `setUp` before **each** test method, so every test starts with a fresh copy, and a test that changes the data cannot affect the others. `tearDown` runs after each test, including one that fails. It is the place to release anything `setUp` created, such as an open file or a database connection."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-setup-teardown-md",
   "metadata": {},
   "source": [
    "```{index} setUp(), tearDown()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "setup-teardown-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test_add_fruit (__main__.TestFruitBasket.test_add_fruit) ... ok\n",
      "test_starts_with_two_fruits (__main__.TestFruitBasket.test_starts_with_two_fruits) ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 2 tests in 0.000s\n",
      "\n",
      "OK\n",
      "\n"
     ]
    }
   ],
   "source": [
    "class TestFruitBasket(unittest.TestCase):\n",
    "    def setUp(self):\n",
    "        # runs before each test: every test gets its own new basket\n",
    "        self.basket = [\"apple\", \"banana\"]\n",
    "\n",
    "    def tearDown(self):\n",
    "        # runs after each test: release what setUp created\n",
    "        self.basket = None\n",
    "\n",
    "    def test_add_fruit(self):\n",
    "        self.basket.append(\"cherry\")\n",
    "        self.assertEqual(len(self.basket), 3)\n",
    "\n",
    "    def test_starts_with_two_fruits(self):\n",
    "        # passes even though test_add_fruit (which runs first) appended to its basket\n",
    "        self.assertEqual(len(self.basket), 2)\n",
    "\n",
    "buf = io.StringIO()\n",
    "runner = unittest.TextTestRunner(stream=buf, verbosity=2)\n",
    "result = runner.run(unittest.TestLoader().loadTestsFromTestCase(TestFruitBasket))\n",
    "print(buf.getvalue())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "s2b-almost-equal-md",
   "metadata": {},
   "source": [
    "### Comparing Floats with `assertAlmostEqual`\n",
    "\n",
    "`assertEqual` checks for exact equality, which is a problem for floating-point results: `0.1 + 0.2` is stored as `0.30000000000000004`, not `0.3`. `self.assertAlmostEqual(first, second, places=n)` passes when `first` and `second` agree to `n` decimal places (the default is 7). Use it whenever the value you are checking comes from floating-point arithmetic."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "s2b-idx-almost-equal",
   "metadata": {},
   "source": [
    "```{index} assertAlmostEqual()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "s2b-almost-equal-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "test_sum (__main__.TestFloats.test_sum) ... ok\n",
      "test_two_places (__main__.TestFloats.test_two_places) ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 2 tests in 0.000s\n",
      "\n",
      "OK\n",
      "\n"
     ]
    }
   ],
   "source": [
    "class TestFloats(unittest.TestCase):\n",
    "    def test_sum(self):\n",
    "        # assertEqual(0.1 + 0.2, 0.3) would fail; the values differ in the 17th digit\n",
    "        self.assertAlmostEqual(0.1 + 0.2, 0.3)\n",
    "\n",
    "    def test_two_places(self):\n",
    "        # 2 / 3 is 0.6666..., which rounds to 0.67 at two decimal places\n",
    "        self.assertAlmostEqual(2 / 3, 0.67, places=2)\n",
    "\n",
    "buf = io.StringIO()\n",
    "runner = unittest.TextTestRunner(stream=buf, verbosity=2)\n",
    "result = runner.run(unittest.TestLoader().loadTestsFromTestCase(TestFloats))\n",
    "print(buf.getvalue())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "019f5e82",
   "metadata": {},
   "source": [
    "### `unittest` Conventions\n",
    "\n",
    "- **Name test methods descriptively**: `test_divide_by_zero_raises_exception` tells you exactly what's being checked; `test_division` doesn't.\n",
    "- **One behavior per test method**: instead of one `test_grade_calculation` that checks everything, write `test_grade_returns_percentage`, `test_grade_raises_on_negative_score`, etc. Narrow tests pinpoint exactly what broke.\n",
    "- **Use `setUp` for shared state**: if multiple tests need the same object, create it in `setUp` rather than repeating the construction in every method.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-019f5e82",
   "metadata": {},
   "source": [
    "```{index} test naming convention\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2e8de9b",
   "metadata": {},
   "source": [
    "### `pytest` vs `unittest`\n",
    "\n",
    "Now that you have seen both frameworks, the table below compares them across the features you're most likely to care about.\n",
    "\n",
    "| Feature | `unittest` | `pytest` |\n",
    "|---|---|---|\n",
    "| Requires class? | Yes (`TestCase`) | No |\n",
    "| Assertion style | `self.assertEqual(a, b)` | `assert a == b` |\n",
    "| Discovery | `python -m unittest` finds `test*.py` files automatically | `pytest` finds `test_*.py` and `*_test.py` files automatically |\n",
    "| Output | Minimal | Detailed, colored diff |\n",
    "| Fixtures | `setUp`/`tearDown` | `@pytest.fixture` |\n",
    "| Ecosystem | Standard library | Third-party, widely adopted |\n",
    "\n",
    "Both are valid. `unittest` is built-in; `pytest` is preferred in industry\n",
    "because its plain `assert` style produces clearer failure messages.\n",
    "\n",
    ":::{note}\n",
    "**`unittest` assertions vs. bare `assert`**\n",
    "\n",
    "`unittest`'s `assertX` methods (`assertEqual`, `assertRaises`, `assertIsNone`, etc.) are ordinary method calls, so they cannot be disabled. Bare Python `assert` statements *can* be silently disabled by running the interpreter with the `-O` (optimize) flag, which strips them from the bytecode. In practice you never run your test suite with `-O`, so this rarely matters; but it is why `assert` is discouraged for *input validation* in production code while being perfectly fine inside test functions. `pytest` still gives detailed failure messages for plain `assert` through **assertion rewriting**: when it imports a test module, it rewrites each `assert` statement so that a failure reports the values involved.\n",
    ":::\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f2e8de9b",
   "metadata": {},
   "source": [
    "```{index} pytest, unittest module\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "da7966f6",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Write a TestCase for to_celsius(f)\n",
    "#   to_celsius(f) converts Fahrenheit to Celsius: (f - 32) * 5 / 9\n",
    "#   Write a class TestToCelsius(unittest.TestCase) with three test methods:\n",
    "#     1. test_boiling: to_celsius(212) should equal 100.0\n",
    "#     2. test_freezing: to_celsius(32) should equal 0.0\n",
    "#     3. test_body_temp: to_celsius(98.6) should be approximately 37.0\n",
    "#        (hint: use assertAlmostEqual with places=1)\n",
    "#   Run using TextTestRunner with io.StringIO and verbosity=2.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "40216e16",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "test_body_temp (__main__.TestToCelsius.test_body_temp) ... ok\n",
      "test_boiling (__main__.TestToCelsius.test_boiling) ... ok\n",
      "test_freezing (__main__.TestToCelsius.test_freezing) ... ok\n",
      "\n",
      "----------------------------------------------------------------------\n",
      "Ran 3 tests in 0.000s\n",
      "\n",
      "OK\n",
      "\n",
      "All tests passed.\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import io\n",
    "\n",
    "def to_celsius(f):\n",
    "    return (f - 32) * 5 / 9\n",
    "\n",
    "class TestToCelsius(unittest.TestCase):\n",
    "    def test_boiling(self):\n",
    "        self.assertEqual(to_celsius(212), 100.0)\n",
    "\n",
    "    def test_freezing(self):\n",
    "        self.assertEqual(to_celsius(32), 0.0)\n",
    "\n",
    "    def test_body_temp(self):\n",
    "        self.assertAlmostEqual(to_celsius(98.6), 37.0, places=1)\n",
    "\n",
    "buf = io.StringIO()\n",
    "runner = unittest.TextTestRunner(stream=buf, verbosity=2)\n",
    "result = runner.run(unittest.TestLoader().loadTestsFromTestCase(TestToCelsius))\n",
    "print(buf.getvalue())\n",
    "if result.wasSuccessful():\n",
    "    print('All tests passed.')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6dd33555",
   "metadata": {},
   "source": [
    "## Doctests"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-6dd33555",
   "metadata": {},
   "source": [
    "```{index} doctest\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ec0c161",
   "metadata": {},
   "source": [
    "A **doctest** is a test embedded directly in a function's docstring. You write an example interaction using `>>>` (the Python interactive prompt), followed by the expected output. Python's `doctest` module finds and runs these examples automatically.\n",
    "\n",
    "Doctests serve two purposes at once: they document how a function works *and* verify that it actually works that way. They're best for simple input/output examples, not a replacement for `pytest` or `unittest` when you need complex setup or many edge cases.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "4ecdc88c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def uses_any(word, letters):\n",
    "    \"\"\"Checks if a word uses any of a list of letters.\n",
    "    \n",
    "    >>> uses_any('banana', 'aeiou')\n",
    "    True\n",
    "    >>> uses_any('apple', 'xyz')\n",
    "    False\n",
    "    \"\"\"\n",
    "    for letter in word.lower():\n",
    "        if letter in letters.lower():\n",
    "            return True\n",
    "    return False"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec62bdb0",
   "metadata": {},
   "source": [
    "Each test begins with `>>>`, which is used as a prompt in some Python environments to indicate where the user can type code.\n",
    "In a doctest, the prompt is followed by an expression, usually a function call.\n",
    "The following line indicates the value the expression should have if the function works correctly.\n",
    "\n",
    "In the first example, `'banana'` uses `'a'`, so the result should be `True`.\n",
    "In the second example, `'apple'` does not use any of `'xyz'`, so the result should be `False`.\n",
    "\n",
    "Outside a notebook, you would usually run doctests from the command line with `python -m doctest file.py -v`, or let pytest collect them with `pytest --doctest-modules`.\n",
    "In a notebook, we use a function from the `doctest` module called `run_docstring_examples`.\n",
    "To make it easier to use, we can wrap it in a small function that takes a function object as an argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "62bf2bad",
   "metadata": {},
   "outputs": [],
   "source": [
    "from doctest import run_docstring_examples\n",
    "\n",
    "def run_doctests(func):\n",
    "    run_docstring_examples(func, globals(), name=func.__name__)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0eeafbfb",
   "metadata": {},
   "source": [
    ":::{admonition} What are `globals()` and `__name__`?\n",
    ":class: dropdown\n",
    "\n",
    "`globals()` is a built-in that returns a dictionary of every name defined in the current scope: variables, functions, imports, everything. `run_docstring_examples` evaluates the doctest expressions inside that dictionary, so any function you've already defined (like `uses_any`) is available by name.\n",
    "\n",
    "`func.__name__` is a string attribute every function carries. It's just the name you gave it when you wrote `def`. Passing it as `name=` makes error messages say `uses_any` instead of the placeholder `NoName`.\n",
    "\n",
    "You don't need to use either directly; the `run_doctests` wrapper handles them for you. They'll reappear later when we cover namespaces and function objects.\n",
    ":::\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2ca2fb8",
   "metadata": {},
   "source": [
    "Now we can test `uses_any` like this."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "35c5c4de",
   "metadata": {},
   "outputs": [],
   "source": [
    "run_doctests(uses_any)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "df72a37e",
   "metadata": {},
   "source": [
    "`run_doctests` finds the expressions in the docstring and evaluates them.\n",
    "If the result is the expected value, the test **passes**.\n",
    "Otherwise it **fails**.\n",
    "\n",
    "If all tests pass, `run_doctests` displays no output. In that case, no news is good news.\n",
    "To see what happens when a test fails, here's an incorrect version of `uses_any`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "5974bb1d",
   "metadata": {},
   "outputs": [],
   "source": [
    "def uses_any_incorrect(word, letters):\n",
    "    \"\"\"Checks if a word uses any of a list of letters.\n",
    "    \n",
    "    >>> uses_any_incorrect('banana', 'aeiou')\n",
    "    True\n",
    "    >>> uses_any_incorrect('apple', 'xyz')\n",
    "    False\n",
    "    \"\"\"\n",
    "    for letter in word.lower():\n",
    "        if letter in letters.lower():\n",
    "            return True\n",
    "        else:\n",
    "            return False  "
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f93b688f",
   "metadata": {},
   "source": [
    "And here's what happens when we test it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "b81b70b5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "**********************************************************************\n",
      "File \"__main__\", line 4, in uses_any_incorrect\n",
      "Failed example:\n",
      "    uses_any_incorrect('banana', 'aeiou')\n",
      "Expected:\n",
      "    True\n",
      "Got:\n",
      "    False\n"
     ]
    }
   ],
   "source": [
    "run_doctests(uses_any_incorrect)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d23ecfdd",
   "metadata": {},
   "source": [
    "The output includes the example that failed, the value the function was expected to produce, and the value the function actually produced.\n",
    "\n",
    "If you are not sure why this test failed, you'll have a chance to debug it as an exercise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "0aab242c",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Fix the Failing Doctest\n",
    "#   `uses_any_incorrect` has a bug that causes one doctest to fail.\n",
    "#   1. Trace through what happens when the function is called with ('banana', 'aeiou').\n",
    "#   2. Write a corrected version called `uses_any_fixed`.\n",
    "#   3. Include the same two doctest examples and run `run_doctests(uses_any_fixed)`.\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "b562023b",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [],
   "source": [
    "### Solution\n",
    "def uses_any_fixed(word, letters):\n",
    "    \"\"\"Checks if a word uses any of a list of letters.\n",
    "\n",
    "    >>> uses_any_fixed('banana', 'aeiou')\n",
    "    True\n",
    "    >>> uses_any_fixed('apple', 'xyz')\n",
    "    False\n",
    "    \"\"\"\n",
    "    for letter in word.lower():\n",
    "        if letter in letters.lower():\n",
    "            return True\n",
    "    return False  # moved outside the loop: this was the bug in uses_any_incorrect\n",
    "\n",
    "run_doctests(uses_any_fixed)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "125c5630",
   "metadata": {
    "tags": []
   },
   "source": [
    "## More Testing Techniques\n",
    "\n",
    "The sections below cover techniques you'll reach for on real projects: isolating code from external dependencies, running the same test logic across many inputs, and measuring how much of your code your tests actually exercise."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f298b95f",
   "metadata": {},
   "source": [
    "### Mocking Dependencies\n",
    "\n",
    "Tests should run without network calls, database access, or file I/O. **Mocking** replaces a real object with a controlled stand-in so tests are fast, isolated, and deterministic.\n",
    "\n",
    "`unittest.mock.patch` is the standard tool. It temporarily replaces the target for the duration of the `with` block and restores the original afterward.\n",
    "\n",
    "The example below patches a simple function (`get_price`) so the test never makes a real network call:\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-f298b95f",
   "metadata": {},
   "source": [
    "```{index} mocking, unittest.mock module, pytest fixture\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "b280c032",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "apply_discount('widget') = 90.0  ✓\n",
      "get_price was called with: call('widget')\n",
      "\n",
      "get_price is restored; calling it now would raise RuntimeError\n"
     ]
    }
   ],
   "source": [
    "from unittest.mock import patch\n",
    "\n",
    "# Imagine this lives in a pricing module and makes a real network call.\n",
    "def get_price(item):\n",
    "    \"\"\"Fetch item price from an external service.\"\"\"\n",
    "    raise RuntimeError(\"This would make a real network call\")\n",
    "\n",
    "def apply_discount(item, discount=0.10):\n",
    "    \"\"\"Return the discounted price for an item.\"\"\"\n",
    "    price = get_price(item)\n",
    "    return round(price * (1 - discount), 2)\n",
    "\n",
    "# Patch get_price so apply_discount never touches the network.\n",
    "with patch(\"__main__.get_price\", return_value=100.0) as mock_get:\n",
    "    result = apply_discount(\"widget\")\n",
    "    assert result == 90.0\n",
    "    print(f\"apply_discount('widget') = {result}  ✓\")\n",
    "    print(f\"get_price was called with: {mock_get.call_args}\")\n",
    "\n",
    "# Outside the 'with' block, get_price is restored to the original.\n",
    "print(\"\\nget_price is restored; calling it now would raise RuntimeError\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "s2b-mock-calls-md",
   "metadata": {},
   "source": [
    "The mock that `patch` hands you (`mock_get` above) also records every call made to it, so a test can check *how* the code used its dependency. `mock_get.assert_called_once_with(...)` passes if the mock was called exactly once with exactly those arguments, and raises `AssertionError` otherwise:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "s2b-idx-mock-calls",
   "metadata": {},
   "source": [
    "```{index} assert_called_once_with()\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "s2b-mock-calls-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": [
      "get_price was called once with 'widget'\n",
      "AssertionError: expected call not found.\n",
      "Expected: get_price('gadget')\n",
      "  Actual: get_price('widget')\n"
     ]
    }
   ],
   "source": [
    "with patch(\"__main__.get_price\", return_value=100.0) as mock_get:\n",
    "    apply_discount(\"widget\")\n",
    "    mock_get.assert_called_once_with(\"widget\")   # passes: one call, argument \"widget\"\n",
    "    print(\"get_price was called once with 'widget'\")\n",
    "\n",
    "    try:\n",
    "        mock_get.assert_called_once_with(\"gadget\")   # wrong argument\n",
    "    except AssertionError as e:\n",
    "        print(\"AssertionError:\", e)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "monkeypatch-md",
   "metadata": {},
   "source": [
    "`pytest` has its own tool for this, the `monkeypatch` **fixture**. A fixture is an object that `pytest` passes to a test function automatically when the function names it as a parameter. `monkeypatch.setattr` replaces a function for one test, and `pytest` restores the original when the test ends:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "monkeypatch-code",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m.\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32m                                                                                            [100%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\u001b[32m\u001b[32m\u001b[1m1 passed\u001b[0m\u001b[32m in 0.00s\u001b[0m\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "%%ipytest\n",
    "\n",
    "def fake_get_price(item):\n",
    "    return 100.0\n",
    "\n",
    "def test_apply_discount(monkeypatch):\n",
    "    monkeypatch.setattr(\"__main__.get_price\", fake_get_price)\n",
    "    assert apply_discount(\"widget\") == 90.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "patch-where-md",
   "metadata": {},
   "source": [
    ":::{note}\n",
    "**Patch the name where it is looked up**\n",
    "\n",
    "In this notebook everything lives in one module, `__main__`, so the target is `__main__.get_price`. In a project, patch the name in the module that *uses* it, which is not always the module that defines it. Suppose `get_price` is defined in `pricing.py`:\n",
    "\n",
    "- If `shop.py` does `from pricing import get_price`, then `shop` has its own reference to the function. Patch `shop.get_price`; patching `pricing.get_price` would leave `shop` calling the original.\n",
    "- If `shop.py` does `import pricing` and calls `pricing.get_price(...)`, the name is looked up on `pricing` at call time, so `pricing.get_price` is the right target.\n",
    "\n",
    "The same rule applies to `unittest.mock.patch` and `monkeypatch.setattr`.\n",
    ":::"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-inject-md",
   "metadata": {},
   "source": [
    "Patching is not the only way to use a fake. If you can change the function's design, pass the dependency in as an argument instead. The function then works with whatever lookup it is given: the real one in production, and a **fake** (a simple stand-in that returns canned data) in a test. This design is called **dependency injection**. Nothing is replaced, so there is nothing to restore after the test."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-ch05-inject",
   "metadata": {},
   "source": [
    "```{index} dependency injection, fake object\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ch05-inject-code",
   "metadata": {},
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "90.0\n"
    }
   ],
   "source": [
    "def apply_discount_with(item, get_price):\n",
    "    \"\"\"Apply a 10% discount to the price that get_price returns.\"\"\"\n",
    "    return get_price(item) * 0.9\n",
    "\n",
    "def fake_get_price(item):\n",
    "    return 100.0\n",
    "\n",
    "assert apply_discount_with(\"widget\", fake_get_price) == 90.0\n",
    "print(apply_discount_with(\"widget\", fake_get_price))   # 90.0"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ch05-inject-compare",
   "metadata": {},
   "source": [
    "Use `patch` (or `monkeypatch`) when you cannot change how the code gets its dependency, for example when it calls a library function directly. Use an injected fake when the function takes the dependency as a parameter: the test simply passes the fake in."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f982e982",
   "metadata": {},
   "source": [
    "\n",
    ":::{admonition} Advanced: mocking context managers\n",
    ":class: dropdown\n",
    "\n",
    "When the code under test uses a `with` statement (e.g., `with urllib.request.urlopen(url) as resp:`), the mock must also support the context-manager protocol (`__enter__` / `__exit__`). `MagicMock` does this automatically:\n",
    "\n",
    "```python\n",
    "from unittest.mock import patch, MagicMock\n",
    "import json\n",
    "\n",
    "def fetch_json(url):\n",
    "    import urllib.request\n",
    "    with urllib.request.urlopen(url) as resp:\n",
    "        return json.loads(resp.read())\n",
    "\n",
    "with patch(\"urllib.request.urlopen\") as mock_open:\n",
    "    mock_resp = MagicMock()\n",
    "    mock_resp.__enter__.return_value = mock_resp\n",
    "    mock_resp.__exit__.return_value = False\n",
    "    mock_resp.read.return_value = b'{\"status\": \"ok\"}'\n",
    "    mock_open.return_value = mock_resp\n",
    "\n",
    "    data = fetch_json(\"https://example.com/api\")\n",
    "    assert data == {\"status\": \"ok\"}\n",
    "```\n",
    "\n",
    "The key lines are `mock_resp.__enter__.return_value = mock_resp` (so `as resp` binds to the mock) and `mock_resp.__exit__.return_value = False` (so exceptions are not suppressed).\n",
    ":::\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "ea393949",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [],
   "source": [
    "### Exercise: Mock a database lookup\n",
    "#   get_user(user_id) is supposed to look up a user in a database.\n",
    "#   format_greeting(user_id) calls get_user() and returns 'Hello, {name}!'\n",
    "#   Using patch, mock get_user so format_greeting never touches a real database:\n",
    "#     - patch get_user to return {'name': 'Alice'}\n",
    "#     - assert format_greeting(1) == 'Hello, Alice!'\n",
    "#     - assert get_user was called exactly once with argument 1\n",
    "#       (hint: mock_get.assert_called_once_with(1))\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "3f50e388",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "format_greeting(1) = 'Hello, Alice!'  ✓\n",
      "get_user called with: call(1)\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "from unittest.mock import patch\n",
    "\n",
    "def get_user(user_id):\n",
    "    raise RuntimeError('This would query a real database')\n",
    "\n",
    "def format_greeting(user_id):\n",
    "    user = get_user(user_id)\n",
    "    return f\"Hello, {user['name']}!\"\n",
    "\n",
    "with patch('__main__.get_user', return_value={'name': 'Alice'}) as mock_get:\n",
    "    result = format_greeting(1)\n",
    "    assert result == 'Hello, Alice!', f'Got: {result}'\n",
    "    mock_get.assert_called_once_with(1)\n",
    "    print(f'format_greeting(1) = {result!r}  ✓')\n",
    "    print(f'get_user called with: {mock_get.call_args}')"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b8e15ce",
   "metadata": {},
   "source": [
    "### Parametrized Tests\n",
    "\n",
    "Writing one test function per input case leads to repetitive code. `@pytest.mark.parametrize` runs the same test function once for each row of inputs. The `@` line written directly above `def` is a **decorator**: here it attaches the list of parameter rows to the test function, so `pytest` knows to run that function once per row. You will learn how decorators work in {doc}`10.1 Functional Programming <../10-functional/1001-func-prog>`; for now, treat the line as a label you put on a test. Each row becomes a separate test case in the report, and a failing row shows the exact inputs that failed.\n",
    "\n",
    "In the cell below, the `-vv` option tells `ipytest` to list every test by name, and `--no-header` hides machine-specific details."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "idx-4b8e15ce",
   "metadata": {},
   "source": [
    "```{index} parametrized test, pytest.mark.parametrize\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "id": "f34638f0",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m======================================= test session starts ========================================\u001b[0m\n",
      "\u001b[1mcollecting ... \u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "collected 5 items\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_palindrome[racecar-True] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m               [ 20%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_palindrome[madam-True] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                 [ 40%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_palindrome[hello-False] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                [ 60%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_palindrome[-True] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                      [ 80%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_palindrome[a-True] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                     [100%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[32m======================================== \u001b[32m\u001b[1m5 passed\u001b[0m\u001b[32m in 0.02s\u001b[0m\u001b[32m =========================================\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "%%ipytest -vv --no-header\n",
    "\n",
    "import pytest\n",
    "\n",
    "def is_palindrome(s):\n",
    "    return s == s[::-1]\n",
    "\n",
    "@pytest.mark.parametrize(\"s, expected\", [\n",
    "    (\"racecar\", True),\n",
    "    (\"madam\",   True),\n",
    "    (\"hello\",   False),\n",
    "    (\"\",        True),\n",
    "    (\"a\",       True),\n",
    "])\n",
    "def test_is_palindrome(s, expected):\n",
    "    assert is_palindrome(s) == expected"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "parametrize-after-md",
   "metadata": {},
   "source": [
    "Each row of the table ran as its own test, named after its inputs, such as `test_is_palindrome[racecar-True]`. The long `t_...py` name is a temporary file that `ipytest` creates for the cell."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "a7767543",
   "metadata": {
    "tags": [
     "thebe-interactive"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m======================================= test session starts ========================================\u001b[0m\n",
      "\u001b[1mcollecting ... \u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "collected 0 items\n",
      "\n",
      "\u001b[33m====================================== \u001b[33mno tests ran\u001b[0m\u001b[33m in 0.00s\u001b[0m\u001b[33m =======================================\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "### Exercise: Parametrize tests for is_leap_year(year)\n",
    "#   A year is a leap year if it is divisible by 4,\n",
    "#   EXCEPT century years (divisible by 100) are not,\n",
    "#   UNLESS they are also divisible by 400.\n",
    "#   Write a parametrized test `test_is_leap_year(year, expected)` with at least\n",
    "#   5 (year, expected) rows:\n",
    "#     - divisible by 400 (e.g., 2000) → True\n",
    "#     - divisible by 100 but not 400 (e.g., 1900) → False\n",
    "#     - divisible by 4, not 100 (e.g., 2024) → True\n",
    "#     - not divisible by 4 (e.g., 2023) → False\n",
    "#     - one more case of your choice\n",
    "#   This cell can't start with %%ipytest, so it calls ipytest directly:\n",
    "#   ipytest.clean() removes tests left over from earlier cells, and\n",
    "#   ipytest.run() runs the tests defined in this cell.\n",
    "import ipytest\n",
    "import pytest\n",
    "\n",
    "def is_leap_year(year):\n",
    "    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n",
    "\n",
    "ipytest.clean()\n",
    "### Your code starts here.\n",
    "\n",
    "\n",
    "\n",
    "### Your code ends here.\n",
    "\n",
    "exit_code = ipytest.run(\"-vv\", \"--no-header\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "id": "3e257272",
   "metadata": {
    "tags": [
     "hide-input"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m======================================= test session starts ========================================\u001b[0m\n",
      "\u001b[1mcollecting ... \u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "collected 5 items\n",
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_leap_year[2000-True] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                   [ 20%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_leap_year[1900-False] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                  [ 40%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_leap_year[2024-True] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                   [ 60%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_leap_year[2023-False] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                  [ 80%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "t_244b61e4d80d4bbeae1a987667df8015.py::test_is_leap_year[1600-True] "
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[32mPASSED\u001b[0m\u001b[32m                   [100%]\u001b[0m"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "\u001b[32m======================================== \u001b[32m\u001b[1m5 passed\u001b[0m\u001b[32m in 0.02s\u001b[0m\u001b[32m =========================================\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "### Solution\n",
    "import ipytest\n",
    "import pytest\n",
    "\n",
    "def is_leap_year(year):\n",
    "    return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)\n",
    "\n",
    "ipytest.clean()\n",
    "\n",
    "@pytest.mark.parametrize(\"year, expected\", [\n",
    "    (2000, True),   # divisible by 400: leap\n",
    "    (1900, False),  # divisible by 100 but not 400: not leap\n",
    "    (2024, True),   # divisible by 4, not 100: leap\n",
    "    (2023, False),  # not divisible by 4: not leap\n",
    "    (1600, True),   # divisible by 400: leap\n",
    "])\n",
    "def test_is_leap_year(year, expected):\n",
    "    assert is_leap_year(year) == expected\n",
    "\n",
    "exit_code = ipytest.run(\"-vv\", \"--no-header\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1cf2407",
   "metadata": {},
   "source": [
    "### Test Coverage Basics\n",
    "\n",
    "```{index} test coverage, pytest-cov\n",
    "```\n",
    "\n",
    "**Test coverage** measures what fraction of your source code is exercised by your test suite. A line is \"covered\" if at least one test causes it to run.\n",
    "\n",
    "The standard tool is `coverage.py`. With `pytest`, you usually run it through `pytest-cov`, the `pytest` plugin for coverage.py:\n",
    "\n",
    "```bash\n",
    "# Install (once)\n",
    "pip install pytest-cov\n",
    "\n",
    "# Run tests with a coverage report that lists the missed lines\n",
    "pytest --cov=my_module --cov-report=term-missing\n",
    "\n",
    "# Also measure branch coverage: was each side of every if/else taken?\n",
    "pytest --cov=my_module --cov-branch --cov-report=term-missing\n",
    "```\n",
    "\n",
    "| Coverage % | Interpretation |\n",
    "|---|---|\n",
    "| < 50% | Probably missing whole branches or functions |\n",
    "| 50–80% | Reasonable for scripts; low for libraries |\n",
    "| 80–90% | Good target for most production code |\n",
    "| > 90% | High confidence; watch for diminishing returns |\n",
    "\n",
    "**Key insight**: 100% coverage does not mean your code is correct. It means every line ran, not that every case was tested correctly. Focus on covering *branches* (if/else, try/except), not just lines; `--cov-branch` reports the branches your tests never took.\n",
    "\n",
    "```bash\n",
    "# Generate an HTML report to see exactly which lines are missed\n",
    "pytest --cov=my_module --cov-report=html\n",
    "open htmlcov/index.html   # macOS; use 'start' on Windows or 'xdg-open' on Linux\n",
    "# Or just open htmlcov/index.html directly in your browser.\n",
    "```"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv (3.13.7)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
