Logging, error handling & pytest
Add logging and tests so your automation fails loudly and predictably.
By Invicly Tech, , in Full DevOps with Python. About 12 minutes to read.
In short
Logging shows what your automation did, specific exceptions explain what went wrong, and pytest proves it works before it touches real servers. Mocks let you test code that calls commands or APIs.
Explained simply
When automation runs at 3 a.m. with nobody watching, it needs to leave a trail. Logging writes timestamped messages with a level (how serious each one is), so later you can see exactly what happened and where it stopped. print is fine while learning; logging is what real tools use.
Errors in Python are exceptions. When something goes wrong, code raises one, and the program stops unless some code catches it. Good scripts catch only the errors they know how to handle, and let surprises crash loudly with a clear message instead of carrying on in a broken state.
Tests are small pieces of code that run your code and check the result. pytest is the standard tool: write a function whose name starts with test_, use a plain assert, and run pytest. If the assert is false, pytest shows you the actual values.
Automation code talks to the outside world: it runs commands and calls APIs. In tests you replace those parts with fakes (mocks) that return prepared answers. Tests then run in milliseconds, never touch a real server, and still prove your logic is right.
Press Play on a diagram to walk through it one step at a time.
- 1Write a test
Describe expected behaviour with plain assert.
- 2Run pytest
See it fail for the right reason.
- 3Write the code
Smallest change that makes the test pass.
- 4Run again
All tests green, including old ones.
- 5Refactor safely
Tests catch anything you break.
- Back to step 1
- pytest to fixture: Call the fixture1Call the fixture
- fixture to pytest: Run setup, yield the value2Run setup, yield the value
- pytest to test: Run the test with that value3Run the test with that value
- test to pytest: Pass or fail4Pass or fail
- pytest to fixture: Resume after yield5Resume after yield
- fixture to pytest: Teardown finished6Teardown finished
- ConfigError
- Missing or invalid settings
- Raised from the original KeyError
- RemoteCommandError
- A command exited non-zero
- Stores returncode and stderr
- ApiError
- HTTP call failed after retries
- Stores the status code
- Anything else
- Real bugs like TypeError
- Crash with a full traceback
In depth
How the logging module is wired
logging has four parts. Loggers are what your code calls, created with logging.getLogger(__name__) so each module gets one named after it. Handlers decide where records go: the console, a file, syslog. Formatters decide how a line looks. Levels filter on both loggers and handlers.
Loggers form a tree by their dotted names: mytool.cli is a child of mytool, and everything is a child of the root logger. A record travels up the tree (propagation) to the handlers of its ancestors, so you usually configure handlers only on the root, once, at program start, with logging.basicConfig(level=logging.INFO, format=...).
basicConfig does nothing if the root logger already has handlers, which confuses people; pass force=True to replace them. Libraries should never call basicConfig; only the application decides where logs go. Without any configuration, only WARNING and above are shown.
- DEBUG 10, INFO 20, WARNING 30, ERROR 40, CRITICAL 50
- logger.info("copied %s files", n) builds the text only if it is logged
- logger.exception("msg") inside except also logs the traceback
- 1Logger level check
Dropped if below the logger's level
- 2Create record
Message, level, time, logger name
- 3Propagate up
mytool.cli, then mytool, then root
- 4Handler level check
Each handler filters again
- 5Formatter
Turns the record into a line of text
- 6Output
Console, file or syslog
Raising and catching exceptions well
Catch the narrowest exception you can handle: except FileNotFoundError, not except Exception, and never a bare except:, which also catches KeyboardInterrupt (Ctrl+C) and SystemExit. Keep the try block small so you know which line failed.
try has two lesser-known parts. else runs only if no exception happened, which keeps the happy path out of the try block. finally always runs, so it is a place for clean-up, though a with block is usually better.
When you turn a low-level error into a clearer one, chain it: raise ConfigError("db.host missing") from err. The traceback then shows both, so nothing is hidden. For a tool, define a small hierarchy, such as class ToolError(Exception) with subclasses, catch ToolError once in main(), log a one-line message and exit with code 1. Unexpected exceptions still crash with a full traceback, which is what you want for real bugs.
How pytest finds and runs tests
pytest collects files named test_*.py or *_test.py, then functions whose names start with test, and classes named Test... that have no __init__ method. It rewrites assert statements, so a failure shows both sides of the comparison and the values that led there. No special assertEqual methods are needed.
Useful flags: -x stops at the first failure, -k "disk and not slow" selects tests by name, -v lists each test, --lf reruns only the last failures, and -q keeps output short. pytest exits with code 0 when all tests pass and 1 when some fail, which CI uses to mark the build red.
Fixtures shared by many test files go in a conftest.py file, which pytest finds automatically without imports. Built-in fixtures cover a lot: tmp_path gives a fresh temporary folder, monkeypatch replaces attributes and environment variables, capsys captures printed output and caplog captures log records.
- pytest -x -q for a fast feedback loop
- with pytest.raises(ValueError, match="port"): checks the error and its message
- caplog.text contains every log line emitted during the test
Fixtures and parametrize in depth
A fixture is a function marked @pytest.fixture. Any test that names it as a parameter receives its value. If the fixture uses yield instead of return, the code after yield runs as teardown, even when the test failed. That is how you create a temporary config, a fake server or a database connection and clean up afterwards.
Fixtures have a scope. The default, function, builds a fresh one for every test. module, package and session reuse one object across many tests, which is faster for expensive setup but lets tests leak state into each other. Fixtures can depend on other fixtures.
@pytest.mark.parametrize("value,expected", [...]) runs one test once per row, and each row is reported as its own test with an id like test_parse[42-42]. Use pytest.param(..., id="empty") for readable names. Stacking two parametrize decorators runs every combination.
Mocking: patch where the name is looked up
unittest.mock.patch and pytest's monkeypatch replace an object for the duration of one test. The rule people trip on: patch the name where your code looks it up, not where it was defined. If deploy.py does from subprocess import run, deploy now has its own name run, and you must patch deploy.run. If it does import subprocess and calls subprocess.run, patch subprocess.run.
A MagicMock records every call, so you can check how your code used it: mock_run.assert_called_once_with(["systemctl", "restart", "app"], check=True). Set return_value for normal answers, and side_effect to raise an exception or return different values on successive calls.
For HTTP, the responses library intercepts requests calls at the transport level, so your real requests code runs against fake responses. Do not over-mock: a test that mocks everything only proves that the mocks agree with each other.
- deploy has its own name run
- Patch deploy.run
- Patching subprocess.run has no effect
- deploy calls subprocess.run
- Patch subprocess.run
- The name is looked up at call time
Learn it in 5 short steps
About 1h each. Track them with a timer in your plan.
- 1Configure the logging module and levels~1h
- 2Raise and catch specific exceptions~1h
- 3Write pytest tests with assertions~1h
- 4Use fixtures and parametrize~1h
- 5Mock subprocess and HTTP calls~1h
Key points
- Use logging levels: DEBUG for detail, INFO for progress, WARNING and ERROR for problems.
- Catch specific exceptions, not bare except, so real bugs are not hidden.
- Fixtures provide reusable setup; parametrize runs one test with many inputs.
- Mock subprocess and HTTP calls so tests are fast and never touch real systems.
Key terms
Tap a card to flip it. 0/5 known
Examples
import subprocess, pytest
def disk_usage(path):
out = subprocess.run(["du", "-s", path], capture_output=True, text=True, check=True)
return int(out.stdout.split()[0])
@pytest.mark.parametrize("stdout,expected", [("42\t/tmp", 42), ("0\t/x", 0)])
def test_disk_usage(monkeypatch, stdout, expected):
fake = subprocess.CompletedProcess([], 0, stdout=stdout)
monkeypatch.setattr(subprocess, "run", lambda *a, **k: fake)
assert disk_usage("/tmp") == expectedParametrized test with subprocess.run mocked out.
Test an API helper with the responses library
latest_tag() asks GitHub for a repo's latest release. Step 1: decorate the test with @responses.activate, so no real network call can happen. Step 2: register a fake 200 response with the JSON your code expects and check the result. Step 3: replace it with a 404 and check that the helper raises HTTPError instead of returning garbage. Install with pip install responses.
import pytest, requests, responses
URL = "https://api.github.com/repos/acme/api/releases/latest"
def latest_tag(repo):
r = requests.get(f"https://api.github.com/repos/{repo}/releases/latest", timeout=5)
r.raise_for_status()
return r.json()["tag_name"]
@responses.activate
def test_latest_tag_ok_and_missing():
responses.add(responses.GET, URL, json={"tag_name": "v1.4.0"})
assert latest_tag("acme/api") == "v1.4.0"
responses.replace(responses.GET, URL, status=404)
with pytest.raises(requests.HTTPError):
latest_tag("acme/api")Logging setup and one error boundary in main()
Step 1: each module gets a named logger. Step 2: main() configures logging once, with timestamps, and a -v flag switches to DEBUG. Step 3: known problems raise ToolError, which main() catches and logs as one clean line before returning exit code 1. Step 4: anything else is a bug and crashes with a full traceback. Run it and you see a single timestamped ERROR line and exit code 1.
import logging, sys
log = logging.getLogger("mytool")
class ToolError(Exception): pass
def sync_files():
raise ToolError("target folder /srv/data does not exist")
def main(verbose=False):
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
try:
sync_files()
except ToolError as e:
log.error("%s", e)
return 1
return 0
sys.exit(main("-v" in sys.argv))Quick reference
- log = logging.getLogger(__name__) in each module; configure handlers once in main
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
- logger.exception("msg") inside except logs the message plus the traceback
- raise NewError("clear message") from err keeps the original cause visible
- pytest -x -q --lf reruns the last failures and stops at the first one
- with pytest.raises(KeyError): asserts that the code raises the right error
- tmp_path, monkeypatch, capsys and caplog are built-in pytest fixtures
- After from subprocess import run, patch deploy.run, not subprocess.run
Common mistakes
- Using print instead of logging, so there are no levels or timestamps.
- A bare except: that swallows KeyboardInterrupt and real bugs alike.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write is_valid_port(p) that returns True only for integers 1 to 65535, and test it with parametrize using at least 5 cases, including 0, 65536 and the string "80".
- Exercise 2medium
Write read_config(path) that raises your own ConfigError (chained from the original error) if the file is missing. Test the happy path with tmp_path and the missing-file path with pytest.raises.
- Exercise 3hard
A module svc has restart_service(name), which runs systemctl restart, logs a warning containing "retrying" and retries once if the first call fails. Test it: make the fake subprocess.run fail first and succeed second, then check the call count and the log.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Does logging really matter for small scripts?
- As soon as a script runs unattended, yes. Logging gives timestamps and levels, can go to a file or the journal, and can be turned up to DEBUG without editing code.
- Where should I put my tests?
- In a tests/ folder next to your package, in files named test_*.py. Put shared fixtures in tests/conftest.py.
- Should I use unittest or pytest?
- pytest for new code: plain asserts, fixtures and better output. It also runs existing unittest-style tests, so you can switch gradually.
- Why do I not see my print output when tests run?
- pytest captures output and shows it only for failing tests. Run pytest -s to let it through, or use capsys to check it in the test.