Пример #1
0
 def test_load_user_ordered_list(self):
     actual_json = pbJ.load(
         os.path.join(os.path.dirname(__file__), "json", "orderedlist-order.json"),
         self.bindings,
         "json_deserialise",
         path_helper=self.yang_helper,
     )
     self.assertEqual(list(actual_json.ordered.keys()), ["two", "one"])
Пример #2
0
 def parse_acl_json(filename):
     yang_acl = pybindJSON.load(filename, openconfig_acl, "openconfig_acl")
     # Check pybindJSON parsing
     # pybindJSON.load will silently return an empty json object if input invalid
     with open(filename, 'r') as f:
         plain_json = json.load(f)
         if len(plain_json['acl']['acl-sets']['acl-set']) != len(
                 yang_acl.acl.acl_sets.acl_set):
             raise AclLoaderException("Invalid input file %s" % filename)
     return yang_acl
Пример #3
0
 def load_rules_from_file(self, filename):
     """
     Load file with ACL rules configuration in openconfig ACL format. Convert rules
     to Config DB schema.
     :param filename: File in openconfig ACL format
     :return:
     """
     self.yang_acl = pybindJSON.load(filename, openconfig_acl,
                                     "openconfig_acl")
     self.convert_rules()
Пример #4
0
    def test_all_the_types(self):
        expected_json = {
            "c1": {
                "l1": {
                    "1": {
                        "one-leaf": "hi",
                        "typedef-one": "test",
                        "boolean": True,
                        "binary": bitarray("010101"),
                        "union": "16",
                        "identityref": "idone",
                        "enumeration": "one",
                        "k1": 1,
                        "uint16": 1,
                        "union-list": [16, "chicken"],
                        "uint32": 1,
                        "int32": 1,
                        "int16": 1,
                        "string": "bear",
                        "decimal": Decimal("42.42"),
                        "typedef-two": 8,
                        "uint8": 1,
                        "restricted-integer": 6,
                        "leafref": "16",
                        "int8": 1,
                        "uint64": 1,
                        "int64": 1,
                        "restricted-string": "aardvark",
                    }
                },
                "t1": {
                    "32": {
                        "target": "32"
                    },
                    "16": {
                        "target": "16"
                    }
                },
            }
        }
        actual_json = pbJ.load(
            os.path.join(os.path.dirname(__file__), "json", "alltypes.json"),
            self.bindings,
            "json_deserialise",
            path_helper=self.yang_helper,
        ).get(filter=True)

        self.assertEqual(actual_json, expected_json,
                         "Load of object with all items not correct.")
Пример #5
0
    def test_all_the_types(self):
        expected_json = {
            'c1': {
                'l1': {
                    '1': {
                        'one-leaf': 'hi',
                        'typedef-one': 'test',
                        'boolean': True,
                        'binary': bitarray('010101'),
                        'union': '16',
                        'identityref': 'idone',
                        'enumeration': 'one',
                        'k1': 1,
                        'uint16': 1,
                        'union-list': [16, 'chicken'],
                        'uint32': 1,
                        'int32': 1,
                        'int16': 1,
                        'string': 'bear',
                        'decimal': Decimal('42.42'),
                        'typedef-two': 8,
                        'uint8': 1,
                        'restricted-integer': 6,
                        'leafref': '16',
                        'int8': 1,
                        'uint64': 1,
                        'int64': 1,
                        'restricted-string': 'aardvark'
                    }
                },
                't1': {
                    '32': {
                        'target': '32'
                    },
                    '16': {
                        'target': '16'
                    }
                }
            }
        }
        actual_json = pbJ.load(os.path.join(os.path.dirname(__file__), "json",
                                            "alltypes.json"),
                               self.bindings,
                               "json_deserialise",
                               path_helper=self.yang_helper).get(filter=True)

        self.assertEqual(actual_json, expected_json,
                         "Load of object with all items not correct.")
Пример #6
0
  def test_load_full_object(self):
    expected_json = {'load-list': {'1': {'index': 1, 'value': 'one'},
                                   '3': {'index': 3, 'value': 'three'},
                                   '2': {'index': 2, 'value': 'two'}}}
    # For developers looking for examples, note that the arguments here are:
    #   - the file that we're trying to read
    #   - the bindings module that we generated
    #   - the name of the class within that module
    #   kwargs (path_helper, overwrite, etc.)
    actual_json = pbJ.load(
      os.path.join(os.path.dirname(__file__), "json", "list.json"),
      self.bindings,
      "json_deserialise",
      path_helper=self.yang_helper
    ).get(filter=True)

    self.assertEqual(actual_json, expected_json, "Whole object load did not return the correct list.")
Пример #7
0
    def test_all_the_types(self):
        expected_json = {
            "c1": {
                "l1": {
                    "1": {
                        "one-leaf": "hi",
                        "typedef-one": "test",
                        "boolean": True,
                        "binary": bitarray("010101"),
                        "union": "16",
                        "identityref": "idone",
                        "enumeration": "one",
                        "k1": 1,
                        "uint16": 1,
                        "union-list": [16, "chicken"],
                        "uint32": 1,
                        "int32": 1,
                        "int16": 1,
                        "string": "bear",
                        "decimal": Decimal("42.42"),
                        "typedef-two": 8,
                        "uint8": 1,
                        "restricted-integer": 6,
                        "leafref": "16",
                        "int8": 1,
                        "uint64": 1,
                        "int64": 1,
                        "restricted-string": "aardvark",
                    }
                },
                "t1": {"32": {"target": "32"}, "16": {"target": "16"}},
            }
        }
        actual_json = pbJ.load(
            os.path.join(os.path.dirname(__file__), "json", "alltypes.json"),
            self.bindings,
            "json_deserialise",
            path_helper=self.yang_helper,
        ).get(filter=True)

        self.assertEqual(actual_json, expected_json, "Load of object with all items not correct.")
Пример #8
0
    def test_load_full_object(self):
        expected_json = {
            "load-list": {
                "1": {"index": 1, "value": "one"},
                "3": {"index": 3, "value": "three"},
                "2": {"index": 2, "value": "two"},
            }
        }
        # For developers looking for examples, note that the arguments here are:
        #   - the file that we're trying to read
        #   - the bindings module that we generated
        #   - the name of the class within that module
        #   kwargs (path_helper, overwrite, etc.)
        actual_json = pbJ.load(
            os.path.join(os.path.dirname(__file__), "json", "list.json"),
            self.bindings,
            "json_deserialise",
            path_helper=self.yang_helper,
        ).get(filter=True)

        self.assertEqual(actual_json, expected_json, "Whole object load did not return the correct list.")
Пример #9
0
try:
  rt.config.set_tag = "INVALID-TAG"
except ValueError as m:
  print("Cannot set tag: %s" % m)

# Dump the entire instance as JSON in PyangBind format
print(pybindJSON.dumps(oclr))

# Dump the static routes instance as JSON in IETF format
print(pybindJSON.dumps(oclr.local_routes, mode="ietf"))

# Load the "json/oc-lr.json" file into a new instance of
# "openconfig_local_routing". We import the module here, such that a new
# instance of the class can be created by the deserialisation code
import binding
new_oclr = pybindJSON.load(os.path.join("json", "oc-lr.json"), binding,
                              "openconfig_local_routing")

# Manipulate the data loaded
print("Current tag: %d" % 
  new_oclr.local_routes.static_routes.static[u"192.0.2.1/32"].config.set_tag)
new_oclr.local_routes.static_routes.static[u"192.0.2.1/32"].config.set_tag \
                                                                          += 1
print("New tag: %d" % 
  new_oclr.local_routes.static_routes.static[u"192.0.2.1/32"].config.set_tag)

# Load JSON into an existing class structure
from pyangbind.lib.serialise import pybindJSONDecoder
import json

ietf_json = json.load(open(os.path.join("json", "oc-lr_ietf.json"), 'r'))
pybindJSONDecoder.load_ietf_json(ietf_json, None, None,
Пример #10
0
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 += " %s/%s.yang" % (this_dir, TESTNAME)
    os.system(cmd)

    import bindings

    y = YANGPathHelper()

    # For developers looking for examples, note that the arguments here are:
    #   - the file that we're trying to read
    #   - the bindings module that we generated
    #   - the name of the class within that module
    #   kwargs (path_helper, overwrite, etc.)
    whole_obj = pbJ.load(os.path.join(this_dir, "json", "list.json"),
                         bindings,
                         "json_deserialise",
                         path_helper=y)

    expected_whole_obj = {
        'load-list': {
            u'1': {
                'index': 1,
                'value': u'one'
            },
            u'3': {
                'index': 3,
                'value': u'three'
            },
            u'2': {
                'index': 2,
                'value': u'two'
            }
        }
    }
    assert expected_whole_obj == whole_obj.get(filter=True), \
                        "Whole object load did not return the correct list"
    del whole_obj

    js = bindings.json_deserialise(path_helper=y)
    # Load into an existing class
    pbS.pybindJSONDecoder.load_json(json.load(
        open(os.path.join(this_dir, "json", "list-items.json"), 'r')),
                                    None,
                                    None,
                                    obj=js)
    expected_get = {
        'load-list': {
            u'5': {
                'index': 5,
                'value': u'five'
            },
            u'4': {
                'index': 4,
                'value': u'four'
            }
        }
    }
    assert expected_get == js.get(filter=True), \
              "Existing object load did not return the correct list"
    del expected_get

    all_items = pbJ.load(os.path.join(this_dir, "json", "alltypes.json"),
                         bindings,
                         "json_deserialise",
                         path_helper=y)
    expected_get = {
        'c1': {
            'l1': {
                u'1': {
                    'one-leaf': u'hi',
                    'typedef-one': u'test',
                    'boolean': True,
                    'binary': bitarray('111111'),
                    'union': u'16',
                    'identityref': u'idone',
                    'enumeration': u'one',
                    'k1': 1,
                    'uint16': 1,
                    'union-list': [16, u'chicken'],
                    'uint32': 1,
                    'int32': 1,
                    'int16': 1,
                    'string': u'bear',
                    'decimal': Decimal('42.42'),
                    'typedef-two': 8,
                    'uint8': 1,
                    'restricted-integer': 6,
                    'leafref': u'16',
                    'int8': 1,
                    'uint64': 1,
                    'int64': 1,
                    'restricted-string': u'aardvark'
                }
            },
            't1': {
                u'32': {
                    'target': u'32'
                },
                u'16': {
                    'target': u'16'
                }
            }
        }
    }

    assert all_items.get(filter=True) == expected_get, \
              "Load of object with all items not correct"

    del js
    js = pbJ.load(os.path.join(this_dir, "json", "orderedlist-order.json"),
                  bindings,
                  "json_deserialise",
                  path_helper=y)
    assert js.ordered.keys() == ["two", "one"], \
              "Did not correctly load a user ordered list"

    del js
    js = pbJ.load(os.path.join(this_dir, "json", "orderedlist-no-order.json"),
                  bindings,
                  "json_deserialise",
                  path_helper=y)
    assert js.ordered.keys() == ["one", "two"], \
          "Did not correctly follow ordering in JSON file"

    pth = os.path.join(this_dir, "json", "nonexist.json")
    for i in [True, False]:
        nobj = None
        success = True
        try:
            nobj = pybindJSONDecoder.load_ietf_json(json.load(open(pth, 'r')),
                                                    bindings,
                                                    "json_deserialise",
                                                    skip_unknown=i)
        except AttributeError:
            success = False

        assert success is i, "Skipping keys that did not exist was not" + \
          " successfully handled"

    if not k:
        os.system("/bin/rm %s/bindings.py" % this_dir)
        os.system("/bin/rm %s/bindings.pyc" % this_dir)
Пример #11
0
print(nt.node.get(filter=True))
# print(nt.node.port["01"].get(filter=True))

# Add a set of available-cores
for core in [("00", "Core0"), ("01", "Core1")]:
    ac = pl.available_core.add(core[0])
    ac.core_id.available_core = core[1]

# Iterate through the available-cores added
for index, c in pl.available_core.iteritems():
    print("%s: %s" % (index, c.core_id.available_core))

# Dump the entire instance as JSON in PyangBind format
print(pybindJSON.dumps(nt))

# Dump the static routes instance as JSON in IETF format
print(pybindJSON.dumps(nt.node, mode="ietf"))

# Load the "json/oc-lr.json" file into a new instance of
# "openconfig_local_routing". We import the module here, such that a new
# instance of the class can be created by the deserialisation code
import binding

new_nt = pybindJSON.load(os.path.join("json", "nt.json"), binding,
                         "node_topology")

# Manipulate the data loaded
print("Current port: %s" % new_nt.node.port["01"].port_id)
new_nt.node.port["01"].port_id.set_port_id = "02"
print("New port: %s" % new_nt.node.port["01"].port_id.set_port_id)
Пример #12
0
subint0.config.description = "Primary public IP address"
subint0.ipv4.addresses.address.add("192.0.2.1")

nsub = subint0.ipv4.addresses.address["192.0.2.1"]
nsub.config.prefix_length = 24

# Serialise the entire object
# print(pybindJSON.dumps(src_ocif))
pybindJSON.dump(src_ocif, "/tmp/ocif.json")

# Deserialisation from a JSON file
# Arguments are:
#   path to JSON file
#   Python module to find the class in
#   The name of the class
dst_ocif = pybindJSON.load("/tmp/ocif.json", ocbind, "openconfig_interfaces", path_helper=ph)
# print(pybindJSON.dumps(dst_ocif))

src_ocif_json = json.load(open("/tmp/ocif.json", 'r'))

# Deserialisation from a JSON string
# Arguments are:
#   Loaded JSON object
#   Python module to find the class in
#   Name of the class

# In pyangbind 0.3.0 - pybindJSONDecoder becomes a static method - previously
# this should be specified as pybindJSONDecoder().load_json.
dst_ocif_str = pybindJSONDecoder.load_json(src_ocif_json, ocbind, "openconfig_interfaces", path_helper=ph)

# Serialise a particular list entry
Пример #13
0
#!/usr/bin/env python

# flake8: noqa

from __future__ import unicode_literals, print_function
import pprint
import pyangbind.lib.pybindJSON as pbJ
import sbindings
import os

pp = pprint.PrettyPrinter(indent=4)

# Load an instance from file using PyBind's native JSON format
loaded_object = pbJ.load(os.path.join("json", "simple-instance.json"),
                         sbindings, "simple_serialise")
pp.pprint(loaded_object.get(filter=True))

# Load an instance from a corresponding string using the native JSON format
string_to_load = open(os.path.join('json', 'simple-instance.json'), 'r')
string_to_load = string_to_load.read().replace('\n', '')
loaded_object_two = pbJ.loads(string_to_load, sbindings, "simple_serialise")
pp.pprint(loaded_object_two.get(filter=True))

# Load an instance from an IETF-JSON file
loaded_ietf_obj = \
            pbJ.load_ietf(os.path.join("json", "simple-instance-ietf.json"),
                              sbindings, "simple_serialise")
pp.pprint(loaded_ietf_obj.get(filter=True))

# Load an instance from an IETF-JSON string
string_to_load = open(os.path.join('json', 'simple-instance-ietf.json'), 'r')
Пример #14
0
#!/usr/bin/env python

from __future__ import unicode_literals, print_function
import pprint
import pyangbind.lib.pybindJSON as pbJ
import sbindings
import os

pp = pprint.PrettyPrinter(indent=4)

# Load an instance from file using PyBind's native JSON format
loaded_object = pbJ.load(os.path.join("json", "simple-instance.json"), sbindings, "simple_serialise")
pp.pprint(loaded_object.get(filter=True))

# Load an instance from a corresponding string using the native JSON format
string_to_load = open(os.path.join("json", "simple-instance.json"), "r")
string_to_load = string_to_load.read().replace("\n", "")
loaded_object_two = pbJ.loads(string_to_load, sbindings, "simple_serialise")
pp.pprint(loaded_object_two.get(filter=True))

# Load an instance from an IETF-JSON file
loaded_ietf_obj = pbJ.load_ietf(os.path.join("json", "simple-instance-ietf.json"), sbindings, "simple_serialise")
pp.pprint(loaded_ietf_obj.get(filter=True))

# Load an instance from an IETF-JSON string
string_to_load = open(os.path.join("json", "simple-instance-ietf.json"), "r")
string_to_load = string_to_load.read().replace("\n", "")

loaded_ietf_obj_two = pbJ.loads_ietf(string_to_load, sbindings, "simple_serialise")
pp.pprint(loaded_ietf_obj_two.get(filter=True))
Пример #15
0
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 += " %s/%s.yang" % (this_dir, TESTNAME)
  os.system(cmd)

  import bindings

  y = YANGPathHelper()

  # For developers looking for examples, note that the arguments here are:
  #   - the file that we're trying to read
  #   - the bindings module that we generated
  #   - the name of the class within that module
  #   kwargs (path_helper, overwrite, etc.)
  whole_obj = pbJ.load(os.path.join(this_dir, "json", "list.json"), bindings,
                "json_deserialise", path_helper=y)

  expected_whole_obj = {'load-list': {u'1': {'index': 1, 'value': u'one'},
                          u'3': {'index': 3, 'value': u'three'},
                              u'2': {'index': 2, 'value': u'two'}}}
  assert expected_whole_obj == whole_obj.get(filter=True), \
                      "Whole object load did not return the correct list"
  del whole_obj

  js = bindings.json_deserialise(path_helper=y)
  # Load into an existing class
  pbS.pybindJSONDecoder.load_json(json.load(
            open(os.path.join(this_dir, "json", "list-items.json"), 'r')),
              None, None, obj=js)
  expected_get = {'load-list': {u'5': {'index': 5, 'value': u'five'},
                    u'4': {'index': 4, 'value': u'four'}}}
  assert expected_get == js.get(filter=True), \
            "Existing object load did not return the correct list"
  del expected_get

  all_items = pbJ.load(os.path.join(this_dir, "json", "alltypes.json"),
                bindings, "json_deserialise", path_helper=y)
  expected_get = {
      'c1': {
        'l1': {
          u'1': {
            'one-leaf': u'hi',
            'typedef-one': u'test',
            'boolean': True,
            'binary': bitarray('111111'),
            'union': u'16',
            'identityref': u'idone',
            'enumeration': u'one',
            'k1': 1,
            'uint16': 1,
            'union-list': [16, u'chicken'],
            'uint32': 1,
            'int32': 1,
            'int16': 1,
            'string': u'bear',
            'typedef-two': 8,
            'uint8': 1,
            'restricted-integer': 6,
            'leafref': u'16',
            'int8': 1,
            'uint64': 1,
            'int64': 1,
            'restricted-string': u'aardvark'
          }
        },
        't1': {
          u'32': {'target': u'32'},
          u'16': {'target': u'16'}
        }
      }
    }
  assert all_items.get(filter=True) == expected_get, \
            "Load of object with all items not correct"

  del js
  js = pbJ.load(os.path.join(this_dir, "json", "orderedlist-order.json"),
                bindings, "json_deserialise", path_helper=y)
  assert js.ordered.keys() == ["two", "one"], \
            "Did not correctly load a user ordered list"

  del js
  js = pbJ.load(os.path.join(this_dir, "json", "orderedlist-no-order.json"),
                bindings, "json_deserialise", path_helper=y)
  assert js.ordered.keys() == ["one", "two"], \
        "Did not correctly follow ordering in JSON file"

  if not k:
    os.system("/bin/rm %s/bindings.py" % this_dir)
    os.system("/bin/rm %s/bindings.pyc" % this_dir)