──────────────────────────────────────

64. Maintain a Python Tool · Repair and Hand Over a Stock Report

Fix a bug in an existing CSV tool and show the test and Git evidence for the repair.

Lesson files · lessons/maintain-a-tool/stock-report-ticket

Before you start
- Read named CSV columns and total repeated items.
- Reproduce a bug on a small fixture and write a failing test.
- Read a Git diff and find a commit in the local history.

By the end
- Keep zero-quantity items in the report while retaining the ordinary totals.
- Capture the same regression test failing before the fix and passing after it.
- Use the local commit and a run on unfamiliar data to explain the repair.

Where you can use it
Repair a team’s stock report and leave the next maintainer a test, commit and command they can rerun.

A volunteer relies on the stock report to see what needs buying. Gloves are missing when they have zero units. Start with the reported CSV and use the workflow from the room report to isolate this ticket.

The supplied tool can read Studio input or a local CSV and print the same report. The workbook has the same starter as stock_report.py, a test file and two exports. Use README.txt to keep the original in a local Git commit, reproduce the problem, review your repair and share the result.

Predict
What should a volunteer see when the inventory records Gloves with zero units?
- A report that omits Gloves.
- A Gloves line with a count of zero.

Worked example (example.py)

stock = {"Hooks": 5, "Gloves": 0}
print("Gloves" in stock)
print(stock["Gloves"])


Example result
True
0

Repair the stock report described in the ticket. Read item and quantity by column name. Accept zero for a named item. Skip blank item names and total repeated names. Keep the output heading and alphabetical item lines.

Follow README.txt in the workbook folder. Run the new regression test before editing the stock tool and again after the fix. Review the diff and record the fix commit. Ask a partner to pick an unfamiliar export, predict its result and run the repaired script. Record the command and what happened.

Starter program (starter.py)

import argparse
import csv
import sys


def totals_from(stream):
    totals = {}
    for row in csv.DictReader(stream):
        item = row["item"].strip()
        quantity = int(row["quantity"])
        if item and quantity:
            totals[item] = totals.get(item, 0) + quantity
    return totals


def show_report(totals):
    print("Stock totals")
    for item in sorted(totals):
        print(f"{item}: {totals[item]}")


def main():
    parser = argparse.ArgumentParser(description="Summarise a stock export")
    parser.add_argument("source", nargs="?", help="CSV file to read. Omit it to read standard input.")
    options = parser.parse_args()
    if options.source:
        with open(options.source, encoding="utf-8", newline="") as stream:
            show_report(totals_from(stream))
    else:
        show_report(totals_from(sys.stdin))


if __name__ == "__main__":
    main()


Starter input
item,quantity
Hooks,3
Gloves,0
Hooks,2
,4


Hint
Start by comparing the row for Gloves with a row the report correctly includes. Use the smallest input that still shows the failure.

Case 1. Try the sample
Input
item,quantity
Hooks,3
Gloves,0
Hooks,2
,4

Expected output
Stock totals
Gloves: 0
Hooks: 5

Case 2. New export with the columns swapped
Input
quantity,item
1,"Field, Small"
0,Batteries
3,Boards
2,Boards
2, 

Expected output
Stock totals
Batteries: 0
Boards: 5
Field, Small: 1

Case 3. Header only
Input
item,quantity
Expected output
Stock totals

Project requirement
Reproduce the problem with a minimal fixture and record the report you expected.

Project requirement
Add a test to test_stock_report.py that fails for the original tool. Repair the report and show the full unittest suite passing.

Project requirement
Review both edited files with git diff, commit the repair locally and record its short ID.

Project requirement
Hand over the input filename, exact command, expected and observed results for an unfamiliar export.

Project checklist
I recorded a small input and the reported error.

Project checklist
I kept the regression test and saved its failing and passing results.

Project checklist
I reviewed and recorded the local fix commit.

Project checklist
I checked the report on an export I did not write.

Marking criterion
Report behaviour (4 points)
The report keeps named items with zero quantity, totals repeated items and handles the unfamiliar export.

Marking criterion
Regression evidence (3 points)
The learner shows the same focused test failing on the original code and passing after the repair.

Marking criterion
Git review (2 points)
The diff and commit show the focused change and its test.

Marking criterion
Handover (1 points)
A partner can rerun the repaired tool on the unfamiliar export using the recorded command.

Stretch
Ask your partner which command or part of the diff was hardest to follow. Rewrite one line in your handover notes and have them rerun that step.

The ZIP includes added practice files for this lesson. Open its lesson folder and read the included instructions.

Reflect
Which test result and line in the diff show why the report can now show zero stock?

Check your prediction
A Gloves line with a count of zero. The zero is a recorded amount the volunteer uses to decide what to restock.
