From 01022202715cf611ce49160b88810d945d2488b4 Mon Sep 17 00:00:00 2001 From: Pedro Date: Mon, 6 Nov 2023 11:30:37 +0100 Subject: [PATCH] Add write() method to config and created first tests. --- modem/config.py | 40 ++++++++++++++++++++++++++++++++++++++++ tests/test_config.py | 25 +++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 tests/test_config.py diff --git a/modem/config.py b/modem/config.py index cce08deb..8eb0de7b 100644 --- a/modem/config.py +++ b/modem/config.py @@ -40,6 +40,46 @@ class CONFIG: write values to config """ + # Validates config data + def validate(self, data): + for section in data: + for setting in data[section]: + if section == 'NETWORK': + if setting == 'modemport' and int(data[section][setting]) == 0: + raise Exception("'modemport' should be an integer") + if section == 'STATION': + if setting == 'mycall' and len(data[section][setting]) <= 0: + raise Exception("'%s' can't be empty" % setting) + if setting == 'mygrid' and len(data[section][setting]) <= 0: + raise Exception("'%s' can't be empty" % setting) + if setting == 'ssid_list' and not isinstance(data[section][setting], list): + raise Exception("'%s' needs to be a list" % setting) + # TODO finish this for all config settings! + + # Sets and writes config data from a dict containing data settings + def write(self, data): + + # Validate config data before writing + self.validate(data) + + for section in data: + # init section if it doesn't exist yet + if not section.upper() in self.config.keys(): + self.config[section] = {} + + for setting in data[section]: + self.config[section][setting] = data[section][setting] + + # Write config data to file + try: + with open(self.config_name, 'w') as configfile: + self.config.write(configfile) + return self.config + except Exception as conferror: + self.log.error("[CFG] reading logfile", e=conferror) + return False + + # TODO remove this method when ready def write_entire_config(self, data): """ write entire config diff --git a/tests/test_config.py b/tests/test_config.py new file mode 100644 index 00000000..72c7145a --- /dev/null +++ b/tests/test_config.py @@ -0,0 +1,25 @@ +import unittest +from modem import config + +class TestConfigMethods(unittest.TestCase): + + def test_config_exists(self): + c = config.CONFIG('modem/config.ini') + self.assertTrue(c.config_exists()) + + c = config.CONFIG('modem/nonexistant.ini') + self.assertFalse(c.config_exists()) + + + def test_validate_data(self): + c = config.CONFIG('modem/config.ini') + data = {'NETWORK': {'modemport': "abc"}} + with self.assertRaises(ValueError): + c.validate(data) + + data = {'NETWORK': {'modemport': "3000"}} + self.assertIsNone(c.validate(data)) + + +if __name__ == '__main__': + unittest.main()