diff --git a/lockable/lockable.py b/lockable/lockable.py index 5ced918..680dd0f 100644 --- a/lockable/lockable.py +++ b/lockable/lockable.py @@ -56,6 +56,7 @@ class Lockable: """ def __init__(self, hostname=socket.gethostname(), resource_list_file=None, + resource_list=None, lock_folder=tempfile.gettempdir()): self._allocations = dict() self.logger = logging.getLogger('lockable.Lockable') @@ -63,18 +64,29 @@ def __init__(self, hostname=socket.gethostname(), self._hostname = hostname self._lock_folder = lock_folder self._resource_list = None - if resource_list_file: - self.load_resources_list(resource_list_file) + assert not (isinstance(resource_list, list) and + resource_list_file), 'only one of resource_list or ' \ + 'resource_list_file is accepted, not both' + if isinstance(resource_list_file, str): + self.load_resources_list_file(resource_list_file) + elif isinstance(resource_list, list): + self.load_resources_list(resource_list) else: - self.logger.warning('resource_list_file is not configured') + self.logger.warning('resource_list_file or resource_list is not configured') - def load_resources_list(self, filename: str): + def load_resources_list_file(self, filename: str): + """ Load resources list file""" + self.load_resources_list(self._read_resources_list(filename)) + self.logger.warning('Use resources from %s file', filename) + + def load_resources_list(self, resources_list: list): """ Load resources list """ - self._resource_list = self._read_resources_list(filename) - self.logger.debug('Resources: ') + assert isinstance(resources_list, list), 'resources_list is not an list' + self._resource_list = resources_list + self.logger.debug('Resources loaded: ') 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): diff --git a/tests/test_Lockable.py b/tests/test_Lockable.py index 85f57a9..664243a 100644 --- a/tests/test_Lockable.py +++ b/tests/test_Lockable.py @@ -12,10 +12,7 @@ def create_lockable(data=[{"id": 1, "hostname": "myhost", "online": True}], lock_folder=None): with TemporaryDirectory() as tmpdirname: lock_folder = lock_folder or tmpdirname - list_file = os.path.join(tmpdirname, 'test.json') - with open(list_file, 'w') as fp: - fp.write(json.dumps(data)) - yield Lockable(hostname='myhost', resource_list_file=list_file, lock_folder=lock_folder) + yield Lockable(hostname='myhost', resource_list=data, lock_folder=lock_folder) class LockableTests(TestCase): @@ -32,6 +29,11 @@ def test_constructor(self): fp.write('[]') Lockable(hostname='myhost', resource_list_file=list_file, lock_folder=tmpdirname) + def test_invalid_constructor(self): + with self.assertRaises(AssertionError): + Lockable(hostname='myhost', resource_list_file='asdf', + resource_list=[], lock_folder='.') + def test_lock_require_resources_json_loaded(self): lockable = Lockable() with self.assertRaises(AssertionError) as error: