Testing your automation code with pytest: templates, data validation and functions
In short: Automation code needs tests just like any other software. With pytest, you write small functions that check your templates produce the right configuration and your variable files contain valid VLANs, IP addresses and names. Tests run in seconds on a laptop or in a pipeline and catch many mistakes before anything reaches a device.
Why test automation code?
A template change that drops a line, a YAML file with VLAN 4097, or a subnet typed as 10.1.300.0/24 can all break the network when deployed. Unit tests catch these quickly and cheaply.
Getting started
Install with pip install pytest. Create files named test_*.py containing functions named test_*, and run pytest in the project folder.
Validating data
import ipaddress
import yaml
import pytest
with open("vars/vlans.yml") as f:
VLANS = yaml.safe_load(f)["vlans"]
@pytest.mark.parametrize("vlan", VLANS)
def test_vlan_id_in_range(vlan):
assert 1 <= vlan["id"] <= 4094
@pytest.mark.parametrize("vlan", VLANS)
def test_vlan_subnet_is_valid(vlan):
ipaddress.ip_network(vlan["subnet"]) # raises ValueError if invalid
def test_vlan_ids_unique():
ids = [v["id"] for v in VLANS]
assert len(ids) == len(set(ids))
Parametrisation runs a test once per VLAN and reports exactly which entry failed.
Testing templates
from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader("templates"))
def test_access_port_template():
tpl = env.get_template("access_port.j2")
out = tpl.render(interface="Gi1/0/5", vlan=120, description="Printer")
assert "interface Gi1/0/5" in out
assert "switchport access vlan 120" in out
assert "spanning-tree portfast" in out
Testing functions
Keep logic in small functions (for example "choose the next free port" or "build a hostname") so it can be tested without devices. Use pytest fixtures to share sample data between tests.
In a pipeline
Run pytest automatically on every pull request. A failing test blocks the merge until it is fixed. Add more tests whenever a bug is found, so it cannot return.
Real-world example: the duplicate VLAN
Two engineers added different VLANs with the same ID to a site's variable file in separate pull requests. The uniqueness test failed on the second one, and the clash was fixed in review instead of causing a broken network segment during the next deployment.
Practice
How does pytest find tests?
What does parametrisation do in pytest?
How can you test a Jinja2 template?
Key takeaways
- Automation code needs automated tests.
- Validate variables such as VLAN IDs, subnets and unique names.
- Render templates with sample data and check the output.
- Run tests in pipelines and add tests for every bug found.
Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.