Exemplo n.º 1
0
class config:
    '''Alfred VPN workflow configuration management'''
    __wf = None
    __config = None
    __is_init = False

    def __init__(self, wf):
        self.__wf = wf
        self.__config = Settings('./config.json')

        log = self.__wf.logger
        func_name = self.__init__.__name__

        log.info("%s reading configuration", func_name)

        if len(self.__config) is not 0:
            log.info("%s configuration read OK", func_name)
            self.__is_init = True

    def get_field(self, field):
        '''Get configuration field'''
        if self.__is_init is False:
            return None

        return self.__config[field]

    def set_field(self, field, value):
        '''Set configuration field'''
        if self.__is_init is False:
            return False

        self.__config[field] = value
        self.__config.save()
        return True
 def test_delete_settings(self):
     """Settings deleted"""
     s = Settings(self.settings_file)
     self.assertEqual(s['key1'], DEFAULT_SETTINGS['key1'])
     del s['key1']
     s2 = Settings(self.settings_file)
     self.assertEqual(s2.get('key1'), None)
 def test_save_settings(self):
     """Settings saved"""
     s = Settings(self.settings_file)
     self.assertEqual(s['key1'], DEFAULT_SETTINGS['key1'])
     s['key1'] = 'spoons!'
     s2 = Settings(self.settings_file)
     self.assertEqual(s['key1'], s2['key1'])
 def test_delete_settings(self):
     """Settings deleted"""
     s = Settings(self.settings_file)
     self.assertEqual(s['key1'], DEFAULT_SETTINGS['key1'])
     del s['key1']
     s2 = Settings(self.settings_file)
     self.assertEqual(s2.get('key1'), None)
 def test_save_settings(self):
     """Settings saved"""
     s = Settings(self.settings_file)
     self.assertEqual(s["key1"], DEFAULT_SETTINGS["key1"])
     s["key1"] = "spoons!"
     s2 = Settings(self.settings_file)
     self.assertEqual(s["key1"], s2["key1"])
Exemplo n.º 6
0
def test_concurrent_settings(paths):
    """Concurrent access to Settings is serialised."""
    assert not os.path.exists(paths.testfile)
    assert not os.path.exists(paths.lockfile)

    defaults = {'foo': 'bar'}
    # initialise file
    Settings(paths.testfile, defaults)

    data = [(paths, 'thread_{0}'.format(i), 'value_{0}'.format(i))
            for i in range(1, 10)]

    pool = Pool(5)
    errs = pool.map(_write_settings, data)
    errs = [e for e in errs if e is not None]

    assert errs == []

    # Check settings file is still valid JSON
    # and that *something* was added to it.
    # The writing processes will have trampled
    # over each other, so there's no way to know
    # which one won and wrote its value.
    s = Settings(paths.testfile)
    assert s['foo'] == 'bar'
    assert len(s) > 1
 def test_dict_methods(self):
     """Settings dict methods"""
     other = {'key1': 'spoons!'}
     s = Settings(self.settings_file)
     self.assertEqual(s['key1'], DEFAULT_SETTINGS['key1'])
     s.update(other)
     s.setdefault('alist', [])
     s2 = Settings(self.settings_file)
     self.assertEqual(s['key1'], s2['key1'])
     self.assertEqual(s['key1'], 'spoons!')
     self.assertEqual(s2['alist'], [])
Exemplo n.º 8
0
 def test_dict_methods(self):
     """Settings dict methods"""
     other = {"key1": "spoons!"}
     s = Settings(self.settings_file)
     self.assertEqual(s["key1"], DEFAULT_SETTINGS["key1"])
     s.update(other)
     s.setdefault("alist", [])
     s2 = Settings(self.settings_file)
     self.assertEqual(s["key1"], s2["key1"])
     self.assertEqual(s["key1"], "spoons!")
     self.assertEqual(s2["alist"], [])
 def test_mutable_objects_updated(self):
     """Updated mutable objects cause save"""
     s = Settings(self.settings_file)
     mt1 = os.path.getmtime(self.settings_file)
     time.sleep(1)
     seq = s['mutable1']
     seq.append('another string')
     s['mutable1'] = seq
     mt2 = os.path.getmtime(self.settings_file)
     self.assertTrue(mt2 > mt1)
     s2 = Settings(self.settings_file)
     self.assertTrue('another string' in s2['mutable1'])
Exemplo n.º 10
0
    def __init__(self, wf):
        self.__wf = wf
        self.__config = Settings('./config.json')

        log = self.__wf.logger
        func_name = self.__init__.__name__

        log.info("%s reading configuration", func_name)

        if len(self.__config) is not 0:
            log.info("%s configuration read OK", func_name)
            self.__is_init = True
 def test_settings_not_rewritten(self):
     """Settings not rewritten for same value"""
     s = Settings(self.settings_file)
     mt = os.path.getmtime(self.settings_file)
     time.sleep(1)  # wait long enough to register changes in `time.time()`
     now = time.time()
     for k, v in DEFAULT_SETTINGS.items():
         s[k] = v
     self.assertTrue(os.path.getmtime(self.settings_file) == mt)
     s['finished_at'] = now
     s2 = Settings(self.settings_file)
     self.assertEqual(s['finished_at'], s2['finished_at'])
     self.assertTrue(os.path.getmtime(self.settings_file) > mt)
Exemplo n.º 12
0
def _write_settings(args):
    """Write a new value to the Settings."""
    paths, key, value = args
    try:
        s = Settings(paths.testfile)
        s[key] = value
        print('Settings[{0}] = {1}'.format(key, value))
    except Exception as err:
        print('error opening settings (%s): %s' %
              (key, traceback.format_exc()),
              file=sys.stderr)
        return err
 def test_dict_methods(self):
     """Settings dict methods"""
     other = {'key1': 'spoons!'}
     s = Settings(self.settings_file)
     self.assertEqual(s['key1'], DEFAULT_SETTINGS['key1'])
     s.update(other)
     s.setdefault('alist', [])
     s2 = Settings(self.settings_file)
     self.assertEqual(s['key1'], s2['key1'])
     self.assertEqual(s['key1'], 'spoons!')
     self.assertEqual(s2['alist'], [])
 def test_dict_methods(self):
     """Settings dict methods"""
     other = {"key1": "spoons!"}
     s = Settings(self.settings_file)
     self.assertEqual(s["key1"], DEFAULT_SETTINGS["key1"])
     s.update(other)
     s.setdefault("alist", [])
     s2 = Settings(self.settings_file)
     self.assertEqual(s["key1"], s2["key1"])
     self.assertEqual(s["key1"], "spoons!")
     self.assertEqual(s2["alist"], [])
Exemplo n.º 15
0
    def testConcurrentAccess(self):
        """Locked Settings: Concurrent access"""
        def save_data(key, value):
            settings = Settings(self.settings_path, self.defaults)
            settings[key] = value

        threads = []
        for i in range(1, 5):
            t = threading.Thread(target=functools.partial(
                save_data, 'thread_{0}'.format(i), 'value_{0}'.format(i)))
            threads.append(t)

        for t in threads:
            t.start()

        for t in threads:
            t.join()

        settings = Settings(self.settings_path)
        print(settings)
Exemplo n.º 16
0
def _write_settings(args):
    """Write a new value to the Settings."""
    paths, key, value = args
    s = Settings(paths.testfile)
    s[key] = value
    print('Settings[{0}] = {1}'.format(key, value))
 def test_load_settings(self):
     """Load saved settings"""
     s = Settings(self.settings_file, {'key1': 'value2'})
     for key in DEFAULT_SETTINGS:
         self.assertEqual(DEFAULT_SETTINGS[key], s[key])
 def test_defaults(self):
     """Default settings"""
     if os.path.exists(self.settings_file):
         os.unlink(self.settings_file)
     s = Settings(self.settings_file, {'key1': 'value2'})
     self.assertEqual(s['key1'], 'value2')
Exemplo n.º 19
0
 def save_data(key, value):
     settings = Settings(self.settings_path, self.defaults)
     settings[key] = value
Exemplo n.º 20
0
 def setUp(self):
     self.tempdir = tempfile.mkdtemp()
     self.settings_path = os.path.join(self.tempdir, 'settings.json')
     self.defaults = {'foo': 'bar'}
     Settings(self.settings_path, self.defaults)
 def test_defaults(self):
     """Default settings"""
     if os.path.exists(self.settings_file):
         os.unlink(self.settings_file)
     s = Settings(self.settings_file, {"key1": "value2"})
     self.assertEqual(s["key1"], "value2")
Exemplo n.º 22
0
 def __init__(self):
     self.langs = Settings(ITCConfig.ITC_CONFIG_FILE_NAME)
Exemplo n.º 23
0
 def __init__(self):
     settings = Settings(Const.APPLICATION_CONFIG_FILE_NAME,
                         Const.DEFAULT_CONFIG)
     self.itc = settings[Const.ITC]
     self.num = settings[Const.NUMBER]
Exemplo n.º 24
0
 def load_application_settings():
     return Settings(Const.APPLICATION_CONFIG_FILE_NAME,
                     Const.DEFAULT_CONFIG)