Skip to content

Commit

Permalink
allow to lazy load resource list file (#5)
Browse files Browse the repository at this point in the history
  • Loading branch information
jupe authored Oct 6, 2020
1 parent e7612ed commit d861809
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
17 changes: 15 additions & 2 deletions lockable/lockable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions tests/test_Lockable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down

0 comments on commit d861809

Please sign in to comment.