CertGrid CertGrid
Hands-on Lab·Python Automation for IT

Mocking subprocess and HTTP in Python

Half of an automation script is calls you cannot make in a test - a subprocess, an API, a host that may be down. monkeypatch and unittest.mock.patch replace them, and both have one rule that catches everybody: you patch the name where it is looked up, not where it is defined. This guide gets that wrong on purpose and measures the difference, then shows the mock that passes a test with a typo in it.

Remote Hosts and CI/CD Guide 36 of 39 Advanced

unittest.mock is standard library. call_args.args and call_args.kwargs need Python 3.8; before that it was tuple indexing. Mock(spec=...) and autospec=True are the two things that make a mock refuse a typo.

Everything on this page runs on the control node. Any machine with Python 3 will do.
Server NameIP AddressOSRolesCPURAMHDD
RUNNER01192.168.0.27Ubuntu 26.04 LTSControl node - every script in this path runs here2 Core4 GB50 GB

This guide includes

Use this because half of an automation script is calls you cannot make in a test. This matters because a Mock answers anything you ask it - so the mock that lies passes a test the real code would fail.

Before you start

  1. The code that touches the outside world

  2. monkeypatch, for the environment

  3. A fake subprocess.run

  4. The target that looks right and is not

  5. A fake HTTP call

  6. The mock that lies

  7. A fake that is not a mock at all

  8. And the test that needs no mock at all

Official sources