Add unit tests for loopbacks; While here, fix a bug in get_by_name(), yaay

This commit is contained in:
Pim van Pelt
2022-03-22 18:02:35 +00:00
parent 36fbbf9b35
commit 5ecd1ef22c
3 changed files with 47 additions and 1 deletions

View File

@ -0,0 +1,12 @@
loopbacks:
loop0:
description: "Loopback, no config"
loop1:
description: "Loopback, both LCP and address"
mtu: 2000
lcp: "loop56789012345"
addresses: [ 192.0.2.1/29, 2001:db8::1/64 ]
loop2:
description: "Loopback, invalid because it has an address but no LCP"
mtu: 2000
addresses: [ 192.0.2.9/29, 2001:db8:1::1/64 ]

View File

@ -19,6 +19,14 @@ class NullHandler(logging.Handler):
def emit(self, record):
pass
def get_loopbacks(yaml):
""" Return a list of all loopbacks. """
ret = []
if 'loopbacks' in yaml:
for ifname, iface in yaml['loopbacks'].items():
ret.append(ifname)
return ret
def get_by_name(yaml, ifname):
""" Return the loopback by name, if it exists. Return None otherwise. """
try:
@ -26,7 +34,7 @@ def get_by_name(yaml, ifname):
return ifname, yaml['loopbacks'][ifname]
except:
pass
return None
return None, None
def validate_loopbacks(yaml):

View File

@ -0,0 +1,26 @@
import unittest
import yaml
import validator.loopback as loopback
class TestLoopbackMethods(unittest.TestCase):
def setUp(self):
with open("unittest/test_loopback.yaml", "r") as f:
self.cfg = yaml.load(f, Loader = yaml.FullLoader)
def test_get_by_name(self):
ifname, iface = loopback.get_by_name(self.cfg, "loop1")
self.assertIsNotNone(iface)
self.assertEqual("loop1", ifname)
self.assertEqual(iface['mtu'], 2000)
ifname, iface = loopback.get_by_name(self.cfg, "loop-noexist")
self.assertIsNone(ifname)
self.assertIsNone(iface)
def test_enumerators(self):
ifs = loopback.get_loopbacks(self.cfg)
self.assertEqual(len(ifs), 3)
self.assertIn("loop0", ifs)
self.assertIn("loop1", ifs)
self.assertIn("loop2", ifs)
self.assertNotIn("loop-noexist", ifs)