04 / REUSABLE NETWORK AUDITS · LESSON 16

Publish coverage as well as findings

Write stable CSV and JSON reports that retain unavailable devices in the totals.

15 min · learn at your pace

A clean finding list can hide a collection gap

An audit needs to say what was assessed and what was unavailable. This exercise receives already classified devices and writes a coverage report. Each requested device contributes to the total, including unavailable observations. Keep healthy, attention and unavailable counts separate.

Validate duplicate device identities and unexpected statuses before opening output files. Inputs here already contain normalized device labels and validated text fields, so the reporting function can focus on output behavior rather than repeating every collection rule.

Use format libraries and deterministic order

A site label or reason can contain commas, quotes, Unicode or line breaks. Use csv.DictWriter with UTF-8 and newline="" so consumers can parse those values correctly. Do not construct CSV by joining strings with commas.

Sort rows by device and select only the documented columns. Extra internal fields should not appear accidentally when another function adds metadata. Build summary counts directly from the same rows used in the coverage report.

Successful reruns replace previous files, including when the input is empty. An empty run writes headers and zero counts, not yesterday's rows. Avoid reading the wall clock for this report: the caller's evidence and stable ordering should determine its output. The capstone will use these habits to combine several forms of network evidence into one reproducible assessment.

Try an example.py
import csv, io
output = io.StringIO(newline="")
writer = csv.DictWriter(output, fieldnames=["device","site"])
writer.writeheader()
writer.writerow({"device":"edge-a","site":"Sydney, Operations"})
print(output.getvalue())
YOUR TURN

Put it into practice.

Define write_audit_report(rows, output). Rows have normalized unique device, site, status and reason. Allowed statuses are healthy, attention, unavailable; duplicates/invalid statuses raise ValueError before writes. Create output as needed. Write coverage.csv columns device, site, status, reason sorted by device and summary.json containing integer devices, healthy, attention, unavailable counts including zeros. Ignore extra fields, preserve inputs and use UTF-8 CSV escaping. Return the summary. Successful reruns replace output; empty input writes the header and zero counts.

See an explained solution
One way to solve it.py
import csv,json
from pathlib import Path

def write_audit_report(rows, output):
    statuses = ("healthy","attention","unavailable")
    seen = set()
    for row in rows:
        if row["device"] in seen or row["status"] not in statuses:
            raise ValueError("Invalid or duplicate device assessment")
        seen.add(row["device"])
    summary = {"devices":len(rows),**{status:sum(row["status"] == status for row in rows) for status in statuses}}
    destination = Path(output)
    destination.mkdir(parents=True,exist_ok=True)
    with (destination/"coverage.csv").open("w",encoding="utf-8",newline="") as handle:
        writer=csv.DictWriter(handle,fieldnames=["device","site","status","reason"])
        writer.writeheader()
        writer.writerows({key:row[key] for key in writer.fieldnames} for row in sorted(rows,key=lambda row:row["device"]))
    (destination/"summary.json").write_text(json.dumps(summary,sort_keys=True,ensure_ascii=False)+"\n",encoding="utf-8")
    return summary

if __name__ == "__main__":
    print(write_audit_report([{"device":"edge-a","site":"Sydney","status":"unavailable","reason":"missing export"}], "report"))

The report makes coverage limits visible and keeps its summary consistent with the rows. Stable encoding and replacement allow meaningful comparisons between runs.