From d8618096e31ad9b7b94baf3aba5ef1620eb3edfa Mon Sep 17 00:00:00 2001 From: Jussi Vatjus-Anttila Date: Tue, 6 Oct 2020 12:52:00 +0300 Subject: [PATCH] allow to lazy load resource list file (#5) --- lockable/lockable.py | 17 +++++++++++++++-- tests/test_Lockable.py | 6 ++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/lockable/lockable.py b/lockable/lockable.py index 243681d..62149c1 100644 --- a/lockable/lockable.py +++ b/lockable/lockable.py @@ -47,14 +47,26 @@ class Lockable: Base class for Lockable. It handle low-level functionality. """ def __init__(self, hostname=socket.gethostname(), - resource_list_file="resources.json", + resource_list_file=None, lock_folder=tempfile.gettempdir()): self._resources = dict() self.logger = logging.getLogger('lockable.Lockable') self.logger.debug('Initialized lockable') self._hostname = hostname - self._resource_list = Lockable._read_resources_list(resource_list_file) self._lock_folder = lock_folder + self._resource_list = None + if resource_list_file: + self.load_resources_list(resource_list_file) + else: + self.logger.warning('resource_list_file is not configured') + + def load_resources_list(self, filename: str): + """ Load resources list """ + self._resource_list = self._read_resources_list(filename) + self.logger.debug('Resources: ') + for resource in self._resource_list: + self.logger.debug(json.dumps(resource)) + self.logger.warning('Use resources from %s file', filename) @staticmethod def _read_resources_list(filename): @@ -181,6 +193,7 @@ def lock(self, requirements: (str or dict), timeout_s: int = 1000): :param timeout_s: timeout while trying to lock :return: """ + assert isinstance(self._resource_list, list), 'resources list is not loaded' requirements = self.parse_requirements(requirements) predicate = self._get_requirements(requirements, self._hostname) self.logger.debug("Use lock folder: %s", self._lock_folder) diff --git a/tests/test_Lockable.py b/tests/test_Lockable.py index 3cc8e88..b0e76df 100644 --- a/tests/test_Lockable.py +++ b/tests/test_Lockable.py @@ -20,6 +20,12 @@ def test_constructor(self): fp.write('[]') Lockable(hostname='myhost', resource_list_file=list_file, lock_folder=tmpdirname) + def test_lock_require_resources_json_loaded(self): + lockable = Lockable() + with self.assertRaises(AssertionError) as error: + lockable.lock({}) + self.assertEqual(str(error.exception), 'resources list is not loaded') + def test_constructor_file_not_found(self): with TemporaryDirectory() as tmpdirname: list_file = os.path.join(tmpdirname, 'test.json')