Free tech learning for everyone, from basics to pro

Network AutomationNetworking SecurityIntermediate

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.

Testing levels for automation codeUnit testsfunctions, templatesIntegrationagainst a labNetwork testsstate after changePipelineruns all automatically
Figure 1. Fast unit tests catch most mistakes before any device is touched.

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?
It runs functions named test_* in files named test_*.py.
What does parametrisation do in pytest?
Runs the same test once for each item in a list, reporting each result separately.
How can you test a Jinja2 template?
Render it with sample variables and assert the expected configuration lines are present.

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.
Tracks your learning on this device only. See your progress on the learning paths.
Verified author✓ Valid
Issued to
Mohamed Fayas
Role
Founder of FM TecHub
Credentials
CCNABTEC HND Network EngineeringBEng (Hons) Computer Networking & Cloud Security
Issuer
FM TecHub · fmtechub.com

He writes practical, plain-English guides on networking, security and cloud.

More about the author →

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.

Email updates: coming soon

New notes, tools and security news from FM TecHub by email, explained simply. Free. We're not collecting email addresses yet; see our privacy policy.

PortServiceStatus
SMTP/25Email updatesopening soon

Meanwhile, stay connected: