Capstone 1 — Python CLI report tool
The sales operations team meets every Monday to decide where the next promotion budget goes. Before each meeting, an analyst opens a notebook, changes three cells, runs it and copies numbers into the team wiki. The numbers change when someone forgets a cell, and nobody else can produce the report when the analyst is away.
The team lead asks you for a command-line tool: a program that anyone on the team, or a scheduler, runs with one command and gets the same answer. The tool reads the sales files and ranks revenue by a column (category, product, region, channel or store) and by a period (all, year, quarter or month). It prints the report for a person, or writes it as CSV for spreadsheets, JSON for the dashboard service and Markdown for the wiki. It must never print a wrong number quietly: bad input stops the tool with a clear message and an exit code that a scheduler can check.
In module 08 you built salesreport 0.1: one report, plain functions and dicts. This capstone is version 1.0, a tool that a team can trust and extend.
Deliverables:
- A package
salesreport/with three subcommands:summary,reportandformats. It runs withpython -m salesreportand installs asalesreportcommand. - A
pyproject.tomlthat makes the folder an installable project. - A pytest suite of at least 40 tests that runs in under one second, plus a clean
ruff check. - Three report files made from the real data in an
output/folder: one CSV, one JSON and one Markdown file.
Skills practiced:
| Skill | Where you learned it |
|---|---|
| Small functions with one job, docstrings | Module 05 — Functions |
| Custom exceptions, logging, exit codes | Module 06 — Errors and debugging |
csv, json, pathlib, reading by column name |
Module 07 — Files and data formats |
Packages, __main__.py, argparse, pyproject.toml |
Module 08 — Modules, packages and environments |
collections, datetime, decimal, tempfile |
Module 09 — Standard library power tools |
| A context manager for safe writes, a class decorator | Module 11 — Decorators and context managers |
Type hints, generics, mypy --strict |
Module 12 — Type hints |
Test first, fixtures, tmp_path, parametrize, capsys, caplog, monkeypatch |
Module 14 — Testing with pytest |
| Classes, an abstract base class, polymorphism | Module 18 and Module 19 |
__len__ and __iter__ on a result object |
Module 20 — The Python data model |
Frozen dataclasses, StrEnum, IntEnum |
Module 21 — Dataclasses, enums and slots |
| Strategy, template method, factory and registry patterns | Module 22 — Design principles and patterns |
The tool uses only the standard library. It has no dependencies to install.
Dataset
Section titled “Dataset”The tool reads any CSV file with the course’s sales columns. You test it on three inputs. The data dictionary describes each file.
| Input | Rows | Role in this capstone |
|---|---|---|
data/sales.csv |
20,228 lines | the main input; its headline numbers are your oracle |
data/reports/ |
6 files, 297 lines | a folder input: monthly extracts with fewer columns |
data/sales_raw.csv |
1,200 lines | bad input: the tool must refuse it |
An oracle is an independent source of the right answer. The data dictionary gives these numbers for data/sales.csv: total revenue 3,596,523.83, 2023 revenue 1,645,589.59, 2024 revenue 1,950,934.24, 14,877 orders, 29,533 units, Electronics revenue 1,808,108 and East revenue 993,684. Your reports must match them.
Columns used. Required: order_id, order_date, category, product, quantity and revenue. Optional, needed only to group by them: region, channel and store_id.
Known quirks:
order_idis not unique: one order has 1–3 lines. Count orders as distinct ids, not as lines.revenuehas two decimals. Floats add cents with tiny errors, so the dictionary compares with a tolerance of 0.01.decimal.Decimaladds cents exactly, so your totals can equal the oracle exactly.- The files in
data/reports/have onlyorder_id, order_date, store_id, product, category, quantity, revenue. They have noregionorchannel, so a report by region must fail with a clear message.2024-04.csvhas the same columns in a different order, so read by column name. data/sales_raw.csvhas dates in three formats and 10 bad quantities, among other problems. The tool does not clean data (that is module 26): it counts the invalid rows and stops when there are too many.- Store
S12opened on 2023-06-15, so a store ranking for 2023 is not a fair comparison of stores. - The course files are plain UTF-8. Your team’s files may come from Excel, whose “CSV UTF-8” export starts with a byte-order mark (BOM): 3 hidden bytes before the first column name. The tool must read both kinds.
Milestones
Section titled “Milestones”Build the milestones in order. Each one adds modules to the package and the tests that prove them. Work test first (module 14): write a test for the next rule, run it and watch it fail (red), write the code that makes it pass (green), then clean up (refactor).
- Package skeleton. Goal: a folder that Python runs as a program and pip installs as a project.
- Suggested steps: create
pyproject.toml; createsalesreport/__init__.pywith only a docstring and__version__; create a firstcli.pywith only--version; add__main__.py; runpython -m salesreport --version. - Acceptance:
python -m salesreport --versionprintssalesreport 1.0.0.pyproject.tomldeclares the name, the version,requires-python = ">=3.12", no dependencies and asalesreportentry point.pip install -e .works. - Review: module 08.
- Suggested steps: create
- Records and loading. Goal: read one file, many files or a folder into typed, frozen records, and reject bad input with a precise error.
- Suggested steps: write the exception classes and the
Saledataclass; writeparse_row()and test it on good and bad values; addread_file()with the column check; addfind_csv_files()for folders; add themax_badrule inload_sales(). - Acceptance:
data/sales.csvloads 20,228 lines with a revenue of exactly 3,596,523.83.data/reports/loads 297 lines from 6 files with a revenue of 57,266.39. A file that is reached twice is read once. Each problem gives its own clear message and a documented exception class:InputErrorfor a missing file, an empty folder or a non-UTF-8 file;SchemaErrorfor a missing column;DataErrorfor an empty file, no valid rows or too many invalid rows.data/sales_raw.csvis refused, with the number of invalid rows in the message. - Review: module 06, module 07, module 09, module 21.
- Suggested steps: write the exception classes and the
- Report engine. Goal: group the lines by period and column, rank each period’s groups and keep the top N.
- Suggested steps: write
GroupByandPeriodwithPeriod.label(); write the frozenReportConfig; writebuild_report()for one period, then add periods, ranks, top N and the year filter; writesummarize()for the headline numbers. - Acceptance: the settings are a frozen dataclass that rejects
top=0. The ranking is stable: equal revenues are ordered by name. Shares add up to 100% in each period. The category and year totals match the oracle. - Review: module 05, module 09, module 20, module 21.
- Suggested steps: write
- Report writers. Goal: one class per output format, chosen by name, so a new format needs one new class and no other change.
- Suggested steps: write the abstract
ReportWriterwithrender(); write the CSV writer and its test; add the registry,@registerandget_writer(); add JSON and Markdown; addwrite()with the atomic write and the overwrite check. - Acceptance: an abstract base class defines
render()andwrite(). A registry holdscsv,jsonandmarkdown. A writer never overwrites a file unless asked. A failed write keeps the old file and leaves no temporary file. - Review: module 11, module 19, module 22.
- Suggested steps: write the abstract
- Command-line interface. Goal: subcommands with checked options, logging on request and a documented exit code for every outcome.
- Suggested steps: write
build_parser()with the three subcommands; add the argparse typespositive_int()andfraction(); addconfigure_logging()and-v; writemain(), which turns eachSalesReportErrorinto a message and an exit code; handle a closed pipe. - Acceptance:
--helpworks on the tool and on each subcommand.-vshows progress and-vvlists every skipped row, on stderr, before or after the command name. The exit code is 0 for success, 1 for unusable input, 2 for a bad option, 3 for an output problem and 141 when the reader of a pipe stops early. A data or output error prints one line that starts withsalesreport: error:, without a traceback. A bad option prints argparse’s usage text and a linesalesreport <command>: error: .... - Review: module 06, module 08.
- Suggested steps: write
- Tests and quality checks. Goal: a suite that proves each rule, so the team can change the code without fear.
- Suggested steps: run the whole suite; list each error path of the code and find its test; add the missing ones; run
ruff checkandmypy --strict. - Acceptance: at least 40 tests in
tests/, all passing in under one second. Fixtures inconftest.pywrite small files totmp_path. Every error path has a test.ruff checkpasses. (Excellent:mypy --strictpasses too.) - Review: module 12, module 14.
- Suggested steps: run the whole suite; list each error path of the code and find its test; add the missing ones; run
Grading rubric
Section titled “Grading rubric”Each criterion has three levels. The points of a level are in brackets.
| Criterion | Needs work (0) | Meets | Excellent | Max |
|---|---|---|---|---|
| Packaging | does not run as python -m salesreport |
runs with -m; valid pyproject.toml (1) |
also installs a working salesreport command with --version (2) |
2 |
| Loading and validation | reads by position, or crashes on bad rows | reads by name; typed records; invalid rows are counted (2) | one documented exception class per problem; folder input; exact Decimal totals (4) |
4 |
| Report correctness | totals differ from the oracle | totals match; top N works (2) | stable tie order; shares per period; year filter; clear error for a missing column (4) | 4 |
| Writer design | one function with an if per format |
one class per format (2) | abstract base class, registry and factory; atomic, no-overwrite writes (3) | 3 |
| Command-line behavior | tracebacks for user mistakes | subcommands, --help, checked options (2) |
clear errors and documented exit codes for every outcome, all tested (4) | 4 |
| Logging | print() for progress, or no feedback |
logging on stderr (1) |
-v and -vv levels, both tested; the data on stdout stays clean (2) |
2 |
| Test suite | fewer than 40 tests, or tests that read data/ |
40 or more tests with fixtures and tmp_path (3) |
also parametrized rules, capsys and caplog checks, a test for every error path, under one second (5) |
5 |
| Code quality | lint errors, no type hints | ruff check passes; type hints on public functions (1) |
mypy --strict passes; docstrings on every module (2) |
2 |
| Total | 0 | 14 | 26 | 26 |
You meet the brief with 14 points or more: “Meets” on every criterion, or more points on some criteria to make up for others. 22 points or more is an excellent project.
Reference solution
Section titled “Reference solution”The solution is a real project with 16 files. It grows milestone by milestone, in this build order:
| Milestone | New files | Tests |
|---|---|---|
| 1 | pyproject.toml, __init__.py, __main__.py |
none yet |
| 2 | errors.py, models.py, loader.py |
samples.py, conftest.py, test_loader.py |
| 3 | config.py, report.py |
test_report.py |
| 4 | writers.py |
test_writers.py |
| 5 | cli.py |
test_cli.py |
| 6 | none | the whole suite, ruff, mypy |
Each file is shown in its final form, with a short “build it in this order” list where the file is long. The page then runs the code: Python blocks import the package, and terminal blocks run the command and the tests from the project folder.
Reference solution — Milestone 1: Package skeleton
The project uses the flat layout of module 08: the package folder sits at the project root, next to data/, so python -m salesreport works without an install step. This is the finished project; milestone 1 creates only the first three files.
my-course/├── data/ # the course data├── pyproject.toml # milestone 1├── salesreport/│ ├── __init__.py # milestone 1: version and public names│ ├── __main__.py # milestone 1: runs on "python -m salesreport"│ ├── errors.py # milestone 2: exceptions and exit codes│ ├── models.py # milestone 2: Sale and SalesData records│ ├── loader.py # milestone 2: read and validate CSV files│ ├── config.py # milestone 3: ReportConfig, GroupBy, Period│ ├── report.py # milestone 3: build_report() and summarize()│ ├── writers.py # milestone 4: csv, json, markdown│ └── cli.py # milestone 5: argparse, logging, exit codes└── tests/ ├── samples.py # milestone 2: five sample lines with known totals ├── conftest.py # milestone 2: fixtures ├── test_loader.py # milestone 2 ├── test_report.py # milestone 3 ├── test_writers.py # milestone 4 └── test_cli.py # milestone 5[project]name = "salesreport"version = "1.0.0"description = "Turn sales CSV files into ranked revenue reports."requires-python = ">=3.12"license = "MIT"authors = [{ name = "Ada Lovelace", email = "ada@example.com" }]keywords = ["sales", "report", "csv", "cli"]dependencies = []
[project.scripts]salesreport = "salesreport.cli:main"
[dependency-groups]dev = ["pytest>=9.2", "ruff>=0.17", "mypy>=2.4"]
[build-system]requires = ["hatchling>=1.27"]build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]packages = ["salesreport"]
[tool.pytest]testpaths = ["tests"]pythonpath = [".", "tests"] # import samples in any import modestrict = true
[tool.ruff]line-length = 88target-version = "py312"src = [".", "tests"] # tests/samples.py is our own module
[tool.ruff.lint]select = ["E", "F", "W", "I", "B", "UP"][project.scripts]creates thesalesreportcommand at install time. It callsmain()insalesreport/cli.py.[dependency-groups]lists the tools that only developers need: pytest, ruff and mypy.[tool.hatch.build.targets.wheel]names the package folder, so the build never packstests/ordata/.[tool.pytest]tells pytest where the tests are.pythonpathputs the project root andtests/on the import path, so the tests can importsalesreportandsampleswithout an install.strict = trueturns unknown markers and config typos into errors.[tool.ruff]pins the lint rules in the project, soruff checkgives the same result on every machine.srctells the import sorter thattests/samples.pyis first-party code.
"""salesreport: turn sales CSV files into ranked revenue reports.
Run it with: python -m salesreport --help"""
from .config import GroupBy, Period, ReportConfigfrom .errors import ExitCode, SalesReportErrorfrom .loader import load_salesfrom .report import Report, ReportRow, build_reportfrom .writers import get_writer, writer_names
__version__ = "1.0.0"__all__ = [ "ExitCode", "GroupBy", "Period", "Report", "ReportConfig", "ReportRow", "SalesReportError", "build_report", "get_writer", "load_sales", "writer_names",]In milestone 1, __init__.py holds only the docstring and __version__. Add each import when its module exists.
"""Run the package as a program: python -m salesreport ..."""
from .cli import main
raise SystemExit(main())raise SystemExit(main()) turns the return value of main() into the exit code of the process. In milestone 1, cli.py is a stub: a parser with only the --version option. Milestone 5 replaces it. The version lives in __init__.py, and cli.py reads it from there, so --version and the package always agree. (The version in pyproject.toml is the one the installer records; a stretch goal removes the copy.)
python -m salesreport --versionsalesreport 1.0.0An editable install (-e) links the project folder into the environment instead of copying it, so your code changes apply at once. Run it once in your activated virtual environment:
python -m pip install -e . # or: uv pip install -e .salesreport --version # the entry point now works from any folderReference solution — Milestone 2: Records and loading
salesreport/errors.py defines one exception class per kind of problem. Each class carries its exit code, so main() needs no if chain to choose one. The milestone 5 codes are here too, so all exit codes live in one place.
"""Expected problems, each with the exit code that the command returns."""
from enum import IntEnum
class ExitCode(IntEnum): """Exit codes of the salesreport command."""
OK = 0 DATA_ERROR = 1 # the input cannot give a trustworthy report USAGE_ERROR = 2 # bad command-line arguments (argparse exits with 2) OUTPUT_ERROR = 3 # the report cannot be written PIPE_CLOSED = 141 # the reader of stdout stopped early: 128 + SIGPIPE (13)
class SalesReportError(Exception): """Base class: a problem the user can fix, with a one-line message."""
exit_code = ExitCode.DATA_ERROR
class InputError(SalesReportError): """An input path is missing, is not UTF-8 text or holds no CSV files."""
class SchemaError(SalesReportError): """The input lacks a column that the report needs."""
class DataError(SalesReportError): """The input is empty, has no valid rows or has too many invalid rows."""
class OutputError(SalesReportError): """The report file cannot be written."""
exit_code = ExitCode.OUTPUT_ERRORsalesreport/models.py holds the records. frozen=True makes them read-only, so no step can change a sale by accident. slots=True saves memory on 20,000 objects.
"""Record types: one sales line, and the lines loaded from a set of files."""
from dataclasses import dataclassfrom datetime import datefrom decimal import Decimalfrom pathlib import Path
@dataclass(frozen=True, slots=True)class Sale: """One order line. An optional column is None when its file lacks it."""
order_id: str order_date: date category: str product: str quantity: int revenue: Decimal region: str | None = None channel: str | None = None store_id: str | None = None
@dataclass(frozen=True, slots=True)class SalesData: """The valid lines of one or more files, and how many lines were skipped."""
sales: tuple[Sale, ...] columns: frozenset[str] # the columns that every file has sources: tuple[Path, ...] skipped: int = 0
def __len__(self) -> int: return len(self.sales)
@property def revenue(self) -> Decimal: return sum((sale.revenue for sale in self.sales), Decimal(0))salesreport/loader.py reads by column name with csv.DictReader, so the column order does not matter. Build it in this order, with a test before each step:
text()andparse_row(): one row in, oneSaleor aValueErrorout.read_file(): open the file, check the columns, count the bad rows and log each one at DEBUG level with its file and line number.find_csv_files(): expand folders and skip a file that is reached twice.load_sales(): combine the files and apply themax_badrule. A few bad rows are skipped with a warning; too many, or no valid row at all, stop the run.
"""Read sales CSV files by column name and validate every row."""
import csvimport loggingfrom collections.abc import Iterablefrom datetime import datefrom decimal import Decimal, InvalidOperationfrom pathlib import Path
from .errors import DataError, InputError, SchemaErrorfrom .models import Sale, SalesData
log = logging.getLogger(__name__)
REQUIRED = frozenset( {"order_id", "order_date", "category", "product", "quantity", "revenue"})OPTIONAL = ("region", "channel", "store_id")
def find_csv_files(paths: Iterable[Path]) -> list[Path]: """Return the files to read: a folder gives its CSV files, sorted by name.
A file that is reached twice (by a folder and by its own name) is read once. """ files: list[Path] = [] seen: set[Path] = set() for path in paths: if path.is_dir(): found = sorted(path.glob("*.csv")) if not found: raise InputError(f"no CSV files in folder: {path}") elif path.is_file(): found = [path] else: raise InputError(f"file not found: {path}") for file in found: if file.resolve() in seen: log.warning("%s is given twice; reading it once", file) continue seen.add(file.resolve()) files.append(file) return files
def text(row: dict[str, str | None], column: str) -> str: """Return a stripped, non-empty value. Raise ValueError when it is empty.""" value = (row.get(column) or "").strip() if not value: raise ValueError(f"{column} is empty") return value
def parse_row(row: dict[str, str | None]) -> Sale: """Convert one CSV row to a Sale. Raise ValueError for a bad value.""" quantity = int(text(row, "quantity")) if quantity < 1: raise ValueError(f"quantity must be at least 1, got {quantity}") raw_revenue = text(row, "revenue") try: revenue = Decimal(raw_revenue) except InvalidOperation: raise ValueError(f"revenue is not a number: {raw_revenue!r}") from None if not revenue.is_finite() or revenue < 0: raise ValueError(f"revenue must not be negative, got {raw_revenue!r}") raw_date = text(row, "order_date") try: order_date = date.fromisoformat(raw_date) except ValueError: raise ValueError(f"order_date is not YYYY-MM-DD: {raw_date!r}") from None optional = {name: (row.get(name) or "").strip() or None for name in OPTIONAL} return Sale( order_id=text(row, "order_id"), order_date=order_date, category=text(row, "category"), product=text(row, "product"), quantity=quantity, revenue=revenue, **optional, )
def read_file(path: Path) -> tuple[list[Sale], frozenset[str], int]: """Return the valid sales, the column names and the number of bad rows.""" sales: list[Sale] = [] bad = 0 try: # utf-8-sig also reads files that start with a byte-order mark (Excel). with path.open(newline="", encoding="utf-8-sig") as file: reader = csv.DictReader(file) if reader.fieldnames is None: raise DataError(f"{path}: file is empty") columns = frozenset(reader.fieldnames) missing = REQUIRED - columns if missing: names = ", ".join(sorted(missing)) raise SchemaError(f"{path}: missing columns: {names}") for row in reader: try: sales.append(parse_row(row)) except ValueError as exc: bad += 1 log.debug("%s:%d: %s", path, reader.line_num, exc) except UnicodeDecodeError: raise InputError(f"{path}: not UTF-8 text") from None log.info("read %s: %d valid rows, %d skipped", path, len(sales), bad) return sales, columns, bad
def load_sales(paths: Iterable[Path], *, max_bad: float = 0.05) -> SalesData: """Load and validate every file. Fail when more than max_bad rows are bad.""" files = find_csv_files(paths) sales: list[Sale] = [] common: frozenset[str] | None = None bad = 0 for path in files: file_sales, columns, file_bad = read_file(path) sales.extend(file_sales) bad += file_bad common = columns if common is None else common & columns total = len(sales) + bad if total == 0: raise DataError("the input has no data rows") if bad / total > max_bad: raise DataError( f"{bad:,} of {total:,} rows ({bad / total:.1%}) are invalid, " f"above the {max_bad:.1%} limit; -vv lists them" ) if not sales: # possible with --max-bad 1 raise DataError( f"the input has no valid rows ({total:,} invalid); -vv lists them" ) if bad: log.warning("skipped %d invalid rows of %d", bad, total) return SalesData(tuple(sales), common or frozenset(), tuple(files), bad)Design notes:
log = logging.getLogger(__name__)gives the logger the namesalesreport.loader. The module only creates log records. The command line decides where they go (milestone 5).encoding="utf-8-sig"reads UTF-8 with or without a byte-order mark. With plain"utf-8", the BOM sticks to the first column name, and an Excel file fails withmissing columns: order_id, although the column is visibly there.- A 0-byte file has no header, so
reader.fieldnamesisNone. The loader says “file is empty” instead of listing every column as missing. UnicodeDecodeErroris a subclass ofValueError. It is caught outside the row loop, because the reader raises it while it reads the file, not insideparse_row().find_csv_files()comparespath.resolve(), the absolute path, sodata/reportsanddata/reports/2024-01.csvcannot count January twice.columnskeeps only the columns that every file has (&is set intersection), so a report can check its grouping column once.raise ... from Nonehides the low-level exception. The new message already says what is wrong.
The tests use five sample lines with known totals. They live in tests/samples.py, a plain module: tests import data from it, and conftest.py holds only fixtures.
"""Sample sales lines with known totals, shared by the tests."""
HEADER = ( "order_id", "order_date", "store_id", "region", "channel", "product", "category", "quantity", "revenue",)# Electronics 1,350.50 (2 orders), Clothing 120.00, Books 45.00: total 1,515.50.LINES = """O1,2024-01-05,S01,North,store,Laptop,Electronics,1,900.00O1,2024-01-05,S01,North,store,Novel,Books,2,30.00O2,2024-02-10,S04,South,online,Tablet,Electronics,1,450.50O3,2024-04-01,S04,South,store,Sweater,Clothing,3,120.00O4,2023-12-30,S07,East,online,Novel,Books,1,15.00"""ROWS = tuple(tuple(line.split(",")) for line in LINES.split())"""Shared fixtures: small sales files with known totals, in a temporary folder."""
import csvimport loggingfrom collections.abc import Callable, Iterator, Sequencefrom pathlib import Path
import pytest
from salesreport.loader import load_salesfrom salesreport.models import SalesDatafrom samples import HEADER, ROWS
@pytest.fixturedef write_csv(tmp_path: Path) -> Callable[..., Path]: """Return a function that writes a CSV file into tmp_path."""
def write( name: str = "sales.csv", rows: Sequence[Sequence[str]] = ROWS, header: Sequence[str] = HEADER, ) -> Path: path = tmp_path / name path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", newline="", encoding="utf-8") as file: writer = csv.writer(file) writer.writerow(header) writer.writerows(rows) return path
return write
@pytest.fixturedef sales_csv(write_csv: Callable[..., Path]) -> Path: return write_csv()
@pytest.fixturedef sales_data(sales_csv: Path) -> SalesData: return load_sales([sales_csv])
@pytest.fixture(autouse=True)def reset_package_logger() -> Iterator[None]: """Undo the logging setup of main() after each test, so caplog sees records.""" yield logger = logging.getLogger("salesreport") logger.handlers.clear() logger.setLevel(logging.NOTSET) logger.propagate = Truewrite_csvis a factory fixture: it returns a function, so one test can write several files, reverse the columns or remove one.sales_csvandsales_databuild on it: pytest resolves the chainsales_data→sales_csv→write_csv→tmp_pathfor you.tmp_pathis a fresh temporary folder per test. The tests never readdata/, so they are fast, independent and run on any machine.reset_package_loggeris an autouse fixture: it runs for every test without being named. Milestone 5’smain()changes thesalesreportlogger; the fixture puts it back after each test.import samplesworks becausepyproject.tomlputstests/onpythonpath. Without that line, it works only in pytest’s defaultprependimport mode, not with--import-mode=importlib.
"""Loading: types, column names, folders and every kind of bad input."""
import loggingfrom collections.abc import Callablefrom datetime import datefrom decimal import Decimalfrom pathlib import Path
import pytest
from salesreport.errors import DataError, InputError, SchemaErrorfrom salesreport.loader import load_salesfrom salesreport.models import SalesDatafrom samples import HEADER, ROWS
def test_rows_become_typed_sales(sales_data: SalesData) -> None: first = sales_data.sales[0] assert len(sales_data) == 5 assert first.order_date == date(2024, 1, 5) assert first.quantity == 1 assert first.revenue == Decimal("900.00") assert sales_data.revenue == Decimal("1515.50") assert sales_data.skipped == 0
def test_columns_are_read_by_name(write_csv: Callable[..., Path]) -> None: reversed_file = write_csv( "reversed.csv", rows=[row[::-1] for row in ROWS], header=HEADER[::-1] ) normal = load_sales([write_csv()]) assert load_sales([reversed_file]).sales == normal.sales
def test_folder_gives_its_csv_files_sorted(write_csv: Callable[..., Path]) -> None: write_csv("monthly/b.csv") path = write_csv("monthly/a.csv") (path.parent / "notes.txt").write_text("not a report", encoding="utf-8") data = load_sales([path.parent]) assert [source.name for source in data.sources] == ["a.csv", "b.csv"] assert len(data) == 10
def test_missing_file_is_an_input_error(tmp_path: Path) -> None: with pytest.raises(InputError, match="file not found"): load_sales([tmp_path / "nope.csv"])
def test_empty_folder_is_an_input_error(tmp_path: Path) -> None: with pytest.raises(InputError, match="no CSV files"): load_sales([tmp_path])
def test_non_utf8_file_is_an_input_error(tmp_path: Path) -> None: path = tmp_path / "latin1.csv" path.write_bytes(",".join(HEADER).encode() + b"\nO1,2024-01-05,S01,M\xfcnchen\n") with pytest.raises(InputError, match="not UTF-8"): load_sales([path])
def test_missing_column_is_a_schema_error(write_csv: Callable[..., Path]) -> None: path = write_csv(header=HEADER[:-1], rows=[row[:-1] for row in ROWS]) with pytest.raises(SchemaError, match="missing columns: revenue"): load_sales([path])
def test_header_only_file_is_a_data_error(write_csv: Callable[..., Path]) -> None: with pytest.raises(DataError, match="no data rows"): load_sales([write_csv(rows=[])])
def test_zero_byte_file_is_a_data_error(tmp_path: Path) -> None: path = tmp_path / "empty.csv" path.touch() with pytest.raises(DataError, match="empty.csv: file is empty"): load_sales([path])
def test_no_valid_row_is_a_data_error_even_with_max_bad_1( write_csv: Callable[..., Path],) -> None: rows = [list(row) for row in ROWS] for row in rows: row[HEADER.index("order_date")] = "07/01/2023" with pytest.raises(DataError, match=r"no valid rows \(5 invalid\)"): load_sales([write_csv(rows=rows)], max_bad=1.0)
def test_file_given_twice_is_read_once( write_csv: Callable[..., Path], caplog: pytest.LogCaptureFixture) -> None: path = write_csv("monthly/a.csv") caplog.set_level(logging.WARNING, logger="salesreport") data = load_sales([path.parent, path]) assert (len(data.sources), len(data)) == (1, 5) assert "is given twice; reading it once" in caplog.text
def test_byte_order_mark_is_ignored(sales_csv: Path, tmp_path: Path) -> None: excel_file = tmp_path / "excel.csv" excel_file.write_bytes(b"\xef\xbb\xbf" + sales_csv.read_bytes()) # UTF-8 BOM assert load_sales([excel_file]).sales == load_sales([sales_csv]).sales
@pytest.mark.parametrize( ("column", "value"), [ ("quantity", "0"), ("quantity", "two"), ("revenue", "N/A"), ("revenue", "-5.00"), ("order_date", "07/01/2024"), ("product", " "), ],)def test_bad_row_is_skipped_and_logged( write_csv: Callable[..., Path], caplog: pytest.LogCaptureFixture, column: str, value: str,) -> None: rows = [list(row) for row in ROWS] rows[2][HEADER.index(column)] = value caplog.set_level(logging.WARNING, logger="salesreport") data = load_sales([write_csv(rows=rows)], max_bad=0.25) assert (len(data), data.skipped) == (4, 1) assert "skipped 1 invalid rows of 5" in caplog.text
def test_too_many_bad_rows_is_a_data_error(write_csv: Callable[..., Path]) -> None: rows = [list(row) for row in ROWS] rows[0][HEADER.index("quantity")] = "-1" with pytest.raises(DataError, match=r"1 of 5 rows \(20\.0%\) are invalid"): load_sales([write_csv(rows=rows)], max_bad=0.1)pytest -q tests/test_loader.py................... [100%]19 passed in 0.03sNow load the real main file and compare it with the oracle:
from decimal import Decimalfrom pathlib import Path
from salesreport.errors import DataErrorfrom salesreport.loader import load_sales
sales = load_sales([Path("data/sales.csv")])first = sales.sales[0]print(f"{len(sales):,} lines, revenue {sales.revenue:,.2f}, skipped {sales.skipped}")print(first.order_id, first.order_date, first.category, first.quantity, first.revenue)assert len(sales) == 20_228assert sales.revenue == Decimal("3596523.83") # exact, no tolerance needed20,228 lines, revenue 3,596,523.83, skipped 0O000001 2023-01-01 Home 1 66.49The total equals the oracle to the cent. With floats, the same sum would need a tolerance. Now load the folder of monthly extracts:
monthly = load_sales([Path("data/reports")])print([path.name for path in monthly.sources])print(f"{len(monthly)} lines, revenue {monthly.revenue:,.2f}")print("missing columns:", sorted(sales.columns - monthly.columns))assert (len(monthly), monthly.revenue) == (297, Decimal("57266.39"))['2024-01.csv', '2024-02.csv', '2024-03.csv', '2024-04.csv', '2024-05.csv', '2024-06.csv']297 lines, revenue 57,266.39missing columns: ['channel', 'customer_id', 'discount', 'product_id', 'region', 'unit_price']The six revenue sums of the data dictionary add up to 57,266.39, so 2024-04.csv, with its other column order, was read correctly. Finally, the raw file:
try: load_sales([Path("data/sales_raw.csv")])except DataError as exc: print(f"{type(exc).__name__}: {exc}")DataError: 480 of 1,200 rows (40.0%) are invalid, above the 5.0% limit; -vv lists themThe data dictionary lists 477 dates in DD/MM/YYYY or Month D, YYYY form, which are not ISO dates, and 6 negative quantities. Some rows have both problems, so 480 rows are invalid. The tool refuses to report on them. It does not guess what 07/01/2023 means. The rule for quantities is only “at least 1”, so 2 of the 4 rows with absurd quantities (500 and 1,000) are accepted. The other two (250 and 999) already fail on their dates.
Reference solution — Milestone 3: Report engine
salesreport/config.py names the fixed choices with StrEnum, so a member is also its string: GroupBy.STORE == "store_id". ReportConfig is frozen and keyword-only, and __post_init__ rejects a bad top even when the caller is not the command line.
"""Report settings: the grouping column, the period, the top N and a year."""
from dataclasses import dataclassfrom datetime import datefrom enum import StrEnum
class GroupBy(StrEnum): """The columns a report can group by. The value is the CSV column name."""
CATEGORY = "category" PRODUCT = "product" REGION = "region" CHANNEL = "channel" STORE = "store_id"
class Period(StrEnum): """The time buckets of a report."""
ALL = "all" YEAR = "year" QUARTER = "quarter" MONTH = "month"
def label(self, day: date) -> str: """Return the bucket of a date, for example '2024-Q3'.""" match self: case Period.ALL: return "all" case Period.YEAR: return str(day.year) case Period.QUARTER: return f"{day.year}-Q{(day.month - 1) // 3 + 1}" case Period.MONTH: return f"{day:%Y-%m}"
@dataclass(frozen=True, slots=True, kw_only=True)class ReportConfig: """What one report shows. Frozen, so a report cannot change its settings."""
group_by: GroupBy = GroupBy.CATEGORY period: Period = Period.ALL top: int | None = None # None keeps every group year: int | None = None # None keeps every year
def __post_init__(self) -> None: if self.top is not None and self.top < 1: raise ValueError(f"top must be at least 1, got {self.top}")
@property def title(self) -> str: parts = [f"Revenue by {self.group_by}"] if self.period is not Period.ALL: parts.append(f"per {self.period}") if self.year is not None: parts.append(f"in {self.year}") if self.top is not None: parts.append(f"(top {self.top})") return " ".join(parts)salesreport/report.py holds the calculations; it knows nothing about the terminal. Build it in this order, with a test before each step:
ReportRowandReport, thenbuild_report()forPeriod.ALLonly: one total per group, ranked.- Periods: a nested
defaultdictholds a runningTotalsobject per period and group. - The tie-breaker,
topand the year filter. Summaryandsummarize(), the headline numbers that thesummarycommand prints.
"""Aggregate sales lines into a ranked revenue report."""
from collections import defaultdictfrom collections.abc import Iteratorfrom dataclasses import dataclass, fieldfrom datetime import datefrom decimal import Decimal
from .config import ReportConfigfrom .errors import DataError, SchemaErrorfrom .models import SalesData
CENT = Decimal("0.01")
@dataclass(frozen=True, slots=True)class ReportRow: """One group in one period."""
period: str rank: int group: str orders: int units: int revenue: Decimal share: float # share of the period's revenue, from 0 to 1
@dataclass(frozen=True, slots=True)class Report: """The result of build_report(): the settings, the rows and the totals."""
config: ReportConfig rows: tuple[ReportRow, ...] total_revenue: Decimal lines: int # sales lines after the year filter
def __len__(self) -> int: return len(self.rows)
def __iter__(self) -> Iterator[ReportRow]: return iter(self.rows)
@property def title(self) -> str: return self.config.title
@dataclass(frozen=True, slots=True)class Summary: """The headline numbers of a set of sales lines."""
files: int lines: int skipped: int orders: int units: int revenue: Decimal first_date: date last_date: date
def summarize(data: SalesData) -> Summary: """Return the headline numbers. Orders are distinct order ids, not lines.""" if not data.sales: raise DataError("no sales lines") dates = [sale.order_date for sale in data.sales] return Summary( files=len(data.sources), lines=len(data), skipped=data.skipped, orders=len({sale.order_id for sale in data.sales}), units=sum(sale.quantity for sale in data.sales), revenue=data.revenue.quantize(CENT), first_date=min(dates), last_date=max(dates), )
@dataclassclass Totals: """Running totals of one group while the lines are counted."""
orders: set[str] = field(default_factory=set) units: int = 0 revenue: Decimal = Decimal(0)
def build_report(data: SalesData, config: ReportConfig) -> Report: """Group the lines by period and column, then rank each period's groups.""" column = config.group_by.value if column not in data.columns: raise SchemaError(f"cannot group by {column}: the input has no such column") sales = [ sale for sale in data.sales if config.year is None or sale.order_date.year == config.year ] if not sales: where = "" if config.year is None else f" in {config.year}" raise DataError(f"no sales lines{where}")
cells: defaultdict[str, defaultdict[str, Totals]] = defaultdict( lambda: defaultdict(Totals) ) for sale in sales: group = getattr(sale, column) or "(missing)" cell = cells[config.period.label(sale.order_date)][group] cell.orders.add(sale.order_id) cell.units += sale.quantity cell.revenue += sale.revenue
rows: list[ReportRow] = [] for period in sorted(cells): groups = cells[period] period_revenue = sum((t.revenue for t in groups.values()), Decimal(0)) # Largest revenue first; the name breaks ties, so the order is stable. ranked = sorted(groups.items(), key=lambda item: (-item[1].revenue, item[0])) for rank, (group, t) in enumerate(ranked[: config.top], start=1): share = float(t.revenue / period_revenue) if period_revenue else 0.0 rows.append( ReportRow( period=period, rank=rank, group=group, orders=len(t.orders), units=t.units, revenue=t.revenue.quantize(CENT), share=share, ) ) total = sum((sale.revenue for sale in sales), Decimal(0)).quantize(CENT) return Report( config=config, rows=tuple(rows), total_revenue=total, lines=len(sales) )Design notes:
- The sort key
(-revenue, group)puts the largest revenue first and breaks ties by name, so two runs always give the same order.ranked[: config.top]keeps everything whentopisNone. Reportdefines__len__and__iter__, solen(report)andfor row in reportread naturally.summarize()returns a frozen dataclass instead of printing. A test can then compare the whole result with one==, and the command line only formats it.
"""The report engine: grouping, periods, ranking, top N and filters."""
from collections.abc import Callablefrom datetime import datefrom decimal import Decimalfrom pathlib import Path
import pytest
from salesreport.config import GroupBy, Period, ReportConfigfrom salesreport.errors import DataError, SchemaErrorfrom salesreport.loader import load_salesfrom salesreport.models import SalesDatafrom salesreport.report import Summary, build_report, summarizefrom samples import HEADER, ROWS
def test_groups_are_ranked_by_revenue(sales_data: SalesData) -> None: report = build_report(sales_data, ReportConfig()) summary = [(row.rank, row.group, row.orders, row.revenue) for row in report] assert summary == [ (1, "Electronics", 2, Decimal("1350.50")), (2, "Clothing", 1, Decimal("120.00")), (3, "Books", 2, Decimal("45.00")), ] assert report.total_revenue == Decimal("1515.50") assert report.lines == 5
@pytest.mark.parametrize( ("period", "label"), [ (Period.ALL, "all"), (Period.YEAR, "2024"), (Period.QUARTER, "2024-Q3"), (Period.MONTH, "2024-08"), ],)def test_period_labels(period: Period, label: str) -> None: assert period.label(date(2024, 8, 31)) == label
def test_shares_add_up_to_one_in_each_period(sales_data: SalesData) -> None: report = build_report(sales_data, ReportConfig(period=Period.MONTH)) for period in {row.period for row in report}: shares = [row.share for row in report if row.period == period] assert sum(shares) == pytest.approx(1.0)
def test_top_n_applies_to_each_period(sales_data: SalesData) -> None: config = ReportConfig(period=Period.YEAR, top=1) report = build_report(sales_data, config) assert [(row.period, row.group) for row in report] == [ ("2023", "Books"), ("2024", "Electronics"), ]
def test_ties_are_broken_by_name(write_csv: Callable[..., Path]) -> None: rows = [ ("O1", "2024-01-05", "S01", "North", "store", "Mug", "Home", "1", "10.00"), ("O2", "2024-01-05", "S01", "North", "store", "Atlas", "Books", "1", "10.00"), ] report = build_report(load_sales([write_csv(rows=rows)]), ReportConfig()) assert [row.group for row in report] == ["Books", "Home"]
def test_year_filter_keeps_one_year(sales_data: SalesData) -> None: report = build_report(sales_data, ReportConfig(year=2023)) assert (report.lines, report.total_revenue) == (1, Decimal("15.00"))
def test_year_without_sales_is_a_data_error(sales_data: SalesData) -> None: with pytest.raises(DataError, match="no sales lines in 2022"): build_report(sales_data, ReportConfig(year=2022))
def test_missing_group_column_is_a_schema_error( write_csv: Callable[..., Path],) -> None: keep = [i for i, name in enumerate(HEADER) if name != "channel"] path = write_csv( header=[HEADER[i] for i in keep], rows=[[row[i] for i in keep] for row in ROWS] ) with pytest.raises(SchemaError, match="cannot group by channel"): build_report(load_sales([path]), ReportConfig(group_by=GroupBy.CHANNEL))
def test_empty_data_has_a_clear_message() -> None: empty = SalesData(sales=(), columns=frozenset({"category"}), sources=()) with pytest.raises(DataError, match="^no sales lines$"): build_report(empty, ReportConfig()) with pytest.raises(DataError, match="^no sales lines$"): summarize(empty)
def test_summary_counts_distinct_orders(sales_data: SalesData) -> None: assert summarize(sales_data) == Summary( files=1, lines=5, skipped=0, orders=4, units=8, revenue=Decimal("1515.50"), first_date=date(2023, 12, 30), last_date=date(2024, 4, 1), )
def test_config_rejects_top_below_one() -> None: with pytest.raises(ValueError, match="at least 1"): ReportConfig(top=0)
def test_config_title_names_every_setting() -> None: config = ReportConfig(group_by=GroupBy.REGION, period=Period.YEAR, top=2) assert config.title == "Revenue by region per year (top 2)"pytest -q tests/test_report.py............... [100%]15 passed in 0.02sRank the categories of the real data:
from salesreport.config import GroupBy, Period, ReportConfigfrom salesreport.report import build_report
by_category = build_report(sales, ReportConfig())print(by_category.title)for row in by_category: print(f"{row.rank}. {row.group:<12}{row.revenue:>14,.2f}{row.share:>7.1%}")assert [row.group for row in by_category][:2] == ["Electronics", "Home"]assert round(by_category.rows[0].revenue) == 1_808_108 # the oracleRevenue by category1. Electronics 1,808,108.17 50.3%2. Home 672,294.61 18.7%3. Sports 544,108.55 15.1%4. Clothing 314,686.62 8.7%5. Beauty 150,417.76 4.2%6. Books 106,908.12 3.0%Electronics brings half of the revenue. Now check the yearly totals with a channel report per year:
per_year = ReportConfig(group_by=GroupBy.CHANNEL, period=Period.YEAR)year_totals: dict[str, Decimal] = {}for row in build_report(sales, per_year): year_totals[row.period] = year_totals.get(row.period, Decimal(0)) + row.revenue print(row.period, f"{row.group:<7}{row.revenue:>14,.2f}{row.share:>7.1%}")old, new = year_totals["2023"], year_totals["2024"]print(f"2023 {old:,.2f} 2024 {new:,.2f} growth {new / old - 1:+.1%}")assert year_totals == {"2023": Decimal("1645589.59"), "2024": Decimal("1950934.24")}2023 store 1,022,736.53 62.2%2023 online 622,853.06 37.8%2024 store 1,054,320.83 54.0%2024 online 896,613.41 46.0%2023 1,645,589.59 2024 1,950,934.24 growth +18.6%Both yearly totals and the growth of 18.6% match the oracle. The online share of revenue rises from 37.8% to 46.0%. The data dictionary gives an online share of 36.8% and 46.2%. Count the lines to see what that share measures:
for year in (2023, 2024): lines = [sale for sale in sales.sales if sale.order_date.year == year] online = sum(sale.channel == "online" for sale in lines) share = online / len(lines) print(f"{year}: {online:,} of {len(lines):,} lines are online ({share:.1%})")assert round(share, 3) == 0.462 # the oracle's 2024 online share2023: 3,345 of 9,081 lines are online (36.8%)2024: 5,150 of 11,147 lines are online (46.2%)The dictionary’s share counts lines. A report that ranks revenue gives a slightly different share, and both are correct for what they measure. Say which one you mean when you report a share.
Reference solution — Milestone 4: Report writers
salesreport/writers.py applies four patterns from module 22:
- Strategy: each writer class is one interchangeable way to turn a
Reportinto text. The command line holds a writer and callsrender()orwrite(). It never asks which format it has. - Template method:
ReportWriter.write()is the same for every format: check the target, call the subclass’srender(), save the text safely. Subclasses only fill inrender(). - Registry and factory:
@registeradds each class toWRITERSunder itsname.get_writer("json")builds a writer from a name. A new format is one new class; the command line’s--formatchoices come from the registry.
Build it in this order, with a test before each step:
ReportWriterwith the abstractrender(), andCsvWriter.WRITERS,register(),writer_names()andget_writer().JsonWriterandMarkdownWriter.atomic_write()andReportWriter.write().
"""Report writers: one class per output format, found by name in a registry."""
import csvimport ioimport jsonimport loggingimport osimport tempfilefrom abc import ABC, abstractmethodfrom collections.abc import Iteratorfrom contextlib import contextmanagerfrom pathlib import Pathfrom typing import IO, ClassVar
from .errors import OutputErrorfrom .report import Report, ReportRow
log = logging.getLogger(__name__)
FIELDS = ("period", "rank", "group", "orders", "units", "revenue", "share")
class ReportWriter(ABC): """Turn a Report into text (render) and save it to a file (write)."""
name: ClassVar[str] # the value of --format suffix: ClassVar[str] description: ClassVar[str]
@abstractmethod def render(self, report: Report) -> str: """Return the whole report as text."""
def write(self, report: Report, path: Path, *, overwrite: bool = False) -> None: """Render the report and save it. Never leave a half-written file.""" if path.exists() and not overwrite: raise OutputError(f"{path} already exists (use --force to replace it)") content = self.render(report) try: with atomic_write(path) as file: file.write(content) except OSError as exc: raise OutputError(f"cannot write {path}: {exc.strerror}") from exc log.info("wrote %s: %d rows as %s", path, len(report), self.name)
WRITERS: dict[str, type[ReportWriter]] = {}
def register[W: type[ReportWriter]](cls: W) -> W: """Class decorator: add a writer to WRITERS under its name.""" if cls.name in WRITERS: raise ValueError(f"format {cls.name!r} is already registered") WRITERS[cls.name] = cls return cls
def writer_names() -> list[str]: return sorted(WRITERS)
def get_writer(name: str) -> ReportWriter: """Factory: return a new writer for a format name.""" try: return WRITERS[name]() except KeyError: known = ", ".join(writer_names()) raise ValueError(f"unknown format {name!r}; choose from: {known}") from None
@contextmanagerdef atomic_write(path: Path) -> Iterator[IO[str]]: """Write to a unique temporary file, then rename it over the target.""" path.parent.mkdir(parents=True, exist_ok=True) file = tempfile.NamedTemporaryFile( # closed by the "with file" below "w", encoding="utf-8", newline="", dir=path.parent, # same folder, so the rename stays on one disk prefix=f".{path.name}.", suffix=".tmp", delete=False, ) temporary = Path(file.name) try: with file: yield file file.flush() os.fsync(file.fileno()) # the bytes are on disk before the rename temporary.replace(path) finally: temporary.unlink(missing_ok=True)
def as_record(row: ReportRow) -> dict[str, str | int | float]: """Return a row as plain JSON-ready values.""" return { "period": row.period, "rank": row.rank, "group": row.group, "orders": row.orders, "units": row.units, "revenue": float(row.revenue), "share": round(row.share, 4), }
@registerclass CsvWriter(ReportWriter): name = "csv" suffix = ".csv" description = "one row per group, for spreadsheets and pandas"
def render(self, report: Report) -> str: buffer = io.StringIO() writer = csv.DictWriter(buffer, fieldnames=FIELDS, lineterminator="\n") writer.writeheader() for row in report: writer.writerow(as_record(row) | {"revenue": f"{row.revenue:.2f}"}) return buffer.getvalue()
@registerclass JsonWriter(ReportWriter): name = "json" suffix = ".json" description = "settings, totals and rows, for other programs"
def render(self, report: Report) -> str: config = report.config document = { "title": report.title, "group_by": config.group_by.value, "period": config.period.value, "top": config.top, "year": config.year, "lines": report.lines, "total_revenue": float(report.total_revenue), "rows": [as_record(row) for row in report], } return json.dumps(document, indent=2) + "\n"
@registerclass MarkdownWriter(ReportWriter): name = "markdown" suffix = ".md" description = "an aligned table, for the terminal, wikis and pull requests"
RIGHT: ClassVar[frozenset[str]] = frozenset(FIELDS) - {"period", "group"}
def render(self, report: Report) -> str: body = [ [ row.period, str(row.rank), row.group.replace("|", r"\|"), # a bare | would end the cell f"{row.orders:,}", f"{row.units:,}", f"{row.revenue:,.2f}", f"{row.share:.1%}", ] for row in report ] widths = [max(map(len, column)) for column in zip(FIELDS, *body, strict=True)]
def line(cells: list[str] | tuple[str, ...]) -> str: padded = [ cell.rjust(width) if name in self.RIGHT else cell.ljust(width) for name, cell, width in zip(FIELDS, cells, widths, strict=True) ] return "| " + " | ".join(padded) + " |"
rule = [ "-" * (width + 1) + ":" if name in self.RIGHT else "-" * (width + 2) for name, width in zip(FIELDS, widths, strict=True) ] lines = [ f"## {report.title}", "", line(FIELDS), "|" + "|".join(rule) + "|", *(line(cells) for cells in body), "", f"{report.lines:,} sales lines, revenue {report.total_revenue:,.2f} USD", ] return "\n".join(lines) + "\n"Design notes:
- An atomic write happens completely or not at all.
atomic_write()writes to a temporary file in the same folder, forces the bytes to disk withos.fsync(), thenPath.replace()renames the file over the target in one step. If the program crashes or the disk fills up, the old report stays in place, never half a new one. Thefinallyclause removes the temporary file when something fails. tempfile.NamedTemporaryFile(delete=False)gives each run a unique temporary name, so two runs that write the same target at the same time do not share a temporary file.- The
exists()check and the rename are two steps, so another program could still create the target between them. For a report tool that one team runs, that risk is acceptable. register[W: type[ReportWriter]]is a generic function (module 12): it returns the same class it receives, so type checkers still seeCsvWriter, not onlyReportWriter.- The registry rejects a second writer with the same name. Two plugins can then never replace each other silently.
MarkdownWriterescapes|in group names. A product such asUSB-C|HDMI Cablewould otherwise split its table cell in two.as_record()convertsDecimaltofloatonly at the edge, for JSON. Inside the tool, money stays exact.
The failure tests do not need a full disk. monkeypatch replaces os.fsync with a function that raises the error a full disk raises, only for the duration of one test:
"""Writers: the registry, each format's content and safe file writing."""
import csvimport errnoimport jsonimport osfrom collections.abc import Callablefrom pathlib import Pathfrom typing import ClassVar
import pytest
from salesreport.config import GroupBy, ReportConfigfrom salesreport.errors import OutputErrorfrom salesreport.loader import load_salesfrom salesreport.models import SalesDatafrom salesreport.report import Report, build_reportfrom salesreport.writers import ( ReportWriter, get_writer, register, writer_names,)from samples import HEADER, ROWS
@pytest.fixturedef report(sales_data: SalesData) -> Report: return build_report(sales_data, ReportConfig())
def full_disk(fd: int) -> None: """A stand-in for os.fsync that fails as a full disk does.""" raise OSError(errno.ENOSPC, "No space left on device")
def test_registry_holds_three_formats() -> None: assert writer_names() == ["csv", "json", "markdown"]
@pytest.mark.parametrize("name", writer_names())def test_every_writer_saves_what_it_renders( report: Report, tmp_path: Path, name: str) -> None: writer = get_writer(name) path = tmp_path / "out" / f"report{writer.suffix}" # write() makes the folder writer.write(report, path) assert path.read_text(encoding="utf-8") == writer.render(report) assert list(path.parent.iterdir()) == [path] # no temporary file is left
def test_csv_has_one_row_per_group(report: Report) -> None: rows = list(csv.DictReader(get_writer("csv").render(report).splitlines())) assert [row["group"] for row in rows] == ["Electronics", "Clothing", "Books"] assert rows[0]["revenue"] == "1350.50" assert rows[0]["share"] == "0.8911"
def test_json_has_settings_totals_and_rows(report: Report) -> None: document = json.loads(get_writer("json").render(report)) assert document["group_by"] == "category" assert document["total_revenue"] == 1515.5 assert len(document["rows"]) == 3
def test_markdown_is_an_aligned_table(report: Report) -> None: lines = get_writer("markdown").render(report).splitlines() assert lines[0] == "## Revenue by category" table = [line for line in lines if line.startswith("|")] assert len({len(line) for line in table}) == 1 # every line has the same width assert lines[-1] == "5 sales lines, revenue 1,515.50 USD"
def test_existing_file_is_kept_unless_overwrite(report: Report, tmp_path: Path) -> None: path = tmp_path / "report.csv" path.write_text("old", encoding="utf-8") writer = get_writer("csv") with pytest.raises(OutputError, match="already exists"): writer.write(report, path) assert path.read_text(encoding="utf-8") == "old" writer.write(report, path, overwrite=True) assert path.read_text(encoding="utf-8").startswith("period,rank,group")
def test_failed_write_keeps_the_old_file( report: Report, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: path = tmp_path / "report.csv" path.write_text("old", encoding="utf-8") monkeypatch.setattr(os, "fsync", full_disk) with pytest.raises(OutputError, match="No space left on device"): get_writer("csv").write(report, path, overwrite=True) assert path.read_text(encoding="utf-8") == "old" assert list(tmp_path.glob(".*.tmp")) == []
def test_markdown_escapes_a_pipe_in_a_group(write_csv: Callable[..., Path]) -> None: rows = [list(row) for row in ROWS] rows[0][HEADER.index("product")] = "USB-C|HDMI Cable" data = load_sales([write_csv(rows=rows)]) text = get_writer("markdown").render( build_report(data, ReportConfig(group_by=GroupBy.PRODUCT)) ) assert r"| USB-C\|HDMI Cable |" in text
def test_unknown_format_lists_the_choices() -> None: with pytest.raises(ValueError, match="choose from: csv, json, markdown"): get_writer("xlsx")
def test_registry_rejects_a_duplicate_name() -> None: with pytest.raises(ValueError, match="already registered"):
@register class OtherCsv(ReportWriter): name: ClassVar[str] = "csv" suffix: ClassVar[str] = ".csv" description: ClassVar[str] = "a second csv writer"
def render(self, report: Report) -> str: return ""pytest -q tests/test_writers.py............ [100%]12 passed in 0.02sRender one small report from the real data in every registered format:
import json
from salesreport.writers import get_writer, writer_names
stores = build_report(sales, ReportConfig(group_by=GroupBy.STORE, year=2024, top=2))for name in writer_names(): print(f"--- {name}") print(get_writer(name).render(stores), end="")document = json.loads(get_writer("json").render(stores))assert [row["group"] for row in document["rows"]] == ["S07", "S01"]assert document["total_revenue"] == 1950934.24--- csvperiod,rank,group,orders,units,revenue,shareall,1,S07,1058,2038,263924.00,0.1353all,2,S01,897,1864,220899.08,0.1132--- json{ "title": "Revenue by store_id in 2024 (top 2)", "group_by": "store_id", "period": "all", "top": 2, "year": 2024, "lines": 11147, "total_revenue": 1950934.24, "rows": [ { "period": "all", "rank": 1, "group": "S07", "orders": 1058, "units": 2038, "revenue": 263924.0, "share": 0.1353 }, { "period": "all", "rank": 2, "group": "S01", "orders": 897, "units": 1864, "revenue": 220899.08, "share": 0.1132 } ]}--- markdown## Revenue by store_id in 2024 (top 2)
| period | rank | group | orders | units | revenue | share ||--------|-----:|-------|-------:|------:|-----------:|------:|| all | 1 | S07 | 1,058 | 2,038 | 263,924.00 | 13.5% || all | 2 | S01 | 897 | 1,864 | 220,899.08 | 11.3% |
11,147 sales lines, revenue 1,950,934.24 USDThe same Report object gives three texts. The two largest stores in 2024 are S07 (New York) and S01 (Chicago), which are also the two stores with the most sales lines in the data dictionary. The share is the share of all 2024 revenue, because top only hides rows; it does not change the total.
Reference solution — Milestone 5: Command-line interface
salesreport/cli.py is the only module that knows about the terminal. It parses the arguments, configures logging, runs one handler and turns a SalesReportError into one line on stderr and an exit code. Build it in this order, with a test before each step:
build_parser()withsummaryandreport, andmain()that calls the handler.positive_int()andfraction(), the argparse types that check option values.configure_logging()and-v.- The
exceptclauses ofmain(): expected errors, then a closed pipe. formats, the subcommand that reads the registry.
"""The command line: parse the arguments, run one command, return an exit code."""
import argparseimport loggingimport osimport sysfrom collections.abc import Callable, Sequencefrom pathlib import Path
from . import __version__from .config import GroupBy, Period, ReportConfigfrom .errors import ExitCode, SalesReportErrorfrom .loader import load_salesfrom .report import build_report, summarizefrom .writers import WRITERS, get_writer, writer_names
log = logging.getLogger(__name__)LOG_FORMAT = "%(levelname)s %(name)s: %(message)s"VERBOSE_HELP = "show progress (-v) or every skipped row (-vv)"
def positive_int(value: str) -> int: """argparse type for --top: an int of at least 1.""" try: number = int(value) except ValueError: raise argparse.ArgumentTypeError(f"not a whole number: {value!r}") from None if number < 1: raise argparse.ArgumentTypeError(f"must be at least 1, got {number}") return number
def fraction(value: str) -> float: """argparse type for --max-bad: a number from 0 to 1.""" try: number = float(value) except ValueError: raise argparse.ArgumentTypeError(f"not a number: {value!r}") from None if not 0 <= number <= 1: raise argparse.ArgumentTypeError(f"must be from 0 to 1, got {number}") return number
def configure_logging(verbosity: int) -> None: """Send this package's log records to stderr: -v for INFO, -vv for DEBUG.""" levels = {0: logging.WARNING, 1: logging.INFO} logger = logging.getLogger("salesreport") logger.setLevel(levels.get(verbosity, logging.DEBUG)) logger.handlers.clear() # main() may run many times in one test session logger.propagate = False # a host program's root handler must not print twice handler = logging.StreamHandler() # the current sys.stderr handler.setFormatter(logging.Formatter(LOG_FORMAT)) logger.addHandler(handler)
def run_summary(args: argparse.Namespace) -> int: summary = summarize(load_sales(args.paths, max_bad=args.max_bad)) facts = { "files": f"{summary.files:,}", "sales lines": f"{summary.lines:,}", "skipped lines": f"{summary.skipped:,}", "orders": f"{summary.orders:,}", "units": f"{summary.units:,}", "revenue": f"{summary.revenue:,.2f}", "first date": f"{summary.first_date}", "last date": f"{summary.last_date}", } for name, value in facts.items(): print(f"{name:<14}{value:>14}") return ExitCode.OK
def run_report(args: argparse.Namespace) -> int: config = ReportConfig( group_by=GroupBy(args.by), period=Period(args.period), top=args.top, year=args.year, ) report = build_report(load_sales(args.paths, max_bad=args.max_bad), config) writer = get_writer(args.format) if args.output is None: print(writer.render(report), end="") else: writer.write(report, args.output, overwrite=args.force) print(f"wrote {len(report)} rows to {args.output}") return ExitCode.OK
def run_formats(args: argparse.Namespace) -> int: for name in writer_names(): writer = WRITERS[name] print(f"{name:<10}{writer.suffix:<7}{writer.description}") return ExitCode.OK
def build_parser() -> argparse.ArgumentParser: """Return the parser of the salesreport command and its subcommands.""" parser = argparse.ArgumentParser( prog="salesreport", description="Turn sales CSV files into ranked revenue reports.", epilog="Run 'salesreport COMMAND --help' for the options of a command.", ) parser.add_argument( "--version", action="version", version=f"%(prog)s {__version__}" ) parser.add_argument("-v", "--verbose", action="count", default=0, help=VERBOSE_HELP) # Options that every data command shares, added through parents=[inputs]. inputs = argparse.ArgumentParser(add_help=False) inputs.add_argument( "paths", nargs="+", type=Path, metavar="PATH", help="CSV file or folder" ) inputs.add_argument( "--max-bad", type=fraction, default=0.05, metavar="FRACTION", help="fail when a larger share of rows is invalid (default: %(default)s)", ) # SUPPRESS: without -v after the command, keep the value of -v before it. inputs.add_argument( "-v", "--verbose", action="count", default=argparse.SUPPRESS, help=VERBOSE_HELP ) commands = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
summary = commands.add_parser( "summary", parents=[inputs], help="print headline numbers of the input" ) summary.set_defaults(handler=run_summary)
report = commands.add_parser( "report", parents=[inputs], help="rank revenue by a column and period" ) report.add_argument( "--by", choices=[g.value for g in GroupBy], default=GroupBy.CATEGORY.value, help="column to group by (default: %(default)s)", ) report.add_argument( "--period", choices=[p.value for p in Period], default=Period.ALL.value, help="time bucket (default: %(default)s)", ) report.add_argument( "--top", type=positive_int, metavar="N", help="keep the N best groups" ) report.add_argument("--year", type=int, help="keep only the sales of this year") report.add_argument( "--format", choices=writer_names(), default="markdown", help="output format (default: %(default)s)", ) report.add_argument( "-o", "--output", type=Path, metavar="FILE", help="write to FILE, not stdout" ) report.add_argument("--force", action="store_true", help="replace FILE") report.set_defaults(handler=run_report)
formats = commands.add_parser("formats", help="list the output formats") formats.set_defaults(handler=run_formats) return parser
def main(argv: Sequence[str] | None = None) -> int: """Run the command. argv=None reads the real command line.""" parser = build_parser() args = parser.parse_args(argv) # exits with 2 on a usage error configure_logging(args.verbose) handler: Callable[[argparse.Namespace], int] = args.handler try: code = handler(args) sys.stdout.flush() # a closed pipe fails here, inside the try except SalesReportError as exc: print(f"{parser.prog}: error: {exc}", file=sys.stderr) return exc.exit_code except BrokenPipeError: # The reader (for example "head") closed stdout. Point stdout at devnull, # so the final flush when Python exits does not fail a second time. devnull = os.open(os.devnull, os.O_WRONLY) os.dup2(devnull, sys.stdout.fileno()) return ExitCode.PIPE_CLOSED return codeDesign notes:
- A subcommand is a command inside a command, like
git commit.add_subparsers()creates them.set_defaults(handler=...)stores the function to run, somain()has noifper command. - The
inputsparser is a parent parser:parents=[inputs]copies its arguments intosummaryandreport, so they sharePATH,--max-badand-vwithout repeated code. -vexists on the main parser and on the subcommands, sosalesreport -v summary ...andsalesreport summary ... -vboth work. On the subcommands its default isargparse.SUPPRESS: a subcommand without-vthen sets no value and keeps the one from the main parser.type=positive_intvalidates at parse time. A bad value gets argparse’s standard usage text and exit code 2, the Unix convention for a usage error.configure_logging()attaches one handler to thesalesreportlogger, not to the root logger, and setspropagate = False. A program that callsmain()and has its own root handler then does not see each line twice. The handler setup is cleared first, because the tests callmain()many times in one process.- Data goes to stdout and messages go to stderr. A pipe such as
salesreport report ... > report.mdthen receives only the report. - When the reader of a pipe stops early (
| head -n 3), the next write raisesBrokenPipeError.main()catches it, points stdout atos.devnull, as the Python documentation recommends, and returns 141. A shell reports 141 (128 + signal 13, SIGPIPE) for programs that a closed pipe stops, so scripts can recognize the case. - Only expected problems (
SalesReportError) become one-line messages. A real bug still shows its full traceback, so you can fix it.
The tests call main([...]) in the same process instead of starting python -m salesreport in a subprocess. That is faster, and capsys captures the output. main(argv=None) is what makes this possible. Only the closed-pipe test starts a real process, because it needs a real pipe.
"""The command line, called in-process through main(argv)."""
import errnoimport jsonimport osimport subprocessimport sysfrom collections.abc import Callablefrom pathlib import Path
import pytest
from salesreport import __version__from salesreport.cli import mainfrom salesreport.errors import ExitCodefrom samples import HEADER, ROWS
def test_report_prints_markdown( sales_csv: Path, capsys: pytest.CaptureFixture[str]) -> None: assert main(["report", str(sales_csv), "--top", "1"]) == ExitCode.OK out, err = capsys.readouterr() assert out.startswith("## Revenue by category (top 1)") assert "Electronics" in out assert "Books" not in out assert err == ""
def test_report_writes_json_file( sales_csv: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: target = tmp_path / "out" / "region.json" args = ["report", str(sales_csv), "--by", "region", "--format", "json"] assert main([*args, "-o", str(target)]) == ExitCode.OK assert capsys.readouterr().out == f"wrote 3 rows to {target}\n" rows = json.loads(target.read_text(encoding="utf-8"))["rows"] assert rows[0]["group"] == "North"
def test_summary_prints_headline_numbers( sales_csv: Path, capsys: pytest.CaptureFixture[str]) -> None: assert main(["summary", str(sales_csv)]) == ExitCode.OK lines = capsys.readouterr().out.splitlines() assert lines[1].split() == ["sales", "lines", "5"] assert "1,515.50" in lines[5]
def test_missing_file_exits_with_1( tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: missing = tmp_path / "nope.csv" assert main(["summary", str(missing)]) == ExitCode.DATA_ERROR assert capsys.readouterr().err == f"salesreport: error: file not found: {missing}\n"
@pytest.mark.parametrize("command", ["summary", "report"])def test_no_valid_row_exits_with_1( write_csv: Callable[..., Path], capsys: pytest.CaptureFixture[str], command: str) -> None: rows = [list(row) for row in ROWS] for row in rows: row[HEADER.index("quantity")] = "0" path = write_csv(rows=rows) assert main([command, str(path), "--max-bad", "1"]) == ExitCode.DATA_ERROR assert capsys.readouterr().err == ( "salesreport: error: the input has no valid rows (5 invalid); -vv lists them\n" )
def test_write_failure_exits_with_3( sales_csv: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str], monkeypatch: pytest.MonkeyPatch,) -> None: def full_disk(fd: int) -> None: raise OSError(errno.ENOSPC, "No space left on device")
monkeypatch.setattr(os, "fsync", full_disk) target = tmp_path / "report.md" assert main(["report", str(sales_csv), "-o", str(target)]) == 3 message = f"salesreport: error: cannot write {target}: No space left on device\n" assert capsys.readouterr().err == message assert not target.exists()
def test_existing_output_exits_with_3( sales_csv: Path, capsys: pytest.CaptureFixture[str]) -> None: code = main(["report", str(sales_csv), "-o", str(sales_csv)]) assert code == ExitCode.OUTPUT_ERROR assert "already exists" in capsys.readouterr().err
@pytest.mark.parametrize( ("option", "message"), [ (["--top", "0"], "must be at least 1, got 0"), (["--top", "three"], "not a whole number: 'three'"), (["--max-bad", "2"], "must be from 0 to 1, got 2.0"), (["--by", "city"], "invalid choice: 'city'"), ],)def test_bad_option_is_a_usage_error( sales_csv: Path, capsys: pytest.CaptureFixture[str], option: list[str], message: str,) -> None: with pytest.raises(SystemExit) as stop: main(["report", str(sales_csv), *option]) assert stop.value.code == ExitCode.USAGE_ERROR assert message in capsys.readouterr().err
def test_verbose_logs_to_stderr( sales_csv: Path, capsys: pytest.CaptureFixture[str]) -> None: main(["summary", str(sales_csv)]) assert capsys.readouterr().err == "" main(["summary", str(sales_csv), "-v"]) assert "INFO salesreport.loader: read" in capsys.readouterr().err
def test_verbose_works_before_the_command( sales_csv: Path, capsys: pytest.CaptureFixture[str]) -> None: main(["-v", "summary", str(sales_csv)]) assert "INFO salesreport.loader: read" in capsys.readouterr().err
def test_very_verbose_lists_each_skipped_row( write_csv: Callable[..., Path], capsys: pytest.CaptureFixture[str]) -> None: rows = [list(row) for row in ROWS] rows[2][HEADER.index("quantity")] = "-1" # file line 4: line 1 is the header path = write_csv(rows=rows) assert main(["summary", str(path), "--max-bad", "0.5", "-vv"]) == ExitCode.OK err = capsys.readouterr().err assert f"DEBUG salesreport.loader: {path}:4: quantity must be at least 1" in err assert "WARNING salesreport.loader: skipped 1 invalid rows of 5" in err
def test_closed_pipe_exits_quietly(write_csv: Callable[..., Path]) -> None: # 3,000 products give about 300 KB of output, more than a pipe buffer holds. rows = [ (f"O{i}", "2024-01-05", "S01", "North", "store", f"P{i:04d}", "Home", "1", "1") for i in range(3_000) ] path = write_csv(rows=rows) project = Path(__file__).resolve().parents[1] command = [sys.executable, "-m", "salesreport", "report", str(path), "--by"] with subprocess.Popen( [*command, "product"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, env=os.environ | {"PYTHONPATH": str(project)}, ) as process: assert process.stdout is not None and process.stderr is not None first_line = process.stdout.readline() process.stdout.close() # what "| head -n 1" does after one line errors = process.stderr.read() assert first_line == "## Revenue by product\n" assert process.returncode == ExitCode.PIPE_CLOSED assert errors == ""
def test_formats_lists_the_registry(capsys: pytest.CaptureFixture[str]) -> None: assert main(["formats"]) == ExitCode.OK names = [line.split()[0] for line in capsys.readouterr().out.splitlines()] assert names == ["csv", "json", "markdown"]
def test_version(capsys: pytest.CaptureFixture[str]) -> None: with pytest.raises(SystemExit) as stop: main(["--version"]) assert stop.value.code == 0 assert capsys.readouterr().out == f"salesreport {__version__}\n"pytest -q tests/test_cli.py.................. [100%]18 passed in 0.10sThe help that argparse generates from the parser:
python -m salesreport --helpusage: salesreport [-h] [--version] [-v] COMMAND ...
Turn sales CSV files into ranked revenue reports.
positional arguments: COMMAND summary print headline numbers of the input report rank revenue by a column and period formats list the output formats
options: -h, --help show this help message and exit --version show program's version number and exit -v, --verbose show progress (-v) or every skipped row (-vv)
Run 'salesreport COMMAND --help' for the options of a command.python -m salesreport report --helpusage: salesreport report [-h] [--max-bad FRACTION] [-v] [--by {category,product,region,channel,store_id}] [--period {all,year,quarter,month}] [--top N] [--year YEAR] [--format {csv,json,markdown}] [-o FILE] [--force] PATH [PATH ...]
positional arguments: PATH CSV file or folder
options: -h, --help show this help message and exit --max-bad FRACTION fail when a larger share of rows is invalid (default: 0.05) -v, --verbose show progress (-v) or every skipped row (-vv) --by {category,product,region,channel,store_id} column to group by (default: category) --period {all,year,quarter,month} time bucket (default: all) --top N keep the N best groups --year YEAR keep only the sales of this year --format {csv,json,markdown} output format (default: markdown) -o, --output FILE write to FILE, not stdout --force replace FILEPython 3.12 prints -o FILE, --output FILE; Python 3.13 and later print -o, --output FILE. The line breaks depend on the width of your terminal.
The headline numbers of the main file, the folder and the list of formats:
python -m salesreport summary data/sales.csvpython -m salesreport summary data/reportspython -m salesreport formatsfiles 1sales lines 20,228skipped lines 0orders 14,877units 29,533revenue 3,596,523.83first date 2023-01-01last date 2024-12-31files 6sales lines 297skipped lines 0orders 291units 409revenue 57,266.39first date 2024-01-02last date 2024-06-29csv .csv one row per group, for spreadsheets and pandasjson .json settings, totals and rows, for other programsmarkdown .md an aligned table, for the terminal, wikis and pull requestsThe orders (14,877) and units (29,533) match the oracle. The folder has 291 orders in 297 lines, because some orders have several lines. If a file is given twice, the tool warns and counts it once (2>&1 shows stderr and stdout together, in order):
python -m salesreport summary data/reports data/reports/2024-01.csv 2>&1 | head -n 3WARNING salesreport.loader: data/reports/2024-01.csv is given twice; reading it oncefiles 6sales lines 297The top two regions of each year:
python -m salesreport report data/sales.csv --by region --period year --top 2## Revenue by region per year (top 2)
| period | rank | group | orders | units | revenue | share ||--------|-----:|-------|-------:|------:|-----------:|------:|| 2023 | 1 | East | 1,796 | 3,506 | 448,918.63 | 27.3% || 2023 | 2 | North | 1,623 | 3,227 | 410,500.06 | 24.9% || 2024 | 1 | East | 2,206 | 4,326 | 544,765.09 | 27.9% || 2024 | 2 | South | 2,062 | 4,124 | 482,265.00 | 24.7% |
20,228 sales lines, revenue 3,596,523.83 USDEast leads both years, and its two years add up to 993,683.72, the oracle’s 993,684. South overtakes North in 2024. The best category of each month in the folder input, with progress on stderr:
python -m salesreport report data/reports --period month --top 1 -v 2>&1INFO salesreport.loader: read data/reports/2024-01.csv: 48 valid rows, 0 skippedINFO salesreport.loader: read data/reports/2024-02.csv: 48 valid rows, 0 skippedINFO salesreport.loader: read data/reports/2024-03.csv: 47 valid rows, 0 skippedINFO salesreport.loader: read data/reports/2024-04.csv: 52 valid rows, 0 skippedINFO salesreport.loader: read data/reports/2024-05.csv: 47 valid rows, 0 skippedINFO salesreport.loader: read data/reports/2024-06.csv: 55 valid rows, 0 skipped## Revenue by category per month (top 1)
| period | rank | group | orders | units | revenue | share ||---------|-----:|-------------|-------:|------:|----------:|------:|| 2024-01 | 1 | Electronics | 15 | 17 | 10,015.90 | 70.7% || 2024-02 | 1 | Sports | 6 | 11 | 1,259.39 | 26.7% || 2024-03 | 1 | Electronics | 13 | 16 | 8,763.48 | 71.3% || 2024-04 | 1 | Electronics | 9 | 11 | 5,094.35 | 46.8% || 2024-05 | 1 | Electronics | 8 | 8 | 2,988.61 | 44.8% || 2024-06 | 1 | Electronics | 12 | 13 | 4,087.00 | 47.9% |
297 sales lines, revenue 57,266.39 USDThe row counts per file match the data dictionary. These extracts are small samples of 47–55 lines a month, so a monthly winner is a weak signal: in February, Sports wins with only 26.7% of the revenue.
Write the three deliverables to output/. -o creates the folder:
python -m salesreport report data/sales.csv --period quarter --format csv \ -o output/category_quarter.csvpython -m salesreport report data/sales.csv --by region --year 2024 --format json \ -o output/region_2024.json -v 2>&1python -m salesreport report data/sales.csv --by product --top 5 -o output/top_products.mdhead -n 4 output/category_quarter.csvcat output/top_products.mdwrote 48 rows to output/category_quarter.csvINFO salesreport.loader: read data/sales.csv: 20228 valid rows, 0 skippedINFO salesreport.writers: wrote output/region_2024.json: 4 rows as jsonwrote 4 rows to output/region_2024.jsonwrote 5 rows to output/top_products.mdperiod,rank,group,orders,units,revenue,share2023-Q1,1,Electronics,265,313,139713.09,0.47972023-Q1,2,Home,252,359,54554.08,0.18732023-Q1,3,Sports,243,362,49435.31,0.1697## Revenue by product (top 5)
| period | rank | group | orders | units | revenue | share ||--------|-----:|-----------------------------|-------:|------:|-----------:|------:|| all | 1 | 14-inch Ultrabook Laptop | 532 | 599 | 665,328.45 | 18.5% || all | 2 | 55-inch 4K Smart TV | 427 | 504 | 628,586.10 | 17.5% || all | 3 | Noise-Cancelling Headphones | 856 | 966 | 231,943.50 | 6.4% || all | 4 | Espresso Machine | 479 | 585 | 197,987.70 | 5.5% || all | 5 | Adjustable Dumbbells | 436 | 611 | 165,084.30 | 4.6% |
20,228 sales lines, revenue 3,596,523.83 USDA long report can go into a pipe. Here head stops reading after three lines, and the tool stops quietly, without a traceback:
python -m salesreport report data/sales.csv --by product --period month --format json | head -n 3{ "title": "Revenue by product per month", "group_by": "product",Now every failure. $? holds the exit code of the last command. 2>&1 sends the error text to the same place as the normal output:
python -m salesreport summary data/nope.csv 2>&1; echo "exit code: $?"python -m salesreport report data/reports --by channel 2>&1; echo "exit code: $?"python -m salesreport summary data/sales_raw.csv 2>&1; echo "exit code: $?"python -m salesreport report data/sales.csv -o output/top_products.md 2>&1; echo "exit code: $?"salesreport: error: file not found: data/nope.csvexit code: 1salesreport: error: cannot group by channel: the input has no such columnexit code: 1salesreport: error: 480 of 1,200 rows (40.0%) are invalid, above the 5.0% limit; -vv lists themexit code: 1salesreport: error: output/top_products.md already exists (use --force to replace it)exit code: 3Each message names the problem and, where possible, the fix. A bad option is a usage error. argparse prints the usage text of the subcommand, then the error, and exits with 2:
python -m salesreport report data/sales.csv --top 0 2>&1; echo "exit code: $?"usage: salesreport report [-h] [--max-bad FRACTION] [-v] [--by {category,product,region,channel,store_id}] [--period {all,year,quarter,month}] [--top N] [--year YEAR] [--format {csv,json,markdown}] [-o FILE] [--force] PATH [PATH ...]salesreport report: error: argument --top: must be at least 1, got 0exit code: 2-vv lists the skipped rows with their file and line number. Send the log to a file and look at its ends:
python -m salesreport summary data/sales_raw.csv -vv 2> output/raw.log; echo "exit code: $?"head -n 3 output/raw.logtail -n 2 output/raw.logexit code: 1DEBUG salesreport.loader: data/sales_raw.csv:9: order_date is not YYYY-MM-DD: '07/01/2023'DEBUG salesreport.loader: data/sales_raw.csv:10: order_date is not YYYY-MM-DD: 'January 7, 2023'DEBUG salesreport.loader: data/sales_raw.csv:11: order_date is not YYYY-MM-DD: '10/01/2023'INFO salesreport.loader: read data/sales_raw.csv: 720 valid rows, 480 skippedsalesreport: error: 480 of 1,200 rows (40.0%) are invalid, above the 5.0% limit; -vv lists themReference solution — Milestone 6: Tests and quality checks
Each earlier milestone added its tests. This milestone checks the whole suite against the code: every rule and every error path must have a test. The table maps the rules to the pytest tools that check them:
| Rule | Test tool |
|---|---|
| each kind of bad value is skipped and logged | parametrize over 6 cases, caplog |
| each error raises its documented class with a clear message | pytest.raises(..., match=...) |
| an empty file, an all-invalid file, a BOM and a file given twice | small files written to tmp_path |
| every format saves exactly what it renders, with no temporary file left | parametrize over writer_names(), tmp_path |
| a failed write keeps the old file and exits with 3 | monkeypatch on os.fsync |
| the command prints data to stdout, messages to stderr | capsys |
-v and -vv log at the right levels, before or after the command |
capsys on stderr |
| bad options exit with 2, bad input with 1, a closed pipe with 141 | pytest.raises(SystemExit), return codes, one subprocess |
| the result does not depend on the column order | a reversed copy of the same file |
The error paths of the code and their tests:
| Error path | Exception or code | Test |
|---|---|---|
| file not found, empty folder, not UTF-8 | InputError |
test_missing_file_*, test_empty_folder_*, test_non_utf8_* |
| missing column (load or group by) | SchemaError |
test_missing_column_*, test_missing_group_column_* |
| 0-byte file, header only, no valid row, too many bad rows | DataError |
test_zero_byte_*, test_header_only_*, test_no_valid_row_*, test_too_many_* |
| empty year, empty data | DataError |
test_year_without_sales_*, test_empty_data_* |
| existing output, write failure | OutputError, exit code 3 |
test_existing_*, test_failed_write_*, test_write_failure_* |
| bad option values | exit code 2 | test_bad_option_is_a_usage_error |
| closed pipe | exit code 141 | test_closed_pipe_exits_quietly |
unknown format, duplicate format name, top=0 |
ValueError |
test_unknown_format_*, test_registry_rejects_*, test_config_rejects_* |
Run the whole suite and the quality checks:
pytest -q................................................................ [100%]64 passed in 0.14sruff check salesreport testsmypy --strict salesreport testsAll checks passed!Success: no issues found in 15 source files64 tests pass in well under one second. The lint and the strict type check are clean, for the tests too.
Stretch goals
Section titled “Stretch goals”- Read the version from the installed metadata with
importlib.metadata.version("salesreport"), so it lives only inpyproject.toml. - Add
--fromand--todate options, with an argparse type that parses ISO dates. - Add an
htmlwriter. Only one new class should change; check thatformatsand--formatpick it up. - Let other packages add writers through an entry point group such as
salesreport.writers(module 22), loaded withimportlib.metadata.entry_points(). - Read default options from
data/config.json(thresholds.max_missing_fractionis 0.05, the default of--max-bad), with command-line options taking priority. - Count exact duplicate lines and report them in
summary.data/sales_raw.csvhas 36. - Add an upper limit for
quantity(thresholds.max_quantityis 50 indata/config.json). Indata/sales_raw.csv, the 2 accepted rows with absurd quantities (500 and 1,000) then count as invalid too. - Add a coverage gate with
pytest-cov(module 14) at 95%.
Next steps
Section titled “Next steps”- Capstone 2 — Sales analysis answers business questions about the same data with pandas and charts.
- Review module 14 and module 22 if a milestone was hard.