task 3.1 · chapter 3 of 8: loops, conditionals and functions · 25 min
Which interfaces are down?
objective
Write two functions that loop over a list of interfaces: one returns the names of those that aren’t working, the other counts how many have each status.
netlab/interfaces.pyopen a file in VS Code: Ctrl+P (Cmd+P on a Mac), type its name, Enter
| The data | a list of dicts like the ones interfaces_to_dicts() makes in task 2.2 |
|---|---|
| Your functions | netlab/interfaces.py: down_interfaces() at TODO 3.1a, count_by_status() at TODO 3.1b |
| Working means | status up and protocol up |
new to this? step by stepbeginner
- In netlab/interfaces.py, write
down_interfaces()underTODO 3.1a: the code is in step 2 of the follow-along. python, then try it on r1’s interfaces (step 3).- Challenge:
count_by_status()underTODO 3.1b, a dict of each status and how many interfaces have it. make check T=3.1.
more in meet the lab
A loop, a question, an answer
The shape of both functions
Both functions in this task follow the same pattern: start with an empty result, loop over the interfaces,
decide something about each one with if, and return the result when the loop is done.
result = [] # or {} for a dict
for i in interfaces:
if ...: # a question about this one interface
... # add to the result
return result
The function takes its data as a parameter and gives its answer back with return. It doesn’t print,
log in to anything, or read a file. That’s why the check can call it on interface lists it made up a moment
before, and know the right answer.
in one sentence Empty result, loop, if, add, return: most functions in this lab start out like that.
What down means
show ip interface brief has two state columns: Status, the interface itself, and Protocol, the line
protocol running on it. An interface is working only when both are up. It isn’t working when:
| Status | Protocol | Means |
|---|---|---|
down | down | nothing at the other end, or a fault |
administratively down | down | someone configured shutdown |
up | down | the interface is up but the protocol isn’t: a mismatch, or no keepalives |
Testing status == "down" catches only the first row. Ask the question the other way around, is it fully
up?, and everything else is down, whatever words the OS uses.
in one sentence Test for what working looks like; treat everything else as not working.
A dict as a counter
To count things, keep a dict whose keys are the things and whose values are the counts. get(key, 0) gives
the count so far, or 0 for a key you haven’t seen yet, so adding one always works.
r1 and sw1
r1 has one interface shut down. sw1, the lab’s switch, has eight ports (GigabitEthernet1 to 8) and cables on
only two of them. Its saved output is in checks/data/, and open(...).read() reads a file into one string
(chapter 4 covers files):
>>> down_interfaces(interfaces)
['GigabitEthernet4']
>>> text = open("checks/data/brief-sw1.txt").read()
>>> sw1 = interfaces_to_dicts(text)
>>> down_interfaces(sw1)
['GigabitEthernet3', 'GigabitEthernet4', 'GigabitEthernet5', 'GigabitEthernet6', 'GigabitEthernet7', 'GigabitEthernet8']
>>> count_by_status(sw1)
{'up': 4, 'down': 6}
And a version of down_interfaces() that tests status == "down", as make check sees it. The message gives
the input (a list of ten interfaces, shortened here), what the check expected, and what came back:
E AssertionError: for these interfaces
E [{'interface': 'GigabitEthernet0', ... 'status': 'down', 'protocol': 'down'}, ... ]
E we expected ['GigabitEthernet0', 'GigabitEthernet2', 'GigabitEthernet3', 'Loopback0', 'Vlan20']
E and got ['GigabitEthernet0', 'GigabitEthernet3']
...
__________________________ test_up_but_protocol_down ___________________________
checks/test_3_1.py:18: in test_up_but_protocol_down
assert call(down_interfaces, rows) == ["Gi1"], "status up but protocol down still isn't working"
E AssertionError: status up but protocol down still isn't working
E assert [] == ['Gi1']
GigabitEthernet2 and Vlan20 were administratively down, and Loopback0 was up with its protocol down. None of
them said "down" in the Status column.
down_interfaces()
Open
netlab/interfaces.pyand read the docstring underTODO 3.1a, the text in triple quotes. It’s the spec: names, in the order they came, of the interfaces that aren’t fully up.Replace its
raise NotImplementedError(...)line with:editnetlab/interfaces.pyCtrl+P → interfaces.pydown = [] for i in interfaces: if i["status"] != "up" or i["protocol"] != "up": down.append(i["interface"]) return downRead it aloud: for each interface, if its status isn’t up or its protocol isn’t up, add its name.
ormeans either one is enough. Thereturnis level with thefor, so it runs once, after the loop; one level further in and it would return after the first interface.Save, start a REPL, and try it on r1. This uses your
interfaces_to_dicts()from task 2.2 (skipped it?make solve T=2.2puts it in):run in the terminalpython>>> from netlab.parse import SAMPLE, interfaces_to_dicts >>> from netlab.interfaces import down_interfaces, count_by_status >>> interfaces = interfaces_to_dicts(SAMPLE) >>> down_interfaces(interfaces) ['GigabitEthernet4']Now the cases no lab device is in right now. You don’t need a device in that state: hand the function the data.
>>> down_interfaces([{"interface": "Gi1", "status": "up", "protocol": "down"}]) ['Gi1'] >>> down_interfaces([]) []An empty list never enters the loop, so the function returns the empty
downit started with.
in one sentence A function that takes data can be tried on any data, including states the lab isn’t in.
count_by_status()
Write count_by_status(interfaces) under TODO 3.1b. It returns a dict with one key per status that occurs,
and how many interfaces have it:
>>> count_by_status(interfaces)
{'up': 5, 'administratively down': 1}
>>> count_by_status([])
{}
Only statuses that occur are keys: no 'down': 0.
hint
The same shape as down_interfaces(), with a dict instead of a list: counts = {} before the loop,
return counts after it.
hint
counts[status] += 1 fails with KeyError the first time a status turns up, because the key isn’t there
yet. counts.get(status, 0) is the count so far, or 0.
show the solutionnetlab/interfaces.py
or pull it into your lab: make solve T=3.1, then git diff --staged shows what changed
def count_by_status(interfaces):
counts = {}
for i in interfaces:
counts[i["status"]] = counts.get(i["status"], 0) + 1
return counts
For each interface, look up how many of its status you’ve counted so far (0 if none), add one, and store it
back under the same key. A new status gets a key the first time it’s seen, so only statuses that occur appear,
in the order they first turned up. There’s no if here: the dict does the deciding. Python’s standard library
has a ready-made counter,
collections.Counter, which does the same; writing it once yourself is how you find
out what it’s doing.
5 check: run it, then prove it
$ make check T=3.1when it's right, you'll see
task 3.1 checks/test_3_1.py
checks/test_3_1.py::test_down_interfaces PASSED [ 25%]
checks/test_3_1.py::test_up_but_protocol_down PASSED [ 50%]
checks/test_3_1.py::test_count_by_status PASSED [ 75%]
checks/test_3_1.py::test_empty PASSED [100%]
============================== 4 passed in 0.01s ===============================
✓ task 3.1 done