The Problem
Every lab in this course -- all 55 of them -- depends on a working testing toolchain. If you have to stop mid-lab to install a missing dependency or debug a configuration issue, you lose context and momentum. This lesson sets up the entire toolchain once, verifies it with a smoke test, and creates the project scaffold that every subsequent lab builds on.
The toolchain has six components, each corresponding to a layer of the verification pyramid:
| Tool | Pyramid Layer | What it does |
|---|
| pytest | Unit | Runs unit tests |
| Hypothesis | Property-Based | Generates thousands of test inputs automatically |
| mutmut | Mutation | Mutates code to validate test quality |
| Semgrep | Security | Static analysis for CWE patterns |
| Ruff | Static Analysis | Fast Python linter |
| mypy | Static Analysis | Type checking |
Plus pre-commit hooks to run them automatically on every commit.
Installation
Create a project directory and install all tools:
mkdir ai-code-testing && cd ai-code-testing
python -m venv .venv
source .venv/bin/activate
pip install pytest hypothesis mutmut semgrep ruff mypy pre-commit
Verify each tool is installed:
pytest --version
python -c "import hypothesis; print(hypothesis.__version__)"
mutmut --version
semgrep --version
ruff --version
mypy --version
Project scaffold
Create the following directory structure -- every lab in this course follows this pattern:
ai-code-testing/
.venv/
.pre-commit-config.yaml
pyproject.toml
conftest.py
src/
__init__.py
tests/
__init__.py
test_smoke.py
semgrep.yml
Why a shared scaffold matters
Every lab in this course produces a code artifact (e.g., lesson_00_01_defect_patterns.py) and expects the toolchain to be available. By setting up the scaffold now, you can drop each lesson's code artifact into src/, its tests into tests/, and run the full verification pipeline without any additional setup. This is the same pattern you will use in your real AI code projects.
Configuration files
pyproject.toml -- central configuration for all tools:
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-v --tb=short"
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "B", "C4", "SIM"]
[tool.mypy]
python_version = "3.10"
warn_return_any = true
warn_unused_configs = true
[tool.mutmut]
paths_to_mutate = "src/"
tests_dir = "tests/"
.pre-commit-config.yaml -- runs all tools on every commit:
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.0
hooks:
- id: ruff
args: [--fix]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.0.0
hooks:
- id: mypy
- repo: https://github.com/returntocorp/semgrep
rev: v1.0.0
hooks:
- id: semgrep
args: [--config, semgrep.yml]
semgrep.yml -- custom rules for AI code defect patterns:
rules:
- id: ai-missing-exception-handling
pattern: json.loads($X)
message: "json.loads() can raise JSONDecodeError. Wrap in try/except."
severity: WARNING
languages: [python]
- id: ai-subscript-without-get
pattern: $DICT[$KEY]
message: "Direct subscript access can raise KeyError. Use .get() instead."
severity: INFO
languages: [python]
conftest.py -- shared pytest fixtures:
import pytest
@pytest.fixture
def sample_ai_code():
return '''
def process_users(data):
result = []
for user in data:
email = user["email"].lower()
result.append({"name": user["name"], "email": email})
return result
'''
Smoke test
Create tests/test_smoke.py to verify the entire toolchain works:
"""Smoke test: verifies the entire testing toolchain is working."""
import pytest
from hypothesis import given, strategies as st
def test_pytest_works():
assert 1 + 1 == 2
@given(st.integers(), st.integers())
def test_hypothesis_works(a, b):
assert (a + b) == (b + a)
def test_mutmut_can_find_src():
import importlib
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src"))
def test_semgrep_config_exists():
import os
base = os.path.dirname(os.path.dirname(__file__))
assert os.path.exists(os.path.join(base, "semgrep.yml"))
def test_ruff_config_exists():
import os
base = os.path.dirname(os.path.dirname(__file__))
assert os.path.exists(os.path.join(base, "pyproject.toml"))
Run the smoke test:
pytest tests/test_smoke.py -v
If all 5 tests pass, your toolchain is ready. If any fail, check the installation steps above.
You run pytest tests/test_smoke.py -v and the Hypothesis test fails with ImportError: No module named 'hypothesis'. What is the most likely cause and fix?
The most common cause is that the virtual environment is not activated (so the system Python is being used instead of the project's venv) or Hypothesis was not installed in the venv. The fix is to activate the venv with source .venv/bin/activate and install Hypothesis with pip install hypothesis. This is why the smoke test exists -- to catch missing dependencies before you start a lab and lose context mid-way through.
After setting up the toolchain, you want to verify that mutmut is correctly configured. What command do you run, and what output confirms it is working?
mutmut run is the command that verifies the full configuration. It reads paths_to_mutate from pyproject.toml, generates mutants by modifying the source code, runs the test suite against each mutant, and reports the mutation score. If it reports 0 mutants, the paths_to_mutate path is empty or incorrect. If it reports mutants but all survive, the test suite is weak (which is expected at this stage -- the smoke test only has 5 tests). The key is that mutmut runs without errors and produces a report, confirming the toolchain integration is working.