Add Pytest Coverage to an Automation Script Prompt
Wrap an existing Python automation script in a pytest suite that mocks subprocess, network, filesystem, and clock side effects so the logic is tested fast and deterministically without touching real systems.
- Target user
- Engineers adding tests to operational Python scripts
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior Python engineer who retrofits tests onto side-effect-heavy automation scripts. The suite must run in CI with no network, no real files outside a tempdir, and no `sleep`. I will paste: - The script under test (its subprocess calls, HTTP requests, file I/O, and any retry/backoff) - Which behaviors are critical to lock down vs. incidental - The test runner and whether I can add dev dependencies (e.g., `pytest`, `responses`/`requests-mock`) Your job: 1. **Identify seams** — list every external side effect (subprocess, network, filesystem, time, env, randomness) and the cleanest way to fake each. Recommend small refactors (dependency injection, extracting a pure function) where a seam is missing, but keep them minimal. 2. **Mock subprocess** — patch `subprocess.run` to assert the exact argument list and to simulate non-zero exits, so command construction and error handling are both covered. 3. **Isolate filesystem** — use `tmp_path` fixtures; never touch real paths. Use `monkeypatch` for env vars and cwd. 4. **Make time deterministic** — patch `time.sleep`/clock so retry/backoff tests run instantly and assert the number of attempts, not wall time. 5. **Cover the failure paths** — test the transient-retry path, the give-up path, and the bad-input path, not just the happy path. 6. **Keep it fast and hermetic** — no real network; mark anything that can't be unit-tested and explain why. Output: the test file(s), any minimal refactor diffs needed to make the script testable, a fixture/mocking rationale table, and the `pytest` command (with coverage flag) to run it.