Пример #1
0
def openwrt_edit_config(request):
    device = DBSession.query(OpenWrt).get(request.matchdict['uuid'])
    if not device:
        return exc.HTTPNotFound()
    conf = Uci()
    conf.load_tree(device.configuration);
    if request.POST:
        configsToBeUpdated=[]
        newConfig = {}
        for key, val in request.POST.dict_of_lists().items():
            if key != "submitted":
                val[0] = val[0].replace("'", '"') # for better json recognition
                packagename, configname, optionname = key.split()
                if not (packagename in newConfig.keys()):
                    newConfig[packagename] = {}
                    newConfig[packagename]['values'] = {}
                if not (configname in newConfig[packagename]['values'].keys()):
                    newConfig[packagename]['values'][configname] = {}
                try:
                    savevalue = json.loads(val[0])
                except ValueError:
                    savevalue = val[0]
                newConfig[packagename]['values'][configname][optionname] = savevalue
        newUci = Uci()
        newUci.load_tree(json.dumps(newConfig));
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(conf.diff(newUci));
        device.configuration = newUci.export_json()
        transaction.commit()
        jobtask.update_config.delay(request.matchdict['uuid'])
        return HTTPFound(location=request.route_url('openwrt_list'))
    return{ 'hiddenOptions' : ['.index','.type','.name','.anonymous'],
            'config'        : conf,
           'devicename'     : device.name}
Пример #2
0
 def setUp(self):
     path, filename = os.path.split(os.path.realpath(__file__))
     self.confstring = open(os.path.join(path, 'example_config')).read()
     self.confa = Uci()
     self.confb = Uci()
     self.confa.load_tree(self.confstring)
     self.confb.load_tree(self.confstring)
Пример #3
0
 def setUp(self):
     path, filename = os.path.split(os.path.realpath(__file__))
     self.confstring = open(os.path.join(path, "example_config")).read()
     self.confa = Uci()
     self.confb = Uci()
     self.confa.load_tree(self.confstring)
     self.confb.load_tree(self.confstring)
Пример #4
0
def updateDeviceConfig(masterConfig):
    for device in masterConfig.openwrt:
        uci_conf = Uci()
        uci_conf.load_tree(device.configuration)

        diff = masterConfig.exportUCI().diff(uci_conf)

        if diffChanged(diff):
            device.configuration = masterConfig.exportJSON()
Пример #5
0
    def update_config(device, DBSession):
        file_dir = os.path.dirname(os.path.abspath(__file__))
        filepath = os.path.join(file_dir, str(device.uuid) + ".txt")
        print(filepath)
        if os.path.exists(filepath):
            cur_conf = open(filepath).read()
        else:
            cur_conf = "{}"

        new_configuration = Uci()
        new_configuration.load_tree(device.configuration)

        cur_configuration = Uci()
        cur_configuration.load_tree(cur_conf)
        conf_diff = cur_configuration.diff(new_configuration)
        changed = diffChanged(conf_diff)

        if changed:
            device.append_diff(conf_diff, DBSession, "upload: ")

        print(device.configuration)
        print("going to write file")
        open(filepath, 'w').write(device.configuration)
        print("wrote to file")

        DBSession.commit()
        DBSession.close()
Пример #6
0
def updateMasterConfig(device, newJsonString):
    uci_conf = Uci()
    uci_conf.load_tree(newJsonString)

    if not device.masterconf:
        newMasterConf = masterConfigFromUci(uci_conf)
        newMasterConf.openwrt.append(device)
        return

    diff = device.masterconf.exportUCI().diff(uci_conf)

    if diffChanged(diff):
        newMasterConf = masterConfigFromUci(uci_conf)
        if device.masterconf:
            deleteMasterConf(device.masterconf)
        newMasterConf.openwrt.append(device)
    def get_config(device, DBSession):

        try:
            if device.configured:
                newConf = return_jsonconfig_from_device(device)

                newUci = Uci()
                newUci.load_tree(newConf)

                oldUci = Uci()
                oldUci.load_tree(device.configuration)

                diff = oldUci.diff(newUci)

                if diffChanged(diff):
                    device.append_diff(diff, DBSession, "download: ")
                    device.configuration = newConf
            else:
                device.configuration = return_jsonconfig_from_device(device)
                device.configured = True

            DBSession.commit()
            return True
        except Exception as thrownexpt:
            print(thrownexpt)
            device.configured = False
            DBSession.commit()
            return False
Пример #8
0
def update_config(uuid):
    DBSession = get_sql_session()
    device = DBSession.query(OpenWrt).get(uuid)
    new_configuration = Uci()
    new_configuration.load_tree(device.configuration)
    device_url = "http://" + device.address + "/ubus"
    cur_configuration = Uci()
    cur_configuration.load_tree(
        return_config_from_node_as_json(device_url, device.login,
                                        device.password))
    conf_diff = cur_configuration.diff(new_configuration)
    update_diff_conf = signature('openwifi.jobserver.tasks.diff_update_config',
                                 args=(conf_diff, device_url, device.login,
                                       device.password))
    DBSession.commit()
    DBSession.close()
    update_diff_conf.delay()
    def config_differs_device(device, DBSession, config):
        if config == None:
            return True

        new_configuration = Uci()
        new_configuration.load_tree(config)

        cur_configuration = Uci()
        cur_configuration.load_tree(return_jsonconfig_from_device(device))
        conf_diff = cur_configuration.diff(new_configuration)

        return diffChanged(conf_diff), conf_diff
Пример #10
0
def archive_edit_config(request):
    archiveConfig = DBSession.query(ConfigArchive).get(request.matchdict['id'])
    if not archiveConfig:
        return exc.HTTPNotFound()
    device = DBSession.query(OpenWrt).get(archiveConfig.router_uuid)
    if not device:
        return exc.HTTPNotFound()
    conf = Uci()
    conf.load_tree(archiveConfig.configuration);
    if request.POST:
        configsToBeUpdated=[]
        newConfig = {}
        for key, val in request.POST.dict_of_lists().items():
            if key != "submitted":
                val[0] = val[0].replace("'", '"') # for better json recognition
                packagename, configname, optionname = key.split()
                if not (packagename in newConfig.keys()):
                    newConfig[packagename] = {}
                    newConfig[packagename]['values'] = {}
                if not (configname in newConfig[packagename]['values'].keys()):
                    newConfig[packagename]['values'][configname] = {}
                try:
                    savevalue = json.loads(val[0])
                except ValueError:
                    savevalue = val[0]
                newConfig[packagename]['values'][configname][optionname] = savevalue
        confToBeArchivedNew = ConfigArchive(datetime.now(),
                                            json.dumps(newConfig),
                                            archiveConfig.router_uuid,
                                            id_generator())
        DBSession.add(confToBeArchivedNew)
        return HTTPFound(location=request.route_url('confarchive'))
    return{ 'hiddenOptions' : ['.index','.type','.name','.anonymous'],
            'config'        : conf,
            'routerName'    : device.name,
            'date'          : archiveConfig.date}
Пример #11
0
    def get_config(device, DBSession):
        file_dir = os.path.dirname(os.path.abspath(__file__))
        filepath = os.path.join(file_dir, str(device.uuid) + ".txt")
        print(filepath)
        try:
            if os.path.exists(filepath):
                newConf = open(filepath).read()
            else:
                newConf = ""

            if device.configured:

                newUci = Uci()
                newUci.load_tree(newConf)

                oldUci = Uci()
                oldUci.load_tree(device.configuration)

                diff = oldUci.diff(newUci)

                if diffChanged(diff):
                    device.append_diff(diff, DBSession, "download: ")
                    device.configuration = newConf
            else:
                device.configuration = newConf
                device.configured = True

            DBSession.commit()
            DBSession.close()
            return True
        except Exception as thrownexpt:
            print(thrownexpt)
            device.configured = False
            DBSession.commit()
            DBSession.close()
            return False
Пример #12
0
def update_template(openwrtConfJSON, templateJSON):
    openwrt_config = Uci()
    openwrt_config.load_tree(openwrtConfJSON)
    metaconf = json.loads(templateJSON)['metaconf']
    for package in metaconf['change']['add']:  # packages to be added
        if package not in openwrt_config.packages.keys():
            openwrt_config.add_package(package)
    for package in metaconf['change']['del']:  # packages to be deleted
        if package in openwrt_config.packages.keys():
            openwrt_config.packages.pop(package)
    packages = metaconf['packages']
    for package_match in packages:
        if not package_match['type'] == 'package':
            raise MetaconfWrongFormat('first level should be type: \
                     package, but found: ' + cur_package_match['type'])
        package = package_match['matchvalue']
        # scan for packages to be added and add
        for config in package_match['change']['add']:
            nameMismatch = True
            typeMismatch = True
            # match names
            if config[0] in openwrt_config.packages[package].keys():
                nameMismatch = False
            # match types
            for confname, conf in openwrt_config.packages[package].items():
                if conf.uci_type == config[1]:
                    typeMismatch = False
                    break
            if (config[2] == 'always') or\
               (config[2] == 'typeMismatch' and typeMismatch) or\
               (config[2] == 'nameMismatch' and nameMismatch) or\
               (config[2] == 'bothMismatch' and typeMismatch and nameMismatch):
                openwrt_config.packages[package][config[0]] = Config(
                    config[1], config[0],
                    config[0] == '')  #Config(ucitype, name, anon)
        # scan for packages to be removed and delete
        for config in package_match['change']['del']:
            confmatch = config[2]
            # match names
            if config[0] in openwrt_config.packages[package].keys():
                if confmatch == 'always' or confmatch == 'nameMatch':
                    openwrt_config.packages[package].pop(config[0])
            # match types
            for confname, conf in openwrt_config.packages[package].items():
                if conf.uci_type == config[1]:
                    if confmatch == 'always' or confmatch == 'typeMatch':
                        openwrt_config.packages[package].pop(confname)
                    if confmatch == 'bothMatch' and confname == conf[0]:
                        openwrt_config.packages[package].pop(confname)
        # go into config matches
        for conf_match in package_match['config']:
            matched_configs = []
            configs_to_be_matched = list(
                openwrt_config.packages[package].values())
            while conf_match != '' and configs_to_be_matched:
                for config in configs_to_be_matched:
                    if conf_match['matchtype'] == 'name':
                        if config.name == conf_match['matchvalue']:
                            matched_configs.append(config)
                    if conf_match['matchtype'] == 'type':
                        if config.uci_type == conf_match['ucitype']:
                            matched_configs.append(config)
                for mconfig in matched_configs:
                    for option in conf_match['change']['add']:
                        mconfig.keys[option[0]] = option[1]
                    for option in conf_match['change']['del']:
                        try:
                            mconfig.keys.pop(option)
                        except KeyError:
                            pass
                configs_to_be_matched = matched_configs
                conf_match = conf_match['next']
    return openwrt_config
Пример #13
0
def parseToDBModel(device):
    uci_conf = Uci()
    uci_conf.load_tree(device.configuration)

    newMasterConf = masterConfigFromUci(uci_conf)
    newMasterConf.openwrt.append(device)
Пример #14
0
class TestSetup(unittest.TestCase):
    def setUp(self):
        path, filename = os.path.split(os.path.realpath(__file__))
        self.confstring = open(os.path.join(path, "example_config")).read()
        self.confa = Uci()
        self.confb = Uci()
        self.confa.load_tree(self.confstring)
        self.confb.load_tree(self.confstring)

    def test_sameconfig(self):
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {}
        assert result["newconfigs"] == {}
        assert result["oldpackages"] == {}
        assert result["oldconfigs"] == {}
        assert result["newOptions"] == {}
        assert result["oldOptions"] == {}
        assert result["chaOptions"] == {}

    def test_missing_package_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        self.confa.packages.pop(removed_key)
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {removed_key: self.confb.packages[removed_key]}
        assert result["newconfigs"] == {}
        assert result["oldpackages"] == {}
        assert result["oldconfigs"] == {}
        assert result["newOptions"] == {}
        assert result["oldOptions"] == {}
        assert result["chaOptions"] == {}

    def test_missing_package_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        self.confb.packages.pop(removed_key)
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {}
        assert result["newconfigs"] == {}
        assert result["oldpackages"] == {removed_key: self.confa.packages[removed_key]}
        assert result["oldconfigs"] == {}
        assert result["newOptions"] == {}
        assert result["oldOptions"] == {}
        assert result["chaOptions"] == {}

    def test_missing_config_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        self.confa.packages[removed_key].pop(removed_conf)
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {}
        assert result["newconfigs"] == {(removed_key, removed_conf): self.confb.packages[removed_key][removed_conf]}
        assert result["oldpackages"] == {}
        assert result["oldconfigs"] == {}
        assert result["newOptions"] == {}
        assert result["oldOptions"] == {}
        assert result["chaOptions"] == {}

    def test_missing_config_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        self.confb.packages[removed_key].pop(removed_conf)
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {}
        assert result["newconfigs"] == {}
        assert result["oldpackages"] == {}
        assert result["oldconfigs"] == {(removed_key, removed_conf): self.confa.packages[removed_key][removed_conf]}
        assert result["newOptions"] == {}
        assert result["oldOptions"] == {}
        assert result["chaOptions"] == {}

    def test_missing_option_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = self.confa.packages[removed_key][
            removed_conf
        ].keys.pop(removed_option)
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {}
        assert result["newconfigs"] == {}
        assert result["oldpackages"] == {}
        assert result["oldconfigs"] == {}
        assert result["oldOptions"] == {}
        print(result["chaOptions"])
        assert result["chaOptions"] == {}
        print(result["oldOptions"])
        print(removed_option_dict)
        assert result["newOptions"] == removed_option_dict

    def test_missing_option_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = self.confb.packages[removed_key][
            removed_conf
        ].keys.pop(removed_option)
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {}
        assert result["newconfigs"] == {}
        assert result["oldpackages"] == {}
        assert result["oldconfigs"] == {}
        assert result["newOptions"] == {}
        print(result["chaOptions"])
        assert result["chaOptions"] == {}
        print(result["oldOptions"])
        print(removed_option_dict)
        assert result["oldOptions"] == removed_option_dict

    def test_changed_option_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = (
            self.confa.packages[removed_key][removed_conf].keys.get(removed_option),
            str(self.confa.packages[removed_key][removed_conf].keys.get(removed_option)) + "changed",
        )
        self.confb.packages[removed_key][removed_conf].keys[removed_option] = (
            str(self.confa.packages[removed_key][removed_conf].keys.get(removed_option)) + "changed"
        )
        result = self.confa.diff(self.confb)
        assert result["newpackages"] == {}
        assert result["newconfigs"] == {}
        assert result["oldpackages"] == {}
        assert result["oldconfigs"] == {}
        assert result["newOptions"] == {}
        assert result["oldOptions"] == {}
        print(self.confa.packages[removed_key][removed_conf].keys[removed_option])
        print(self.confb.packages[removed_key][removed_conf].keys[removed_option])
        print(self.confa.packages[removed_key][removed_conf].export_dict(forjson=True))
        print(self.confb.packages[removed_key][removed_conf].export_dict(forjson=True))
        print(result["chaOptions"])
        print(removed_option_dict)
        assert result["chaOptions"] == removed_option_dict
Пример #15
0
class TestSetup(unittest.TestCase):
    def setUp(self):
        self.maxDiff = None
        path,filename = os.path.split(os.path.realpath(__file__))
        self.confstring = open(os.path.join(path,'example_config')).read()
        self.confa = Uci()
        self.confb = Uci()
        self.confa.load_tree(self.confstring)
        self.confb.load_tree(self.confstring)

    def test_sameconfig(self):
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {})
        self.assertEqual(result['newconfigs'], {})
        self.assertEqual(result['oldpackages'], {})
        self.assertEqual(result['oldconfigs'], {})
        self.assertEqual(result['newOptions'], {})
        self.assertEqual(result['oldOptions'], {})
        self.assertEqual(result['chaOptions'], {})

        jsonExport = result.exportJson()
        self.assertEqual(json.loads(jsonExport), json.loads('{"newpackages": {}, "oldpackages": {}, "newconfigs": {}, "oldconfigs": {}, "newOptions": {}, "oldOptions": {}, "chaOptions": {}}'))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)

    def test_missing_package_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        self.confa.packages.pop(removed_key)
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {removed_key: self.confb.packages[removed_key]})
        self.assertEqual(result['newconfigs'], {})
        self.assertEqual(result['oldpackages'], {})
        self.assertEqual(result['oldconfigs'], {})
        self.assertEqual(result['newOptions'], {})
        self.assertEqual(result['oldOptions'], {})
        self.assertEqual(result['chaOptions'], {})

        jsonExport = result.exportJson()
        packageJsonString = json.dumps(self.confb.packages[removed_key].exportDictForJson())
        expected = '{"newpackages": '
        expected += '{"' + removed_key + '": ' + packageJsonString + '}'
        expected += ', "oldpackages": {}, "newconfigs": {}, "oldconfigs": {}, "newOptions": {}, "oldOptions": {}, "chaOptions": {}}'
        self.assertEqual(json.loads(jsonExport), json.loads(expected))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)

    def test_missing_package_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        self.confb.packages.pop(removed_key)
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {})
        self.assertEqual(result['newconfigs'], {})
        self.assertEqual(result['oldpackages'], {removed_key: self.confa.packages[removed_key]})
        self.assertEqual(result['oldconfigs'], {})
        self.assertEqual(result['newOptions'], {})
        self.assertEqual(result['oldOptions'], {})
        self.assertEqual(result['chaOptions'], {})

        packageJsonString = json.dumps(self.confa.packages[removed_key].exportDictForJson())
        expected = '{"newpackages": {}, "oldpackages": '
        expected += '{"' + removed_key + '": ' + packageJsonString + '}'
        expected += ', "newconfigs": {}, "oldconfigs": {}, "newOptions": {}, "oldOptions": {}, "chaOptions": {}}'
        jsonExport = result.exportJson()
        self.assertEqual(json.loads(jsonExport), json.loads(expected))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)

    def test_missing_config_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        self.confa.packages[removed_key].pop(removed_conf)
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {})
        self.assertEqual(result['newconfigs'], {(removed_key, removed_conf): self.confb.packages[removed_key][removed_conf]})
        self.assertEqual(result['oldpackages'], {})
        self.assertEqual(result['oldconfigs'], {})
        self.assertEqual(result['newOptions'], {})
        self.assertEqual(result['oldOptions'], {})
        self.assertEqual(result['chaOptions'], {})

        jsonExport = result.exportJson()
        configJsonString = json.dumps(self.confb.packages[removed_key][removed_conf].export_dict(forjson=True))
        expected = '{"newpackages": {}, "oldpackages": {}, "newconfigs": '
        expected += '{"' + removed_conf + '": {"value": ' + configJsonString + ', "package": "' + removed_key + '"}}'
        expected += ', "oldconfigs": {}, "newOptions": {}, "oldOptions": {}, "chaOptions": {}}'
        self.assertEqual(json.loads(jsonExport), json.loads(expected))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)

    def test_missing_config_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        self.confb.packages[removed_key].pop(removed_conf)
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {})
        self.assertEqual(result['newconfigs'], {})
        self.assertEqual(result['oldpackages'], {})
        self.assertEqual(result['oldconfigs'], {(removed_key, removed_conf): self.confa.packages[removed_key] [removed_conf]})
        self.assertEqual(result['newOptions'], {})
        self.assertEqual(result['oldOptions'], {})
        self.assertEqual(result['chaOptions'], {})

        jsonExport = result.exportJson()
        configJsonString = json.dumps(self.confa.packages[removed_key][removed_conf].export_dict(forjson=True))
        expected = '{"newpackages": {}, "oldpackages": {}, "newconfigs": {}, "oldconfigs": '
        expected += '{"' + removed_conf + '": {"value": ' + configJsonString + ', "package": "' + removed_key + '"}}'
        expected += ', "newOptions": {}, "oldOptions": {}, "chaOptions": {}}'
        self.assertEqual(json.loads(jsonExport), json.loads(expected))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)

    def test_missing_option_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = \
            list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = \
            self.confa.packages[removed_key][removed_conf].keys.pop(removed_option)
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {})
        self.assertEqual(result['newconfigs'], {})
        self.assertEqual(result['oldpackages'], {})
        self.assertEqual(result['oldconfigs'], {})
        self.assertEqual(result['oldOptions'], {})
        self.assertEqual(result['chaOptions'], {})
        self.assertEqual(result['newOptions'], removed_option_dict)

        jsonExport = result.exportJson()
        removedOptVal = removed_option_dict[(removed_key, removed_conf, removed_option)]
        expected = '{"newpackages": {}, "oldpackages": {}, "newconfigs": {}, "oldconfigs": {}, "newOptions": {"'
        expected += removed_option+ '": {"value": "' + removedOptVal + '", "package": "' + removed_key + '", "config": "' + removed_conf + '"'
        expected += '}}, "oldOptions": {}, "chaOptions": {}}'
        self.assertEqual(json.loads(jsonExport), json.loads(expected))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)

    def test_missing_option_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = \
            list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = \
                self.confb.packages[removed_key][removed_conf].keys.pop(removed_option)
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {})
        self.assertEqual(result['newconfigs'], {})
        self.assertEqual(result['oldpackages'], {})
        self.assertEqual(result['oldconfigs'], {})
        self.assertEqual(result['newOptions'], {})
        self.assertEqual(result['chaOptions'], {})
        self.assertEqual(result['oldOptions'], removed_option_dict)

        jsonExport = result.exportJson()
        removedOptVal = removed_option_dict[(removed_key, removed_conf, removed_option)]
        expected = '{"newpackages": {}, "oldpackages": {}, "newconfigs": {}, "oldconfigs": {}, "newOptions": {}, "oldOptions": {"'
        expected += removed_option+ '": {"value": "' + removedOptVal + '", "package": "' + removed_key + '", "config": "' + removed_conf + '"'
        expected += '}}, "chaOptions": {}}'
        self.assertEqual(json.loads(jsonExport), json.loads(expected))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)

    def test_changed_option_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = \
            list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = \
            (self.confa.packages[removed_key][removed_conf].keys.get(removed_option),\
            str(self.confa.packages[removed_key][removed_conf].keys.get(removed_option))\
            + 'changed')
        self.confb.packages[removed_key][removed_conf].keys[removed_option] = \
            str(self.confa.packages[removed_key][removed_conf].keys.get(removed_option))\
            + 'changed'
        result = self.confa.diff(self.confb)
        self.assertEqual(result['newpackages'], {})
        self.assertEqual(result['newconfigs'], {})
        self.assertEqual(result['oldpackages'], {})
        self.assertEqual(result['oldconfigs'], {})
        self.assertEqual(result['newOptions'], {})
        self.assertEqual(result['oldOptions'], {})
        self.assertEqual(result['chaOptions'], removed_option_dict)

        jsonExport = result.exportJson()
        removedOptVal = removed_option_dict[(removed_key, removed_conf, removed_option)]
        expected = '{"newpackages": {}, "oldpackages": {}, "newconfigs": {}, "oldconfigs": {}, "newOptions": {}, "oldOptions": {}, "chaOptions": {"'
        expected += removed_option + '": {"value": ' + json.dumps(removedOptVal) + ', "package": "' + removed_key + '", "config": "' + removed_conf + '"'
        expected += '}}}'
        self.assertEqual(json.loads(jsonExport), json.loads(expected))
        importTest = Diff()
        importTest.importJson(jsonExport)
        self.assertEqual(importTest, result)

        result.apply(self.confa)
        self.assertEqual(self.confa, self.confb)
        result.revert(self.confa)
        self.assertEqual(self.confa.diff(self.confb), result)
Пример #16
0
class TestSetup(unittest.TestCase):
    def setUp(self):
        path, filename = os.path.split(os.path.realpath(__file__))
        self.confstring = open(os.path.join(path, 'example_config')).read()
        self.confa = Uci()
        self.confb = Uci()
        self.confa.load_tree(self.confstring)
        self.confb.load_tree(self.confstring)

    def test_sameconfig(self):
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {}
        assert result['newconfigs'] == {}
        assert result['oldpackages'] == {}
        assert result['oldconfigs'] == {}
        assert result['newOptions'] == {}
        assert result['oldOptions'] == {}
        assert result['chaOptions'] == {}

    def test_missing_package_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        self.confa.packages.pop(removed_key)
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {
            removed_key: self.confb.packages[removed_key]
        }
        assert result['newconfigs'] == {}
        assert result['oldpackages'] == {}
        assert result['oldconfigs'] == {}
        assert result['newOptions'] == {}
        assert result['oldOptions'] == {}
        assert result['chaOptions'] == {}

    def test_missing_package_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        self.confb.packages.pop(removed_key)
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {}
        assert result['newconfigs'] == {}
        assert result['oldpackages'] == {
            removed_key: self.confa.packages[removed_key]
        }
        assert result['oldconfigs'] == {}
        assert result['newOptions'] == {}
        assert result['oldOptions'] == {}
        assert result['chaOptions'] == {}

    def test_missing_config_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        self.confa.packages[removed_key].pop(removed_conf)
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {}
        assert result['newconfigs'] == {
            (removed_key, removed_conf):
            self.confb.packages[removed_key][removed_conf]
        }
        assert result['oldpackages'] == {}
        assert result['oldconfigs'] == {}
        assert result['newOptions'] == {}
        assert result['oldOptions'] == {}
        assert result['chaOptions'] == {}

    def test_missing_config_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        self.confb.packages[removed_key].pop(removed_conf)
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {}
        assert result['newconfigs'] == {}
        assert result['oldpackages'] == {}
        assert result['oldconfigs'] == {
            (removed_key, removed_conf):
            self.confa.packages[removed_key][removed_conf]
        }
        assert result['newOptions'] == {}
        assert result['oldOptions'] == {}
        assert result['chaOptions'] == {}

    def test_missing_option_in_oldconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = \
            list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = \
            self.confa.packages[removed_key][removed_conf].keys.pop(removed_option)
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {}
        assert result['newconfigs'] == {}
        assert result['oldpackages'] == {}
        assert result['oldconfigs'] == {}
        assert result['oldOptions'] == {}
        print(result['chaOptions'])
        assert result['chaOptions'] == {}
        print(result['oldOptions'])
        print(removed_option_dict)
        assert result['newOptions'] == removed_option_dict

    def test_missing_option_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = \
            list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = \
                self.confb.packages[removed_key][removed_conf].keys.pop(removed_option)
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {}
        assert result['newconfigs'] == {}
        assert result['oldpackages'] == {}
        assert result['oldconfigs'] == {}
        assert result['newOptions'] == {}
        print(result['chaOptions'])
        assert result['chaOptions'] == {}
        print(result['oldOptions'])
        print(removed_option_dict)
        assert result['oldOptions'] == removed_option_dict

    def test_changed_option_in_newconf(self):
        removed_key = list(self.confa.packages.keys())[0]
        removed_conf = list(self.confa.packages[removed_key].keys())[0]
        removed_option = \
            list(self.confa.packages[removed_key][removed_conf].keys.keys())[0]
        removed_option_dict = dict()
        removed_option_dict[(removed_key, removed_conf, removed_option)] = \
            (self.confa.packages[removed_key][removed_conf].keys.get(removed_option),\
            str(self.confa.packages[removed_key][removed_conf].keys.get(removed_option))\
            + 'changed')
        self.confb.packages[removed_key][removed_conf].keys[removed_option] = \
            str(self.confa.packages[removed_key][removed_conf].keys.get(removed_option))\
            + 'changed'
        result = self.confa.diff(self.confb)
        assert result['newpackages'] == {}
        assert result['newconfigs'] == {}
        assert result['oldpackages'] == {}
        assert result['oldconfigs'] == {}
        assert result['newOptions'] == {}
        assert result['oldOptions'] == {}
        print(self.confa.packages[removed_key]
              [removed_conf].keys[removed_option])
        print(self.confb.packages[removed_key]
              [removed_conf].keys[removed_option])
        print(self.confa.packages[removed_key][removed_conf].export_dict(
            forjson=True))
        print(self.confb.packages[removed_key][removed_conf].export_dict(
            forjson=True))
        print(result['chaOptions'])
        print(removed_option_dict)
        assert result['chaOptions'] == removed_option_dict