def t2_add_retr_object_with_attr(tree=None): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() for p in [["container"], ["container", "deeper"]]: tree.register(p, TestObject("container")) for q_style in ["'", '"', ""]: for i in range(0, 5): tree.register(p + ["foo[id=%s%d%s]" % ( q_style, i, q_style, )], TestObject("t2_ObjTest%d" % i)) for q_style in ["'", '"', ""]: for j in range(0, 5): retr_obj = tree.get("%s/foo[id=%s%d%s]" % ( "/" + "/".join(p), q_style, j, q_style, )) assert len(retr_obj) == 1, ( "retrieved the wrong number of " + "objects (%d != 1)" % len(retr_obj)) assert isinstance( retr_obj[0], TestObject), ("retrieved object " + "was not the correct class") assert retr_obj[0].name() == "t2_ObjTest%d" % j, \ ("retrieved object had an invalid name specified (%s != " + "t2_ObjTest%d, q_style=%s)" % (retr_obj.name(), j, q_style)) if del_tree: del tree
class JSONSerialiseTests(PyangBindTestCase): yang_files = ["json-serialise.yang"] pyang_flags = ["--use-xpathhelper"] def setUp(self): self.yang_helper = YANGPathHelper() self.serialise_obj = self.bindings.json_serialise(path_helper=self.yang_helper) def test_serialise_container(self): self.serialise_obj.two.string_test = "twenty-two" with open(os.path.join(os.path.dirname(__file__), "json", "container.json"), "r") as fp: self.assertEqual( json.loads(dumps(self.yang_helper.get("/two")[0])), json.load(fp), "Invalid output returned when serialising a container.", ) def test_full_serialise(self): self.serialise_obj.c1.l1.add(1) for signed in ["int", "uint"]: for size in [8, 16, 32, 64]: name = "%s%s" % (signed, size) setter = getattr(self.serialise_obj.c1.l1[1], "_set_%s" % name) setter(1) self.serialise_obj.c1.l1[1].restricted_integer = 6 self.serialise_obj.c1.l1[1].string = "bear" self.serialise_obj.c1.l1[1].restricted_string = "aardvark" self.serialise_obj.c1.l1[1].union = 16 self.serialise_obj.c1.l1[1].union_list.append(16) self.serialise_obj.c1.l1[1].union_list.append("chicken") self.serialise_obj.c1.t1.add(16) self.serialise_obj.c1.t1.add(32) self.serialise_obj.c1.l1[1].leafref = 16 self.serialise_obj.c1.l1[1].binary = bitarray("010101") self.serialise_obj.c1.l1[1].boolean = True self.serialise_obj.c1.l1[1].enumeration = "one" self.serialise_obj.c1.l1[1].identityref = "idone" self.serialise_obj.c1.l1[1].typedef_one = "test" self.serialise_obj.c1.l1[1].typedef_two = 8 self.serialise_obj.c1.l1[1].one_leaf = "hi" for i in range(1, 5): self.serialise_obj.c1.l1[1].ll.append(six.text_type(i)) self.serialise_obj.c1.l1[1].next_hop.append("DROP") self.serialise_obj.c1.l1[1].next_hop.append("192.0.2.1") self.serialise_obj.c1.l1[1].next_hop.append("fish") self.serialise_obj.c1.l1[1].typedef_decimal = Decimal("21.21") self.serialise_obj.c1.l1[1].range_decimal = Decimal("4.44443322") self.serialise_obj.c1.l1[1].typedef_decimalrange = Decimal("42.42") self.serialise_obj.c1.l1[1].decleaf = Decimal("42.4422") for i in range(1, 10): self.serialise_obj.c1.l2.add(i) pybind_json = json.loads(dumps(self.serialise_obj)) with open(os.path.join(os.path.dirname(__file__), "json", "expected-output.json"), "r") as fp: external_json = json.load(fp) self.assertEqual(pybind_json, external_json, "JSON did not match expected output.")
class JSONSerialiseTests(PyangBindTestCase): yang_files = ['json-serialise.yang'] pyang_flags = ['--use-xpathhelper'] def setUp(self): self.yang_helper = YANGPathHelper() self.serialise_obj = self.bindings.json_serialise(path_helper=self.yang_helper) def test_serialise_container(self): self.serialise_obj.two.string_test = "twenty-two" with open(os.path.join(os.path.dirname(__file__), "json", "container.json"), 'r') as fp: self.assertEqual( json.loads(dumps(self.yang_helper.get("/two")[0])), json.load(fp), "Invalid output returned when serialising a container." ) def test_full_serialise(self): self.serialise_obj.c1.l1.add(1) for signed in ["int", "uint"]: for size in [8, 16, 32, 64]: name = "%s%s" % (signed, size) setter = getattr(self.serialise_obj.c1.l1[1], "_set_%s" % name) setter(1) self.serialise_obj.c1.l1[1].restricted_integer = 6 self.serialise_obj.c1.l1[1].string = "bear" self.serialise_obj.c1.l1[1].restricted_string = "aardvark" self.serialise_obj.c1.l1[1].union = 16 self.serialise_obj.c1.l1[1].union_list.append(16) self.serialise_obj.c1.l1[1].union_list.append("chicken") self.serialise_obj.c1.t1.add(16) self.serialise_obj.c1.t1.add(32) self.serialise_obj.c1.l1[1].leafref = 16 self.serialise_obj.c1.l1[1].binary = bitarray("010101") self.serialise_obj.c1.l1[1].boolean = True self.serialise_obj.c1.l1[1].enumeration = "one" self.serialise_obj.c1.l1[1].identityref = "idone" self.serialise_obj.c1.l1[1].typedef_one = "test" self.serialise_obj.c1.l1[1].typedef_two = 8 self.serialise_obj.c1.l1[1].one_leaf = "hi" for i in range(1, 5): self.serialise_obj.c1.l1[1].ll.append(six.text_type(i)) self.serialise_obj.c1.l1[1].next_hop.append("DROP") self.serialise_obj.c1.l1[1].next_hop.append("192.0.2.1") self.serialise_obj.c1.l1[1].next_hop.append("fish") self.serialise_obj.c1.l1[1].typedef_decimal = Decimal("21.21") self.serialise_obj.c1.l1[1].range_decimal = Decimal("4.44443322") self.serialise_obj.c1.l1[1].typedef_decimalrange = Decimal("42.42") self.serialise_obj.c1.l1[1].decleaf = Decimal("42.4422") for i in range(1, 10): self.serialise_obj.c1.l2.add(i) pybind_json = json.loads(dumps(self.serialise_obj)) with open(os.path.join(os.path.dirname(__file__), "json", "expected-output.json"), 'r') as fp: external_json = json.load(fp) self.assertEqual(pybind_json, external_json, "JSON did not match expected output.")
def t1_add_retr_object_plain(tree=False): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() obj_one = TestObject("t1_ObjOneTest") tree.register(["obj_one"], obj_one) retr_obj = tree.get(["obj_one"]) assert len(retr_obj) == 1, ("retrieved path matched the wrong number " + "of objects (%d != 1)" % (len(retr_obj))) assert isinstance(retr_obj[0], TestObject), ("retrieved object was not " + "the correct class") assert retr_obj[0].name() == "t1_ObjOneTest", ("retrieved object had an " + "invalid name specified (%s != t1_ObjOneTest)" % retr_obj.name()) if del_tree: del tree
def t1_add_retr_object_plain(tree=None): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() obj_one = TestObject("t1_ObjOneTest") tree.register(["obj_one"], obj_one) retr_obj = tree.get(["obj_one"]) assert len(retr_obj) == 1, ("retrieved path matched the wrong number " + "of objects (%d != 1)" % (len(retr_obj))) assert isinstance(retr_obj[0], TestObject), ("retrieved object was not " + "the correct class") assert retr_obj[0].name() == "t1_ObjOneTest", ( "retrieved object had an " + "invalid name specified (%s != t1_ObjOneTest)" % retr_obj.name()) if del_tree: del tree
def t4_retr_obj_error(tree=False): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() retr = tree.get("/a/non-existant/path") assert len(retr) == 0, ("getting a non-existant path returned the wrong " + "number of objects (%d != 0)" % (len(retr))) passed = False try: tree.register("an-invalid-path-name", TestObject("invalid")) except XPathError: passed = True assert passed is True, ("setting an invalid path did not throw " + "an XPathError")
def t4_retr_obj_error(tree=False): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() retr = tree.get("/a/non-existant/path") assert len(retr) == 0, ("getting a non-existant path returned the wrong " + "number of objects (%d != 0)" % (len(retr))) passed = False try: tree.register("an-invalid-path-name", TestObject("invalid")) except XPathError: passed = True assert passed is True, ("setting an invalid path did not throw " + "an XPathError")
def t3_add_retr_object_hierarchy(tree=False): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() path = [] obj = {} for i in range(0, 10): path += ["node%d" % i] obj[i] = TestObject(i) tree.register(path, obj[i]) path = "" for j in range(0, 10): path += "/node%d" % j retr_obj = tree.get(path) assert len(retr_obj) == 1, \ ("incorrect number of objects retrieved for %s (%d != 1)" % (path, len(retr_obj))) assert retr_obj[0].name() == j, ("retrieved object did not " + "have a valid name (%s != %s)" % (j, retr_obj.name()))
def t3_add_retr_object_hierarchy(tree=False): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() path = [] obj = {} for i in range(0, 10): path += ["node%d" % i] obj[i] = TestObject(i) tree.register(path, obj[i]) path = "" for j in range(0, 10): path += "/node%d" % j retr_obj = tree.get(path) assert len(retr_obj) == 1, \ ("incorrect number of objects retrieved for %s (%d != 1)" % (path, len(retr_obj))) assert retr_obj[0].name() == j, ("retrieved object did not " + "have a valid name (%s != %s)" % (j, retr_obj.name()))
def t2_add_retr_object_with_attr(tree=False): del_tree = False if not tree: del_tree = True tree = YANGPathHelper() for p in [["container"], ["container", "deeper"]]: tree.register(p, TestObject("container")) for q_style in ["'", '"', ""]: for i in range(0, 5): tree.register(p + ["foo[id=%s%d%s]" % (q_style, i, q_style,)], TestObject("t2_ObjTest%d" % i)) for q_style in ["'", '"', ""]: for j in range(0, 5): retr_obj = tree.get("%s/foo[id=%s%d%s]" % ("/" + "/".join(p), q_style, j, q_style,)) assert len(retr_obj) == 1, ("retrieved the wrong number of " + "objects (%d != 1)" % len(retr_obj)) assert isinstance(retr_obj[0], TestObject), ("retrieved object " + "was not the correct class") assert retr_obj[0].name() == "t2_ObjTest%d" % j, \ ("retrieved object had an invalid name specified (%s != " + "t2_ObjTest%d, q_style=%s)" % (retr_obj.name(), j, q_style)) if del_tree: del tree
class PathHelperBaseTests(unittest.TestCase): def setUp(self): self.tree = YANGPathHelper() def test_get_returns_same_number_of_objects_as_registered(self): obj = TestObject("testobj") self.tree.register(["obj_one"], obj) self.assertEqual(len(self.tree.get(["obj_one"])), 1) def test_get_returns_objects_of_same_class_as_registered(self): obj = TestObject("testobj") self.tree.register(["obj_one"], obj) self.assertIsInstance(self.tree.get(["obj_one"])[0], TestObject) def test_get_returns_objects_with_same_attributes_as_registered(self): obj = TestObject("testobj") self.tree.register(["obj_one"], obj) self.assertEqual(self.tree.get(["obj_one"])[0].name(), "testobj") def test_get_non_existent_path_returns_nothing(self): self.assertEqual(len(self.tree.get("/a/non-existent/path")), 0) def test_register_invalid_path_raises_exception(self): with self.assertRaises(XPathError): self.tree.register("an-invalid-path-name", TestObject("invalid")) def test_retrieve_object_at_bottom_of_hierarchy_returns_single_object(self): self.tree.register(["node0"], TestObject(0)) self.tree.register(["node0", "node1"], TestObject(1)) self.tree.register(["node0", "node1", "node2"], TestObject(2)) self.assertEqual(len(self.tree.get("/node0/node1/node2")), 1) def test_retrieve_object_at_bottom_of_hierarchy_has_proper_name(self): self.tree.register(["node0"], TestObject(0)) self.tree.register(["node0", "node1"], TestObject(1)) self.tree.register(["node0", "node1", "node2"], TestObject(2)) self.assertEqual(self.tree.get("/node0/node1/node2")[0].name(), 2) def test_register_object_with_attribute(self): self.tree.register(["container"], TestObject("container")) allowed = True try: self.tree.register(["container", "foo[id=0]"], TestObject("bar")) except Exception: allowed = False self.assertTrue(allowed) def test_retrieve_object_by_attribute_returns_single_object(self): self.tree.register(["container"], TestObject("container")) self.tree.register(["container", "foo[id=0]"], TestObject("bar0")) self.tree.register(["container", "foo[id=1]"], TestObject("bar1")) self.assertEqual(len(self.tree.get("/container/foo[id=0]")), 1) def test_get_object_by_attribute_returns_object_of_same_class(self): self.tree.register(["container"], TestObject("container")) self.tree.register(["container", "foo[id=0]"], TestObject("bar0")) self.assertIsInstance(self.tree.get("/container/foo[id=0]")[0], TestObject) def test_register_object_with_attribute_various_quoting_styles(self): self.tree.register(["container"], TestObject("container")) for style in ['"', "'", ""]: with self.subTest(style=style): allowed = True try: self.tree.register(["container", "foo[id={0}42{0}]".format(style)], TestObject(42)) except Exception: allowed = False self.assertTrue(allowed) def test_get_object_with_attribute_various_quoting_styles(self): self.tree.register(["container"], TestObject("container")) self.tree.register(["container", "foo[id=42]"], TestObject("bar42")) for style in ['"', "'", ""]: with self.subTest(style=style): obj = self.tree.get("/container/foo[id={0}42{0}]".format(style))[0] self.assertEqual(obj.name(), "bar42")
class XPathListLeaflistTests(PyangBindTestCase): yang_files = ['list-tc01.yang'] pyang_flags = ['--use-xpathhelper'] def setUp(self): self.path_helper = YANGPathHelper() self.instance = self.bindings.list_tc01(path_helper=self.path_helper) def test_leaflist_leafref_with_require_instance_true(self): for fish in ['mackerel', 'trout', 'haddock', 'flounder']: self.instance.container.t1.append(fish) for (fish, valid) in [('mackerel', True), ('haddock', True), ('minnow', False)]: with self.subTest(fish=fish, valid=valid): allowed = True try: self.instance.reference.t1_ptr = fish except ValueError: allowed = False self.assertEqual(valid, allowed) def test_leaflist_leafref_with_require_instance_false(self): for fish in ['mackerel', 'trout', 'haddock', 'flounder']: self.instance.container.t1.append(fish) for (fish, exists) in [('flounder', True), ('minnow', False)]: with self.subTest(fish=fish, exists=exists): allowed = True try: self.instance.reference.t1_ptr_noexist = fish except ValueError: allowed = False self.assertTrue(allowed) def test_list_leafref_with_require_instance_true(self): for animal in ['kangaroo', 'wallaby', 'koala', 'dingo']: self.instance.container.t2.add(animal) for (animal, valid) in [('kangaroo', True), ('koala', True), ('wombat', False)]: with self.subTest(animal=animal, valid=valid): allowed = True try: self.instance.reference.t2_ptr = animal except ValueError: allowed = False self.assertEqual(valid, allowed) def test_get_leaflist_with_xpath_helper_returns_single_element(self): for beer in [ 'oatmeal-stout', 'amber-ale', 'pale-ale', 'pils', 'ipa', 'session-ipa' ]: self.instance.container.t3.append(beer) self.assertEqual(len(self.path_helper.get('/container/t3')), 1) def test_find_elements_of_leaflist(self): for beer in [ 'oatmeal-stout', 'amber-ale', 'pale-ale', 'pils', 'ipa', 'session-ipa' ]: self.instance.container.t3.append(beer) leaflist = self.path_helper.get('/container/t3')[0] for (beer, valid) in [('session-ipa', True), ('amber-ale', True), ('moose-drool', False)]: with self.subTest(beer=beer, valid=valid): found = True try: leaflist.index(beer) except ValueError: found = False self.assertEqual(valid, found) def test_remove_elements_from_leaflist(self): for beer in [ 'oatmeal-stout', 'amber-ale', 'pale-ale', 'pils', 'ipa', 'session-ipa' ]: self.instance.container.t3.append(beer) for (beer, valid) in [('session-ipa', True), ('amber-ale', True), ('moose-drool', False)]: with self.subTest(beer=beer, valid=valid): removed = True try: self.instance.container.t3.remove(beer) except ValueError: removed = False self.assertEqual(removed, valid) def test_xpath_helper_gets_updated_leaflist_after_removing_items(self): for beer in [ 'oatmeal-stout', 'amber-ale', 'pale-ale', 'pils', 'ipa', 'session-ipa' ]: self.instance.container.t3.append(beer) retr = self.path_helper.get( '/container/t3') # Retrieve before to get the old value for beer in ['session-ipa', 'amber-ale']: self.instance.container.t3.remove(beer) retr = self.path_helper.get('/container/t3') for beer in ['session-ipa', 'amber-ale', 'moose-drool']: with self.subTest(beer=beer), self.assertRaises(ValueError): retr[0].index(beer) def test_get_list_item_with_xpath_helper_returns_single_element(self): for beer in [ 'steam', 'liberty', 'california-lager', 'porter', 'ipa', 'foghorn' ]: self.instance.container.t4.add(beer) for (beer, exists) in [('steam', 1), ('liberty', 1), ('pygmy-owl', 0)]: with self.subTest(beer=beer, exists=exists): retr = self.path_helper.get('/container/t4[keyval=%s]' % beer) self.assertEqual(len(retr), exists) def test_remove_elements_from_list(self): for beer in [ 'steam', 'liberty', 'california-lager', 'porter', 'ipa', 'foghorn' ]: self.instance.container.t4.add(beer) for (beer, valid) in [('steam', True), ('liberty', True), ('pygmy-owl', False)]: with self.subTest(beer=beer, valid=valid): removed = True try: self.instance.container.t4.delete(beer) except KeyError: removed = False self.assertEqual(removed, valid) def test_xpath_helper_gets_updated_list_after_removing_items(self): for beer in [ 'steam', 'liberty', 'california-lager', 'porter', 'ipa', 'foghorn' ]: self.instance.container.t4.add(beer) for beer in ['steam', 'liberty', 'pygmy-owl']: with self.subTest(beer=beer): path = '/container/t4[keyval=%s]' retr = self.path_helper.get(path) try: self.instance.container.t4.delete(beer) except KeyError: pass retr = self.path_helper.get(path) self.assertEqual(len(retr), 0) def test_typedef_leaflist_with_require_instance_true(self): for city in ['quebec-city', 'montreal', 'laval', 'gatineau']: self.instance.container.t5.append(city) for (city, valid) in [('quebec-city', True), ('montreal', True), ('dallas', False)]: with self.subTest(city=city, valid=valid): allowed = True try: self.instance.reference.t5_ptr = city except ValueError: allowed = False self.assertEqual(valid, allowed) def test_typedef_list_with_require_instance_true(self): for beer in ['la-ciboire', 'la-chipie', 'la-joufflue', 'la-matante']: self.instance.container.t6.add(beer) for (beer, valid) in [('la-ciboire', True), ('la-matante', True), ('heiniken', False)]: with self.subTest(beer=beer, valid=valid): allowed = True try: self.instance.reference.t6_ptr = beer except ValueError: allowed = False self.assertEqual(valid, allowed) def test_leaflist_of_leafrefs_with_require_instance_true(self): for beer in ['snapshot', 'ranger']: self.instance.container.t7.append(beer) for (beer, valid) in [('snapshot', True), ('ranger', True), ('trout-slayer', False)]: with self.subTest(beer=beer, valid=valid): allowed = True try: self.instance.reference.t7_ptr.append(beer) except ValueError: allowed = False self.assertEqual(valid, allowed) def test_standalone_leaflist(self): self.instance.standalone.ll.append(1) retr = self.path_helper.get('/standalone/ll') self.assertEqual(retr[0][0], 1) def test_standlone_list(self): self.instance.standalone.l.add(1) retr = self.path_helper.get('/standalone/l') self.assertEqual(retr[0].x, 1) def test_standalone_ref(self): self.instance.standalone.l.add(1) self.instance.standalone.ref = 1 self.assertEqual(self.instance.standalone.ref._referenced_object, 1) def test_get_list_retrieves_correct_attribute(self): self.assertEqual( self.path_helper.get_list('/standalone/l')._yang_name, 'l') def test_get_list_returns_correct_type(self): self.assertEqual( self.path_helper.get_list('/standalone/l')._is_container, 'list')
def main(): try: opts, args = getopt.getopt(sys.argv[1:], "k", ["keepfiles"]) except getopt.GetoptError as e: print str(e) sys.exit(127) k = False for o, a in opts: if o in ["-k", "--keepfiles"]: k = True pythonpath = os.environ.get("PATH_TO_PYBIND_TEST_PYTHON") if \ os.environ.get('PATH_TO_PYBIND_TEST_PYTHON') is not None \ else sys.executable pyangpath = os.environ.get('PYANGPATH') if \ os.environ.get('PYANGPATH') is not None else False pyangbindpath = os.environ.get('PYANGBINDPATH') if \ os.environ.get('PYANGBINDPATH') is not None else False assert pyangpath is not False, "could not find path to pyang" assert pyangbindpath is not False, "could not resolve pyangbind directory" this_dir = os.path.dirname(os.path.realpath(__file__)) cmd = "%s " % pythonpath cmd += "%s --plugindir %s/pyangbind/plugin" % (pyangpath, pyangbindpath) cmd += " -f pybind -o %s/bindings.py" % this_dir cmd += " -p %s" % this_dir cmd += " --use-xpathhelper" cmd += " %s/%s.yang" % (this_dir, TESTNAME) os.system(cmd) from bindings import json_serialise from bitarray import bitarray from pyangbind.lib.xpathhelper import YANGPathHelper y = YANGPathHelper() js = json_serialise(path_helper=y) js.c1.l1.add(1) for s in ["int", "uint"]: for l in [8, 16, 32, 64]: name = "%s%s" % (s, l) x = getattr(js.c1.l1[1], "_set_%s" % name) x(1) js.c1.l1[1].restricted_integer = 6 js.c1.l1[1].string = "bear" js.c1.l1[1].restricted_string = "aardvark" js.c1.l1[1].union = 16 js.c1.l1[1].union_list.append(16) js.c1.l1[1].union_list.append("chicken") js.c1.t1.add(16) js.c1.t1.add(32) js.c1.l1[1].leafref = 16 js.c1.l1[1].binary = bitarray("010101") js.c1.l1[1].boolean = True js.c1.l1[1].enumeration = "one" js.c1.l1[1].identityref = "idone" js.c1.l1[1].typedef_one = "test" js.c1.l1[1].typedef_two = 8 js.c1.l1[1].one_leaf = "hi" for i in range(1, 5): js.c1.l1[1].ll.append(unicode(i)) js.c1.l1[1].next_hop.append("DROP") js.c1.l1[1].next_hop.append("192.0.2.1") js.c1.l1[1].next_hop.append("fish") js.c1.l1[1].typedef_decimal = Decimal("21.21") js.c1.l1[1].range_decimal = Decimal("4.44443322") js.c1.l1[1].typedef_decimalrange = Decimal("42.42") js.c1.l1[1].decleaf = Decimal("42.4422") for i in range(1, 10): js.c1.l2.add(i) pybind_json = json.loads(dumps(js)) external_json = json.load(open(os.path.join(this_dir, "json", "expected-output.json"), 'r')) assert pybind_json == external_json, "JSON did not match the expected output" yph = YANGPathHelper() new_obj = json_serialise(path_helper=yph) new_obj.two.string_test = "twenty-two" assert json.loads(dumps(yph.get("/two")[0])) == \ json.load(open(os.path.join(this_dir, "json", "container.json"), 'r')), \ "Invalid output returned when serialising a container" if not k: os.system("/bin/rm %s/bindings.py" % this_dir) os.system("/bin/rm %s/bindings.pyc" % this_dir)
class ocDispatcher: """ Open Config Dispatcher that dispatch requests to other openconfig binding modules """ def __init__(self, is_dbg_test): self.my_args = dispArgs() self.my_args.cfgdb = swsssdk.ConfigDBConnector() self.my_args.cfgdb.connect() self.my_args.appdb = swsssdk.SonicV2Connector(host='127.0.0.1') self.my_args.appdb.connect(self.my_args.appdb.APPL_DB) self.my_args.appdb.connect(self.my_args.appdb.COUNTERS_DB) self.my_args.appdb.connect(self.my_args.appdb.ASIC_DB) # check if port table is ready is_pcfg_done = False chk_cnt = 0 while True: pcfg_val = self.my_args.appdb.get_all(self.my_args.appdb.APPL_DB, "PORT_TABLE:PortConfigDone") is_pcfg_done = pcfg_val != None chk_cnt += 1 if is_pcfg_done or chk_cnt % 3 == 1: util_utl.utl_log( "PORT TABLE was%sready...(%s)" % ([" not ", " "][is_pcfg_done], chk_cnt), logging.CRITICAL) if is_pcfg_done: break time.sleep(10) # create the full yang tree # for performance, only update the tree node requested self.oc_yph = YANGPathHelper() for k in ocTable.keys(): if ocTable[k]["cls"]: ocTable[k]["cls"](path_helper = self.oc_yph) # create obj for "/" to only return subtree of depth 1 openconfig_root_dpt_1(self.oc_yph) # create all interfaces to speed up processing request for interfaces later util_interface.interface_create_all_infs(self.oc_yph, is_dbg_test, self.my_args) # create default network instance util_nwi.nwi_create_dflt_nwi(self.oc_yph, is_dbg_test) # create default objects util_qos.qos_create_dflt_obj(self.oc_yph, is_dbg_test) # check if new teammgrd is used test_cmd = 'docker run --rm=true --privileged=true --entrypoint="/bin/bash" "docker-teamd" -c "[ -f /usr/bin/teammgrd ]"' util_interface.IS_NEW_TEAMMGRD = util_utl.utl_execute_cmd(test_cmd) #def CreateAllInterfaces(self, is_dbg_test): # return util_interface.interface_create_all_infs(self.oc_yph, is_dbg_test) @util_utl.utl_timeit @util_utl.utl_log_outer def GetRequestYph(self, path_ar, key_ar): # only return subtree of depth 1 if len(path_ar) < 1: return self.oc_yph if path_ar[0] not in ocTable: oc_yph = StatusCode.INVALID_ARGUMENT else: oc_yph = self.oc_yph # suppose key_ar [0] is interface name e.g. "eth0" try: ret_val = eval(ocTable[path_ar[0]]["info_f"])(oc_yph, path_ar, key_ar, self.my_args) if not ret_val: oc_yph = StatusCode.INTERNAL except Exception as e: logging.fatal(e, exc_info=True) oc_yph = StatusCode.INTERNAL return oc_yph @util_utl.utl_timeit @util_utl.utl_log_outer def SetValByPath(self, yp_str, pkey_ar, val): try: tmp_obj = self.oc_yph.get(yp_str) # replace key [xxx=yyy] with [xxx] reg_path = re.sub(r'\[([\w-]*)=[^]]*\]', r"[\1]", yp_str) ret_val = eval(setPathTable[reg_path])(self.oc_yph, pkey_ar, val.strip('"'), len(tmp_obj) == 0, self.my_args) \ if reg_path in setPathTable else False except Exception as e: logging.fatal(e, exc_info=True) ret_val = False return ret_val
class XPathListLeaflistTests(PyangBindTestCase): yang_files = ["list-tc01.yang"] pyang_flags = ["--use-xpathhelper"] def setUp(self): self.path_helper = YANGPathHelper() self.instance = self.bindings.list_tc01(path_helper=self.path_helper) def test_leaflist_leafref_with_require_instance_true(self): for fish in ["mackerel", "trout", "haddock", "flounder"]: self.instance.container.t1.append(fish) for (fish, valid) in [("mackerel", True), ("haddock", True), ("minnow", False)]: with self.subTest(fish=fish, valid=valid): allowed = True try: self.instance.reference.t1_ptr = fish except ValueError: allowed = False self.assertEqual(valid, allowed) def test_leaflist_leafref_with_require_instance_false(self): for fish in ["mackerel", "trout", "haddock", "flounder"]: self.instance.container.t1.append(fish) for (fish, exists) in [("flounder", True), ("minnow", False)]: with self.subTest(fish=fish, exists=exists): allowed = True try: self.instance.reference.t1_ptr_noexist = fish except ValueError: allowed = False self.assertTrue(allowed) def test_list_leafref_with_require_instance_true(self): for animal in ["kangaroo", "wallaby", "koala", "dingo"]: self.instance.container.t2.add(animal) for (animal, valid) in [("kangaroo", True), ("koala", True), ("wombat", False)]: with self.subTest(animal=animal, valid=valid): allowed = True try: self.instance.reference.t2_ptr = animal except ValueError: allowed = False self.assertEqual(valid, allowed) def test_get_leaflist_with_xpath_helper_returns_single_element(self): for beer in [ "oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa" ]: self.instance.container.t3.append(beer) self.assertEqual(len(self.path_helper.get("/container/t3")), 1) def test_find_elements_of_leaflist(self): for beer in [ "oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa" ]: self.instance.container.t3.append(beer) leaflist = self.path_helper.get("/container/t3")[0] for (beer, valid) in [("session-ipa", True), ("amber-ale", True), ("moose-drool", False)]: with self.subTest(beer=beer, valid=valid): found = True try: leaflist.index(beer) except ValueError: found = False self.assertEqual(valid, found) def test_remove_elements_from_leaflist(self): for beer in [ "oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa" ]: self.instance.container.t3.append(beer) for (beer, valid) in [("session-ipa", True), ("amber-ale", True), ("moose-drool", False)]: with self.subTest(beer=beer, valid=valid): removed = True try: self.instance.container.t3.remove(beer) except ValueError: removed = False self.assertEqual(removed, valid) def test_xpath_helper_gets_updated_leaflist_after_removing_items(self): for beer in [ "oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa" ]: self.instance.container.t3.append(beer) retr = self.path_helper.get( "/container/t3") # Retrieve before to get the old value for beer in ["session-ipa", "amber-ale"]: self.instance.container.t3.remove(beer) retr = self.path_helper.get("/container/t3") for beer in ["session-ipa", "amber-ale", "moose-drool"]: with self.subTest(beer=beer), self.assertRaises(ValueError): retr[0].index(beer) def test_get_list_item_with_xpath_helper_returns_single_element(self): for beer in [ "steam", "liberty", "california-lager", "porter", "ipa", "foghorn" ]: self.instance.container.t4.add(beer) for (beer, exists) in [("steam", 1), ("liberty", 1), ("pygmy-owl", 0)]: with self.subTest(beer=beer, exists=exists): retr = self.path_helper.get("/container/t4[keyval=%s]" % beer) self.assertEqual(len(retr), exists) def test_remove_elements_from_list(self): for beer in [ "steam", "liberty", "california-lager", "porter", "ipa", "foghorn" ]: self.instance.container.t4.add(beer) for (beer, valid) in [("steam", True), ("liberty", True), ("pygmy-owl", False)]: with self.subTest(beer=beer, valid=valid): removed = True try: self.instance.container.t4.delete(beer) except KeyError: removed = False self.assertEqual(removed, valid) def test_xpath_helper_gets_updated_list_after_removing_items(self): for beer in [ "steam", "liberty", "california-lager", "porter", "ipa", "foghorn" ]: self.instance.container.t4.add(beer) for beer in ["steam", "liberty", "pygmy-owl"]: with self.subTest(beer=beer): path = "/container/t4[keyval=%s]" retr = self.path_helper.get(path) try: self.instance.container.t4.delete(beer) except KeyError: pass retr = self.path_helper.get(path) self.assertEqual(len(retr), 0) def test_typedef_leaflist_with_require_instance_true(self): for city in ["quebec-city", "montreal", "laval", "gatineau"]: self.instance.container.t5.append(city) for (city, valid) in [("quebec-city", True), ("montreal", True), ("dallas", False)]: with self.subTest(city=city, valid=valid): allowed = True try: self.instance.reference.t5_ptr = city except ValueError: allowed = False self.assertEqual(valid, allowed) def test_typedef_list_with_require_instance_true(self): for beer in ["la-ciboire", "la-chipie", "la-joufflue", "la-matante"]: self.instance.container.t6.add(beer) for (beer, valid) in [("la-ciboire", True), ("la-matante", True), ("heiniken", False)]: with self.subTest(beer=beer, valid=valid): allowed = True try: self.instance.reference.t6_ptr = beer except ValueError: allowed = False self.assertEqual(valid, allowed) def test_leaflist_of_leafrefs_with_require_instance_true(self): for beer in ["snapshot", "ranger"]: self.instance.container.t7.append(beer) for (beer, valid) in [("snapshot", True), ("ranger", True), ("trout-slayer", False)]: with self.subTest(beer=beer, valid=valid): allowed = True try: self.instance.reference.t7_ptr.append(beer) except ValueError: allowed = False self.assertEqual(valid, allowed) def test_standalone_leaflist(self): self.instance.standalone.ll.append(1) retr = self.path_helper.get("/standalone/ll") self.assertEqual(retr[0][0], 1) def test_standlone_list(self): self.instance.standalone.l.add(1) retr = self.path_helper.get("/standalone/l") self.assertEqual(retr[0].x, 1) def test_standalone_ref(self): self.instance.standalone.l.add(1) self.instance.standalone.ref = 1 self.assertEqual(self.instance.standalone.ref._referenced_object, 1) def test_get_list_retrieves_correct_attribute(self): self.assertEqual( self.path_helper.get_list("/standalone/l")._yang_name, "l") def test_get_list_returns_correct_type(self): self.assertEqual( self.path_helper.get_list("/standalone/l")._is_container, "list")
class PathHelperBaseTests(unittest.TestCase): def setUp(self): self.tree = YANGPathHelper() def test_get_returns_same_number_of_objects_as_registered(self): obj = TestObject('testobj') self.tree.register(['obj_one'], obj) self.assertEqual(len(self.tree.get(['obj_one'])), 1) def test_get_returns_objects_of_same_class_as_registered(self): obj = TestObject('testobj') self.tree.register(['obj_one'], obj) self.assertIsInstance(self.tree.get(['obj_one'])[0], TestObject) def test_get_returns_objects_with_same_attributes_as_registered(self): obj = TestObject('testobj') self.tree.register(['obj_one'], obj) self.assertEqual(self.tree.get(['obj_one'])[0].name(), 'testobj') def test_get_non_existent_path_returns_nothing(self): self.assertEqual(len(self.tree.get('/a/non-existent/path')), 0) def test_register_invalid_path_raises_exception(self): with self.assertRaises(XPathError): self.tree.register('an-invalid-path-name', TestObject('invalid')) def test_retrieve_object_at_bottom_of_hierarchy_returns_single_object(self): self.tree.register(['node0'], TestObject(0)) self.tree.register(['node0', 'node1'], TestObject(1)) self.tree.register(['node0', 'node1', 'node2'], TestObject(2)) self.assertEqual(len(self.tree.get('/node0/node1/node2')), 1) def test_retrieve_object_at_bottom_of_hierarchy_has_proper_name(self): self.tree.register(['node0'], TestObject(0)) self.tree.register(['node0', 'node1'], TestObject(1)) self.tree.register(['node0', 'node1', 'node2'], TestObject(2)) self.assertEqual(self.tree.get('/node0/node1/node2')[0].name(), 2) def test_register_object_with_attribute(self): self.tree.register(['container'], TestObject('container')) allowed = True try: self.tree.register(['container', 'foo[id=0]'], TestObject('bar')) except Exception: allowed = False self.assertTrue(allowed) def test_retrieve_object_by_attribute_returns_single_object(self): self.tree.register(['container'], TestObject('container')) self.tree.register(['container', 'foo[id=0]'], TestObject('bar0')) self.tree.register(['container', 'foo[id=1]'], TestObject('bar1')) self.assertEqual(len(self.tree.get('/container/foo[id=0]')), 1) def test_get_object_by_attribute_returns_object_of_same_class(self): self.tree.register(['container'], TestObject('container')) self.tree.register(['container', 'foo[id=0]'], TestObject('bar0')) self.assertIsInstance(self.tree.get('/container/foo[id=0]')[0], TestObject) def test_register_object_with_attribute_various_quoting_styles(self): self.tree.register(['container'], TestObject('container')) for style in ['"', "'", '']: with self.subTest(style=style): allowed = True try: self.tree.register(['container', 'foo[id={0}42{0}]'.format(style)], TestObject(42)) except Exception: allowed = False self.assertTrue(allowed) def test_get_object_with_attribute_various_quoting_styles(self): self.tree.register(['container'], TestObject('container')) self.tree.register(['container', 'foo[id=42]'], TestObject('bar42')) for style in ['"', "'", '']: with self.subTest(style=style): obj = self.tree.get('/container/foo[id={0}42{0}]'.format(style))[0] self.assertEqual(obj.name(), 'bar42')
class XPathListLeaflistTests(PyangBindTestCase): yang_files = ["list-tc01.yang"] pyang_flags = ["--use-xpathhelper"] def setUp(self): self.path_helper = YANGPathHelper() self.instance = self.bindings.list_tc01(path_helper=self.path_helper) def test_leaflist_leafref_with_require_instance_true(self): for fish in ["mackerel", "trout", "haddock", "flounder"]: self.instance.container.t1.append(fish) for (fish, valid) in [("mackerel", True), ("haddock", True), ("minnow", False)]: with self.subTest(fish=fish, valid=valid): allowed = True try: self.instance.reference.t1_ptr = fish except ValueError: allowed = False self.assertEqual(valid, allowed) def test_leaflist_leafref_with_require_instance_false(self): for fish in ["mackerel", "trout", "haddock", "flounder"]: self.instance.container.t1.append(fish) for (fish, exists) in [("flounder", True), ("minnow", False)]: with self.subTest(fish=fish, exists=exists): allowed = True try: self.instance.reference.t1_ptr_noexist = fish except ValueError: allowed = False self.assertTrue(allowed) def test_list_leafref_with_require_instance_true(self): for animal in ["kangaroo", "wallaby", "koala", "dingo"]: self.instance.container.t2.add(animal) for (animal, valid) in [("kangaroo", True), ("koala", True), ("wombat", False)]: with self.subTest(animal=animal, valid=valid): allowed = True try: self.instance.reference.t2_ptr = animal except ValueError: allowed = False self.assertEqual(valid, allowed) def test_get_leaflist_with_xpath_helper_returns_single_element(self): for beer in ["oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa"]: self.instance.container.t3.append(beer) self.assertEqual(len(self.path_helper.get("/container/t3")), 1) def test_find_elements_of_leaflist(self): for beer in ["oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa"]: self.instance.container.t3.append(beer) leaflist = self.path_helper.get("/container/t3")[0] for (beer, valid) in [("session-ipa", True), ("amber-ale", True), ("moose-drool", False)]: with self.subTest(beer=beer, valid=valid): found = True try: leaflist.index(beer) except ValueError: found = False self.assertEqual(valid, found) def test_remove_elements_from_leaflist(self): for beer in ["oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa"]: self.instance.container.t3.append(beer) for (beer, valid) in [("session-ipa", True), ("amber-ale", True), ("moose-drool", False)]: with self.subTest(beer=beer, valid=valid): removed = True try: self.instance.container.t3.remove(beer) except ValueError: removed = False self.assertEqual(removed, valid) def test_xpath_helper_gets_updated_leaflist_after_removing_items(self): for beer in ["oatmeal-stout", "amber-ale", "pale-ale", "pils", "ipa", "session-ipa"]: self.instance.container.t3.append(beer) retr = self.path_helper.get("/container/t3") # Retrieve before to get the old value for beer in ["session-ipa", "amber-ale"]: self.instance.container.t3.remove(beer) retr = self.path_helper.get("/container/t3") for beer in ["session-ipa", "amber-ale", "moose-drool"]: with self.subTest(beer=beer), self.assertRaises(ValueError): retr[0].index(beer) def test_get_list_item_with_xpath_helper_returns_single_element(self): for beer in ["steam", "liberty", "california-lager", "porter", "ipa", "foghorn"]: self.instance.container.t4.add(beer) for (beer, exists) in [("steam", 1), ("liberty", 1), ("pygmy-owl", 0)]: with self.subTest(beer=beer, exists=exists): retr = self.path_helper.get("/container/t4[keyval=%s]" % beer) self.assertEqual(len(retr), exists) def test_remove_elements_from_list(self): for beer in ["steam", "liberty", "california-lager", "porter", "ipa", "foghorn"]: self.instance.container.t4.add(beer) for (beer, valid) in [("steam", True), ("liberty", True), ("pygmy-owl", False)]: with self.subTest(beer=beer, valid=valid): removed = True try: self.instance.container.t4.delete(beer) except KeyError: removed = False self.assertEqual(removed, valid) def test_xpath_helper_gets_updated_list_after_removing_items(self): for beer in ["steam", "liberty", "california-lager", "porter", "ipa", "foghorn"]: self.instance.container.t4.add(beer) for beer in ["steam", "liberty", "pygmy-owl"]: with self.subTest(beer=beer): path = "/container/t4[keyval=%s]" retr = self.path_helper.get(path) try: self.instance.container.t4.delete(beer) except KeyError: pass retr = self.path_helper.get(path) self.assertEqual(len(retr), 0) def test_typedef_leaflist_with_require_instance_true(self): for city in ["quebec-city", "montreal", "laval", "gatineau"]: self.instance.container.t5.append(city) for (city, valid) in [("quebec-city", True), ("montreal", True), ("dallas", False)]: with self.subTest(city=city, valid=valid): allowed = True try: self.instance.reference.t5_ptr = city except ValueError: allowed = False self.assertEqual(valid, allowed) def test_typedef_list_with_require_instance_true(self): for beer in ["la-ciboire", "la-chipie", "la-joufflue", "la-matante"]: self.instance.container.t6.add(beer) for (beer, valid) in [("la-ciboire", True), ("la-matante", True), ("heiniken", False)]: with self.subTest(beer=beer, valid=valid): allowed = True try: self.instance.reference.t6_ptr = beer except ValueError: allowed = False self.assertEqual(valid, allowed) def test_leaflist_of_leafrefs_with_require_instance_true(self): for beer in ["snapshot", "ranger"]: self.instance.container.t7.append(beer) for (beer, valid) in [("snapshot", True), ("ranger", True), ("trout-slayer", False)]: with self.subTest(beer=beer, valid=valid): allowed = True try: self.instance.reference.t7_ptr.append(beer) except ValueError: allowed = False self.assertEqual(valid, allowed) def test_standalone_leaflist(self): self.instance.standalone.ll.append(1) retr = self.path_helper.get("/standalone/ll") self.assertEqual(retr[0][0], 1) def test_standlone_list(self): self.instance.standalone.l.add(1) retr = self.path_helper.get("/standalone/l") self.assertEqual(retr[0].x, 1) def test_standalone_ref(self): self.instance.standalone.l.add(1) self.instance.standalone.ref = 1 self.assertEqual(self.instance.standalone.ref._referenced_object, 1) def test_get_list_retrieves_correct_attribute(self): self.assertEqual(self.path_helper.get_list("/standalone/l")._yang_name, "l") def test_get_list_returns_correct_type(self): self.assertEqual(self.path_helper.get_list("/standalone/l")._is_container, "list")