I've written about Pytest a couple of times before. The first post covered what pytest is, and the second one looked at using it for automated network checks. Both were fairly long posts, so I thought I would write a quick one focusing on a specific use case.
Let's say you are upgrading your EVPN fabric across spine and leaf switches. It could be tens or even hundreds of switches. Once they are upgraded, you need to do some minimum checks, such as whether all the BGP peers are up on the underlay and overlay, what the EVPN routes look like, checking ARP and MAC address tables, and so on. Of course, doing this by hand would be crazy and time-consuming. So how can we automate this? There are multiple ways to do it, but in this post, we will use Python and pytest.
Lab Topology
For this example, I'm using a small EVPN fabric with two spines and three leaf switches running Junos. Both spines are in AS 65000, and each leaf has its own AS number. The IP addresses shown next to each switch are their loopbacks.

arista1 is dual-homed to leaf1 and leaf2 using EVPN multihoming (ESI LAG), and host6 sits behind it. host4 is connected directly to leaf3. Both hosts are in the same subnet, so traffic between them is bridged across the fabric over VXLAN. But honestly, the focus of this post is to teach pytest so, even if you have no idea about eVPN/VXLAN, you can still follow along and the idea can be applied to any network element.
Installation and Setup
I've created a directory called juniper_pytest for this project. I'm using uv to manage the project and install the packages, but you can use pip if you prefer. If you are not familiar with uv, I have another post that covers it, so feel free to check it out.
First, I initialised the project with Python 3.12.
uv init --python 3.12
Next, I installed junos-eznc (PyEZ) to connect to the Juniper devices, and pytest to run the tests.
uv add junos-eznc
uv add pytest
If you are using pip, you can install both packages with the following command.
pip install junos-eznc pytest
If you are not familiar with Juniper PyEZ, I have a dedicated post that covers it in detail, so feel free to check it out.
A Simple Test
Let's start with a simple test that checks whether all the BGP peers are up on each device. We'll keep it basic for now and improve it as we go. Create a file called test_bgp.py and add the following code.
#test_bgp.py
from jnpr.junos import Device
devices = {
"spine1": "192.168.204.101",
"spine2": "192.168.204.102",
"leaf1": "192.168.204.111",
"leaf2": "192.168.204.112",
"leaf3": "192.168.204.113",
}
username = "admin"
password = "admin@123"
def get_bgp_peers(device):
bgp = device.rpc.get_bgp_summary_information()
peers = {}
for peer in bgp.findall(".//bgp-peer"):
address = peer.findtext("peer-address")
state = peer.findtext("peer-state")
peers[address] = state
return peers
def test_bgp_peers_established():
for name, host in devices.items():
with Device(host=host, user=username, passwd=password) as device:
peers = get_bgp_peers(device)
assert peers, f"{name}: no BGP peers found"
down = [
address for address, state in peers.items() if state != "Established"
]
assert not down, f"{name}: peers not established: {down}"
Just a quick note before we move on. I'm storing the username and password directly in the script to keep things simple for this example. In production, you should never do this. Use environment variables, a secrets manager or prompt for the password at runtime instead.
At the top, I have a dictionary of devices with their names and management IPs, along with the username and password. Then, I’m using PyEZ to connect to the Juniper devices over NETCONF. If you are not familiar with PyEZ, I have a dedicated post on it, so feel free to check it out.
The get_bgp_peers() function takes a device connection and runs the get_bgp_summary_information RPC, which is the same as running show bgp summary on the CLI. The reply comes back as XML, so we use findall(".//bgp-peer") to grab every BGP peer in the output. For each peer, we pull out the peer address and its state, and store them in a dictionary. The result looks something like {"10.0.0.11": "Established", "172.16.1.0": "Established"}.
Here is a trimmed version of the XML output from spine1, so you can see what we are working with.
<bgp-information>
<group-count>2</group-count>
<peer-count>6</peer-count>
<down-peer-count>0</down-peer-count>
<bgp-peer style="terse">
<peer-address>10.0.0.11</peer-address>
<peer-as>65011</peer-as>
<flap-count>4</flap-count>
<elapsed-time seconds="7384">2:03:04</elapsed-time>
<peer-state format="Establ">Established</peer-state>
<bgp-rib style="terse">
<name>bgp.evpn.0</name>
<active-prefix-count>6</active-prefix-count>
<received-prefix-count>6</received-prefix-count>
<accepted-prefix-count>6</accepted-prefix-count>
<suppressed-prefix-count>0</suppressed-prefix-count>
</bgp-rib>
</bgp-peer>
<bgp-peer style="terse">
<peer-address>172.16.1.0</peer-address>
<peer-as>65011</peer-as>
<flap-count>4</flap-count>
<elapsed-time seconds="7412">2:03:32</elapsed-time>
<description>leaf1</description>
<peer-state format="Establ">Established</peer-state>
<bgp-rib style="terse">
<name>inet.0</name>
<active-prefix-count>1</active-prefix-count>
<received-prefix-count>1</received-prefix-count>
<accepted-prefix-count>1</accepted-prefix-count>
<suppressed-prefix-count>0</suppressed-prefix-count>
</bgp-rib>
</bgp-peer>
...
</bgp-information>
Each <bgp-peer> block represents one BGP neighbour. The two values we care about are <peer-address> and <peer-state>.
The test itself is test_bgp_peers_established(). pytest picks up any function that starts with test_, so we don't need to do anything special to register it. Inside the test, we loop through each device, connect to it and get its BGP peers. Using with Device(...) means the connection is opened and closed automatically, so we don't have to worry about calling open() and close() ourselves.
Then we have two checks. The first one makes sure we actually got some peers back. If the list is empty, something is wrong, and the test should fail. The second one builds a list of any peers that are not in the Established state. If that list is not empty, the test fails and shows the device name along with the peers that are down.
Running the Test
To run the test, I use the following command. -v gives us a more verbose output, and --tb=no hides the traceback so the output stays short.
pytest -v --tb=no
==================== test session starts ====================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 1 item
test_bgp.py::test_bgp_peers_established PASSED [100%]
===================== 1 passed in 2.91s =====================
All the BGP peers are up on every device, so the test passes.
To simulate a failure, I shut down the link between spine1 and leaf1. This brings down both the underlay and overlay BGP sessions between the two switches. Running the test again, we can see it fails.
pytest -v --tb=no
==================== test session starts ====================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 1 item
test_bgp.py::test_bgp_peers_established FAILED [100%]
================== short test summary info ==================
FAILED test_bgp.py::test_bgp_peers_established - AssertionError:
spine1: peers not established: ['10.0.0.11', '172.16.1.0']
===================== 1 failed in 0.68s =====================
The failure message tells us which device has the problem and which peers are down. Here, spine1 can't reach 10.0.0.11 (leaf1's loopback for the overlay) and 172.16.1.0 (leaf1's underlay interface).
But there is a problem with this approach. If you look closely, leaf1 also has BGP peers down, yet the test output doesn't mention it at all. This is because the test stops at the first failed assert. The loop goes through the devices in order, and as soon as spine1 fails, pytest exits the test. spine2, leaf1, leaf2 and leaf3 are never checked.
The other issue is that we only get one result for all five devices. Whether one device fails or all of them fail, we still see a single FAILED. So, in the next section, we'll fix both of these using parametrization.
Using Parametrization
To fix these problems, we need to make a few changes to the code. The get_bgp_peers() function stays the same, but the way we connect to the devices and the test itself are a bit different.
# test_bgp.py
import pytest
from jnpr.junos import Device
devices = {
"spine1": "192.168.204.101",
"spine2": "192.168.204.102",
"leaf1": "192.168.204.111",
"leaf2": "192.168.204.112",
"leaf3": "192.168.204.113",
}
username = "admin"
password = "admin@123"
def get_bgp_peers(device):
bgp = device.rpc.get_bgp_summary_information()
peers = {}
for peer in bgp.findall(".//bgp-peer"):
address = peer.findtext("peer-address")
state = peer.findtext("peer-state")
peers[address] = state
return peers
@pytest.fixture(params=devices.keys(), scope="module")
def device(request):
connection = Device(
host=devices[request.param],
user=username,
passwd=password,
)
connection.open()
yield connection
connection.close()
def test_bgp_peers_established(device):
peers = get_bgp_peers(device)
assert peers, f"{device.hostname}: no BGP peers found"
down = [
address for address, state in peers.items() if state != "Established"
]
assert not down, f"{device.hostname}: peers not established: {down}"
Parametrization in pytest lets you run the same test multiple times with different inputs. Instead of looping through the devices inside the test, we let pytest do it for us. Each device becomes its own test, with its own pass or fail result. If one device fails, pytest simply moves on to the next one. There are a couple of ways to do this in pytest, and here we'll parametrize the fixture, so every test that uses it runs once per device.
The first change is the new device() function, which is a pytest fixture. A fixture is a function that prepares something your test needs. In this case, it's the connection to the device. You mark a function as a fixture using the @pytest.fixture decorator.
The params=devices.keys() part is where the parametrization happens. It tells pytest to run the fixture once for each item in the list, which are spine1, spine2, leaf1, leaf2 and leaf3.
request is a built-in pytest object that you can add as an argument to any fixture. It gives the fixture information about the test that's currently using it. When a fixture has params, request.param holds the value for the current run. So on the first run, request.param is spine1, on the second run it's spine2, and so on until all five devices are done. That's why devices[request.param] gives us the IP address of the current device.
The fixture opens the connection, and yield connection hands it over to the test. Once the test finishes, whether it passes or fails, pytest comes back to the fixture and runs connection.close(). So everything before yield is the setup, and everything after it is the teardown. scope="module" means each connection is created once and reused by every test in the file, rather than reconnecting for each test.
The test itself is now simpler. We don’t have a loop anymore. We just add device as an argument, and pytest automatically passes in the connection from the fixture with the same name. The two checks are the same as before. The only difference is that we use device.hostname in the failure message, which is the IP address we connected to. hostname is an attribute of the PyEZ Device object. When you create the connection with Device(host=devices[request.param], ...), PyEZ stores the value you passed to host in device.hostname. That's why it shows the IP address, such as 192.168.204.101, rather than the switch name.
Let's run the test again with the same link still shut down.
pytest -v --tb=no test_bgp.py
==================== test session starts ====================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 5 items
test_bgp.py::test_bgp_peers_established[spine1] FAILED [ 20%]
test_bgp.py::test_bgp_peers_established[spine2] PASSED [ 40%]
test_bgp.py::test_bgp_peers_established[leaf1] FAILED [ 60%]
test_bgp.py::test_bgp_peers_established[leaf2] PASSED [ 80%]
test_bgp.py::test_bgp_peers_established[leaf3] PASSED [100%]
================== short test summary info ==================
FAILED test_bgp.py::test_bgp_peers_established[spine1] -
AssertionError: 192.168.204.101: peers not established:
['10.0.0.11', '172.16.1.0']
FAILED test_bgp.py::test_bgp_peers_established[leaf1] -
AssertionError: 192.168.204.111: peers not established:
['10.0.0.1', '172.16.1.1']
================ 2 failed, 3 passed in 2.83s ================
This time, we get five separate results, one for each device. Both spine1 and leaf1 are reported as failed, along with the peers that are down on each side, while the other three devices pass.
One small thing I didn't like is that the failure message shows the IP address of the device rather than its name. device.hostname is just the value we passed to host when creating the connection. The device name is already available in the fixture as request.param, so I changed the fixture to yield both the name and the connection. The test then unpacks them in the first line and uses the name in the failure messages.
@pytest.fixture(params=devices.keys(), scope="module")
def device(request):
name = request.param
connection = Device(
host=devices[name],
user=username,
passwd=password,
)
connection.open()
yield name, connection
connection.close()
def test_bgp_peers_established(device):
name, connection = device
peers = get_bgp_peers(connection)
assert peers, f"{name}: no BGP peers found"
down = [
address for address, state in peers.items() if state != "Established"
]
assert not down, f"{name}: peers not established: {down}"
Running the test again, the failure messages now show the device names.
pytest -v --tb=no test_bgp.py
==================== test session starts ====================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 5 items
test_bgp.py::test_bgp_peers_established[spine1] FAILED [ 20%]
test_bgp.py::test_bgp_peers_established[spine2] PASSED [ 40%]
test_bgp.py::test_bgp_peers_established[leaf1] FAILED [ 60%]
test_bgp.py::test_bgp_peers_established[leaf2] PASSED [ 80%]
test_bgp.py::test_bgp_peers_established[leaf3] PASSED [100%]
================== short test summary info ==================
FAILED test_bgp.py::test_bgp_peers_established[spine1] -
AssertionError: spine1: peers not established:
['10.0.0.11', '172.16.1.0']
FAILED test_bgp.py::test_bgp_peers_established[leaf1] -
AssertionError: leaf1: peers not established:
['10.0.0.1', '172.16.1.1']
================ 2 failed, 3 passed in 2.77s ================
Of course, if all the BGP peers are up, every device passes.
pytest -v --tb=no test_bgp.py
==================== test session starts ====================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 5 items
test_bgp.py::test_bgp_peers_established[spine1] PASSED [ 20%]
test_bgp.py::test_bgp_peers_established[spine2] PASSED [ 40%]
test_bgp.py::test_bgp_peers_established[leaf1] PASSED [ 60%]
test_bgp.py::test_bgp_peers_established[leaf2] PASSED [ 80%]
test_bgp.py::test_bgp_peers_established[leaf3] PASSED [100%]
===================== 5 passed in 2.80s =====================
Using @pytest.mark.parametrize
What we've used so far is a parametrized fixture. The more common way you'll see in most examples is @pytest.mark.parametrize, which you put directly on the test function. We can get the same results with it. The get_bgp_peers() function stays the same, and we no longer need the fixture.
# test_bgp.py
import pytest
from jnpr.junos import Device
devices = {
"spine1": "192.168.204.101",
"spine2": "192.168.204.102",
"leaf1": "192.168.204.111",
"leaf2": "192.168.204.112",
"leaf3": "192.168.204.113",
}
username = "admin"
password = "admin@123"
def get_bgp_peers(device):
bgp = device.rpc.get_bgp_summary_information()
peers = {}
for peer in bgp.findall(".//bgp-peer"):
address = peer.findtext("peer-address")
state = peer.findtext("peer-state")
peers[address] = state
return peers
@pytest.mark.parametrize("name", devices.keys())
def test_bgp_peers_established(name):
with Device(host=devices[name], user=username, passwd=password) as device:
peers = get_bgp_peers(device)
assert peers, f"{name}: no BGP peers found"
down = [
address for address, state in peers.items() if state != "Established"
]
assert not down, f"{name}: peers not established: {down}"
@pytest.mark.parametrize("name", devices.keys()) tells pytest to run the test once for each device, passing the current device name in as the name argument. Since we have the name directly, we can use it in the failure messages without any extra work. Running the test with the same link shut down gives us the same output as before.
pytest -v --tb=no test_bgp.py
==================== test session starts ====================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 5 items
test_bgp.py::test_bgp_peers_established[spine1] FAILED [ 20%]
test_bgp.py::test_bgp_peers_established[spine2] PASSED [ 40%]
test_bgp.py::test_bgp_peers_established[leaf1] FAILED [ 60%]
test_bgp.py::test_bgp_peers_established[leaf2] PASSED [ 80%]
test_bgp.py::test_bgp_peers_established[leaf3] PASSED [100%]
================== short test summary info ==================
FAILED test_bgp.py::test_bgp_peers_established[spine1] -
AssertionError: spine1: peers not established:
['10.0.0.11', '172.16.1.0']
FAILED test_bgp.py::test_bgp_peers_established[leaf1] -
AssertionError: leaf1: peers not established:
['10.0.0.1', '172.16.1.1']
================ 2 failed, 3 passed in 2.79s ================
So which one should you use? The difference is where the connection happens. With @pytest.mark.parametrize, the connection is inside the test. That's fine for a single test, but as you add more tests, such as EVPN or MAC address checks, each one needs its own with Device(...) block and opens a new connection to every device. With the parametrized fixture, the connection code lives in one place, and thanks to scope="module", all the tests in the file share the same connection to each device. For this post, I'll stick with the fixture.
Checking EVPN ARP Entries
Let's add another check. In my lab, host4 (10.10.1.14) is connected to leaf3, and host6 (10.10.1.16) sits behind arista1, which is dual-homed to leaf1 and leaf2. If EVPN is working, every leaf should learn the ARP entries for both hosts, either locally or from the other leaves through EVPN. So, on each leaf, check that both host IPs are present in the EVPN ARP table.
On the CLI, you can see the entries with show ethernet-switching evpn arp-table.
admin@leaf1> show ethernet-switching evpn arp-table
INET MAC Logical Routing Bridging
address address interface instance domain
10.10.1.16 aa:c1:ab:3e:78:0e ae0.0 default-switch V10
10.10.1.14 aa:c1:ab:5d:fb:10 vtep.32770 default-switch V10
On leaf1, 10.10.1.16 is learned locally on ae0.0, which is the link towards arista1. 10.10.1.14 is learned over the vtep interface, which means it came from a remote leaf through EVPN.
To use this in PyEZ, we need the RPC name for the command. You can get it by adding | display xml rpc to the end of any show command.
admin@leaf1> show ethernet-switching evpn arp-table | display xml rpc
<rpc>
<get-ethernet-switching-evpn-arp-table>
</get-ethernet-switching-evpn-arp-table>
</rpc>
In PyEZ, you replace the hyphens with underscores, so the RPC becomes get_ethernet_switching_evpn_arp_table(). To see what the XML reply looks like, use | display xml. Here is a trimmed version showing one entry.
<l2ng-l2rtb-evpn-arp-db>
<l2ng-l2rtb-evpn-arp-entry junos:style="brief">
<l2ng-l2-evpn-arp-inet-address>10.10.1.14</l2ng-l2-evpn-arp-inet-address>
<l2ng-l2-mac-address>aa:c1:ab:5d:fb:10</l2ng-l2-mac-address>
<l2ng-l2-mac-routing-instance>default-switch</l2ng-l2-mac-routing-instance>
<l2ng-l2-mac-bridging-domain>V10</l2ng-l2-mac-bridging-domain>
<l2ng-l2-mac-logical-interface>vtep.32770</l2ng-l2-mac-logical-interface>
<l2ng-l2-active-source>10.0.0.13</l2ng-l2-active-source>
</l2ng-l2rtb-evpn-arp-entry>
</l2ng-l2rtb-evpn-arp-db>
Each <l2ng-l2rtb-evpn-arp-entry> block is one ARP entry, and the values we need are the IP and MAC addresses. Before adding the new test, I also renamed the file to test_fabric.py, as it now covers more than just BGP.
# test_fabric.py
import pytest
from jnpr.junos import Device
devices = {
"spine1": "192.168.204.101",
"spine2": "192.168.204.102",
"leaf1": "192.168.204.111",
"leaf2": "192.168.204.112",
"leaf3": "192.168.204.113",
}
hosts = ["10.10.1.14", "10.10.1.16"]
username = "admin"
password = "admin@123"
def connect(name):
return Device(host=devices[name], user=username, passwd=password)
def get_bgp_peers(device):
bgp = device.rpc.get_bgp_summary_information()
peers = {}
for peer in bgp.findall(".//bgp-peer"):
address = peer.findtext("peer-address")
state = peer.findtext("peer-state")
peers[address] = state
return peers
def get_evpn_arp_entries(device):
arp = device.rpc.get_ethernet_switching_evpn_arp_table()
entries = {}
for entry in arp.findall(".//l2ng-l2rtb-evpn-arp-entry"):
ip = entry.findtext("l2ng-l2-evpn-arp-inet-address")
mac = entry.findtext("l2ng-l2-mac-address")
entries[ip] = mac
return entries
@pytest.fixture(params=devices.keys(), scope="module")
def device(request):
name = request.param
connection = connect(name)
connection.open()
yield name, connection
connection.close()
@pytest.fixture(
params=[name for name in devices if name.startswith("leaf")],
scope="module",
)
def leaf(request):
name = request.param
connection = connect(name)
connection.open()
yield name, connection
connection.close()
def test_bgp_peers_established(device):
name, connection = device
peers = get_bgp_peers(connection)
assert peers, f"{name}: no BGP peers found"
down = [
address for address, state in peers.items() if state != "Established"
]
assert not down, f"{name}: peers not established: {down}"
@pytest.mark.parametrize("ip", hosts)
def test_evpn_arp_present(leaf, ip):
name, connection = leaf
entries = get_evpn_arp_entries(connection)
assert ip in entries, f"{name}: no EVPN ARP entry for {ip}"
get_evpn_arp_entries() works the same way as get_bgp_peers(). It runs the RPC, finds every ARP entry and returns a dictionary of IP and MAC addresses.
The spines don't have these entries, so running this test against all five devices would fail on spine1 and spine2. That's why I added a separate leaf fixture, which only picks the devices whose names start with leaf. I also moved the Device() call into a small connect() function, so both fixtures can use it without repeating the same code.
The test uses both types of parametrization together. The leaf fixture runs once per leaf, and @pytest.mark.parametrize runs the test once per host IP. pytest combines the two, so we end up with 3 x 2 = 6 tests. The test itself just checks that the IP is in the ARP table.
pytest -v --tb=no test_fabric.py
======================== test session starts ========================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 11 items
test_fabric.py::test_bgp_peers_established[spine1] PASSED [ 9%]
test_fabric.py::test_bgp_peers_established[spine2] PASSED [ 18%]
test_fabric.py::test_bgp_peers_established[leaf1] PASSED [ 27%]
test_fabric.py::test_bgp_peers_established[leaf2] PASSED [ 36%]
test_fabric.py::test_bgp_peers_established[leaf3] PASSED [ 45%]
test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.14] PASSED [ 54%]
test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.16] PASSED [ 63%]
test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.14] PASSED [ 72%]
test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.16] PASSED [ 81%]
test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.14] PASSED [ 90%]
test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.16] PASSED [100%]
======================== 11 passed in 4.59s =========================
We now have 11 tests in total, five for BGP and six for the EVPN ARP entries, and all of them pass.
To simulate a failure, I stopped generating traffic from the hosts, so the leaves no longer have the entries in their EVPN ARP tables. Running the test again, all six ARP checks fail, while the BGP tests still pass.
pytest -v --tb=no test_fabric.py
======================== test session starts ========================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 11 items
test_fabric.py::test_bgp_peers_established[spine1] PASSED [ 9%]
test_fabric.py::test_bgp_peers_established[spine2] PASSED [ 18%]
test_fabric.py::test_bgp_peers_established[leaf1] PASSED [ 27%]
test_fabric.py::test_bgp_peers_established[leaf2] PASSED [ 36%]
test_fabric.py::test_bgp_peers_established[leaf3] PASSED [ 45%]
test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.14] FAILED [ 54%]
test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.16] FAILED [ 63%]
test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.14] FAILED [ 72%]
test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.16] FAILED [ 81%]
test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.14] FAILED [ 90%]
test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.16] FAILED [100%]
====================== short test summary info ======================
FAILED test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.14] -
AssertionError: leaf1: no EVPN ARP entry for 10.10.1.14
FAILED test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.16] -
AssertionError: leaf1: no EVPN ARP entry for 10.10.1.16
FAILED test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.14] -
AssertionError: leaf2: no EVPN ARP entry for 10.10.1.14
FAILED test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.16] -
AssertionError: leaf2: no EVPN ARP entry for 10.10.1.16
FAILED test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.14] -
AssertionError: leaf3: no EVPN ARP entry for 10.10.1.14
FAILED test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.16] -
AssertionError: leaf3: no EVPN ARP entry for 10.10.1.16
==================== 6 failed, 5 passed in 4.68s ====================
This is a good example of why checking BGP alone isn't enough. All the BGP sessions are up, but the leaves have no ARP entries for the hosts. Because each leaf and IP combination is its own test, we can see exactly which leaf is missing which entry.
How Many Times Are We Connecting?
Before we move on, let's look at how many times we connect to each device and how many RPC calls we make.
The spines are simple. They are only used by the device fixture, so each spine gets one connection and one RPC call for the BGP test.
The leaves are a bit different. The device and leaf fixtures are completely separate, so each leaf is connected twice, once by device for the BGP test and once by leaf for the ARP test. Because both fixtures use scope="module", each NETCONF session is opened the first time a test needs it and stays up until all the tests in the file have finished. Only then does pytest run connection.close().
But, how about the RPC calls. The BGP test makes one call per device. The ARP test runs twice per leaf, once for each host IP in the hosts list, and since get_evpn_arp_entries() is called inside the test, each run fetches the ARP table again. Both ARP calls go over the same open session, so there is no new connection, but we are still fetching the same table twice.
So for leaf1, it looks like this
- Connection 1 (from
device) is opened, used for the BGP RPC and stays up until the end. - Connection 2 (from
leaf) is opened, used for both ARP RPCs and stays up until the end.
In total, we make 8 connections (5 from device and 3 from leaf) and 11 RPC calls (5 for BGP and 6 for ARP). In a small lab like this, it doesn't really matter. But if you are checking tens or hundreds of switches after an upgrade, and adding more tests over time, it quickly adds up. Ideally, each device should be connected only once, and each table should be fetched only once per device.
Connecting Only Once
To fix this, we need to make sure each device is connected only once, and each table is fetched only once per device. Here is the updated code.
# test_fabric.py
import pytest
from jnpr.junos import Device
devices = {
"spine1": "192.168.204.101",
"spine2": "192.168.204.102",
"leaf1": "192.168.204.111",
"leaf2": "192.168.204.112",
"leaf3": "192.168.204.113",
}
hosts = ["10.10.1.14", "10.10.1.16"]
username = "admin"
password = "admin@123"
def get_bgp_peers(device):
bgp = device.rpc.get_bgp_summary_information()
peers = {}
for peer in bgp.findall(".//bgp-peer"):
address = peer.findtext("peer-address")
state = peer.findtext("peer-state")
peers[address] = state
return peers
def get_evpn_arp_entries(device):
arp = device.rpc.get_ethernet_switching_evpn_arp_table()
entries = {}
for entry in arp.findall(".//l2ng-l2rtb-evpn-arp-entry"):
ip = entry.findtext("l2ng-l2-evpn-arp-inet-address")
mac = entry.findtext("l2ng-l2-mac-address")
entries[ip] = mac
return entries
@pytest.fixture(scope="session")
def connections():
connections = {}
for name, host in devices.items():
connection = Device(host=host, user=username, passwd=password)
connection.open()
connections[name] = connection
yield connections
for connection in connections.values():
connection.close()
@pytest.fixture(params=devices.keys(), scope="module")
def device(request, connections):
name = request.param
return name, connections[name]
@pytest.fixture(
params=[name for name in devices if name.startswith("leaf")],
scope="module",
)
def leaf(request, connections):
name = request.param
return name, connections[name]
@pytest.fixture(scope="module")
def evpn_arp(leaf):
name, connection = leaf
return name, get_evpn_arp_entries(connection)
def test_bgp_peers_established(device):
name, connection = device
peers = get_bgp_peers(connection)
assert peers, f"{name}: no BGP peers found"
down = [
address for address, state in peers.items() if state != "Established"
]
assert not down, f"{name}: peers not established: {down}"
@pytest.mark.parametrize("ip", hosts)
def test_evpn_arp_present(evpn_arp, ip):
name, entries = evpn_arp
assert ip in entries, f"{name}: no EVPN ARP entry for {ip}"
The first change is the new connections fixture. It opens a connection to every device and stores them in a dictionary, using the device name as the key. It uses scope="session", which means it runs only once for the whole test run. Once all the tests are done, it closes every connection. This is now the only place where we connect to the devices.
The device and leaf fixtures no longer connect to anything. They take connections as an argument and simply pick the right connection by name. So when the BGP test and the ARP test both run against leaf1, they use the same session. Since we no longer create connections in two places, I also removed the connect() function.
The next change is the new evpn_arp fixture, which fetches the ARP table. It depends on the leaf fixture and uses scope="module", so pytest runs it once per leaf and reuses the result for both host IPs. The ARP test now takes evpn_arp instead of leaf, so it only checks the entries and doesn't talk to the device at all.
With these changes, we now make 5 connections (one per device) and 8 RPC calls (5 for BGP and 3 for ARP), down from 8 connections and 11 RPC calls. Running the test again with the same failure gives us the following output.
pytest -v --tb=no test_fabric.py
======================== test session starts ========================
cachedir: .pytest_cache
rootdir: /juniper_pytest
configfile: pyproject.toml
collected 11 items
test_fabric.py::test_bgp_peers_established[spine1] PASSED [ 9%]
test_fabric.py::test_bgp_peers_established[spine2] PASSED [ 18%]
test_fabric.py::test_bgp_peers_established[leaf1] PASSED [ 27%]
test_fabric.py::test_bgp_peers_established[leaf2] PASSED [ 36%]
test_fabric.py::test_bgp_peers_established[leaf3] PASSED [ 45%]
test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.14] FAILED [ 54%]
test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.16] FAILED [ 63%]
test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.14] FAILED [ 72%]
test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.16] FAILED [ 81%]
test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.14] FAILED [ 90%]
test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.16] FAILED [100%]
====================== short test summary info ======================
FAILED test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.14] -
AssertionError: leaf1: no EVPN ARP entry for 10.10.1.14
FAILED test_fabric.py::test_evpn_arp_present[leaf1-10.10.1.16] -
AssertionError: leaf1: no EVPN ARP entry for 10.10.1.16
FAILED test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.14] -
AssertionError: leaf2: no EVPN ARP entry for 10.10.1.14
FAILED test_fabric.py::test_evpn_arp_present[leaf2-10.10.1.16] -
AssertionError: leaf2: no EVPN ARP entry for 10.10.1.16
FAILED test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.14] -
AssertionError: leaf3: no EVPN ARP entry for 10.10.1.14
FAILED test_fabric.py::test_evpn_arp_present[leaf3-10.10.1.16] -
AssertionError: leaf3: no EVPN ARP entry for 10.10.1.16
==================== 6 failed, 5 passed in 2.34s ====================
The results are exactly the same as before, but the test now finishes in 2.34 seconds compared to 4.68 seconds earlier.
Splitting into Multiple Files
As we add more checks, keeping everything in one file gets harder to follow. The file now has the device details, the fixtures, the functions that talk to the devices and the tests all mixed together. So let's split them into separate files.
juniper_pytest/
├── conftest.py
├── helpers.py
├── test_bgp.py
├── test_evpn.py
└── pyproject.toml
conftest.py holds the device details and all the fixtures. pytest automatically loads this file before running any tests, so every test file can use the fixtures without importing them.
# conftest.py
import pytest
from jnpr.junos import Device
from helpers import get_evpn_arp_entries
devices = {
"spine1": "192.168.204.101",
"spine2": "192.168.204.102",
"leaf1": "192.168.204.111",
"leaf2": "192.168.204.112",
"leaf3": "192.168.204.113",
}
username = "admin"
password = "admin@123"
@pytest.fixture(scope="session")
def connections():
connections = {}
for name, host in devices.items():
connection = Device(host=host, user=username, passwd=password)
connection.open()
connections[name] = connection
yield connections
for connection in connections.values():
connection.close()
@pytest.fixture(params=devices.keys(), scope="module")
def device(request, connections):
name = request.param
return name, connections[name]
@pytest.fixture(
params=[name for name in devices if name.startswith("leaf")],
scope="module",
)
def leaf(request, connections):
name = request.param
return name, connections[name]
@pytest.fixture(scope="module")
def evpn_arp(leaf):
name, connection = leaf
return name, get_evpn_arp_entries(connection)
helpers.py holds the functions that send the RPCs to the devices and return the data as simple dictionaries. If you need to grab another field or the XML format changes, this is the only file you need to touch.
# helpers.py
def get_bgp_peers(device):
bgp = device.rpc.get_bgp_summary_information()
peers = {}
for peer in bgp.findall(".//bgp-peer"):
address = peer.findtext("peer-address")
state = peer.findtext("peer-state")
peers[address] = state
return peers
def get_evpn_arp_entries(device):
arp = device.rpc.get_ethernet_switching_evpn_arp_table()
entries = {}
for entry in arp.findall(".//l2ng-l2rtb-evpn-arp-entry"):
ip = entry.findtext("l2ng-l2-evpn-arp-inet-address")
mac = entry.findtext("l2ng-l2-mac-address")
entries[ip] = mac
return entries
The tests are now in their own files. test_bgp.py has the BGP test, and test_evpn.py has the ARP test along with the list of host IPs.
# test_bgp.py
from helpers import get_bgp_peers
def test_bgp_peers_established(device):
name, connection = device
peers = get_bgp_peers(connection)
assert peers, f"{name}: no BGP peers found"
down = [
address for address, state in peers.items() if state != "Established"
]
assert not down, f"{name}: peers not established: {down}"
# test_evpn.py
import pytest
hosts = ["10.10.1.14", "10.10.1.16"]
@pytest.mark.parametrize("ip", hosts)
def test_evpn_arp_present(evpn_arp, ip):
name, entries = evpn_arp
assert ip in entries, f"{name}: no EVPN ARP entry for {ip}"
Because the connections fixture uses scope="session", it's shared across both test files. So even with the tests split up, each device is still connected only once. To run everything, you just run pytest -v --tb=no without a file name, and pytest picks up every file that starts with test_. If you only want to run one area, you can pass the file name, for example pytest -v --tb=no test_evpn.py.
