Interview Prep/Python for DevOps/Testing, CI/CD, packaging & services

You need to test a function that calls `subprocess.run(["terraform", "plan"])`. How?

IntermediateScenarioTesting, CI/CD, packaging & services
Answer

Situation read → Do not run Terraform in unit tests.

What I'd do →

  1. Patch subprocess.run where it is used: monkeypatch.setattr(mymod.subprocess, "run", fake_run), returning a subprocess.CompletedProcess(args, 2, stdout=..., stderr="").
  2. Test parsing and decision logic for each return code (0 no changes, 2 changes with -detailed-exitcode, 1 error).
  3. Assert the exact arguments passed.
  4. A separate integration test can run real Terraform against a local backend.

Why → Unit tests check your logic; integration tests check the tool.

Interview tip → Mention -detailed-exitcode semantics.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, CI/CD, packaging & services