From 0559736bf02bc8c21693adf2193d42f936909ffd Mon Sep 17 00:00:00 2001 From: Jane Fan Date: Tue, 5 Jun 2018 21:07:55 +0000 Subject: [PATCH] Add the wait-on-locks option for acquiring lock --- pytest_lab/locker.py | 39 ++++++++++++++++++++++++--------------- 1 file changed, 24 insertions(+), 15 deletions(-) diff --git a/pytest_lab/locker.py b/pytest_lab/locker.py index 4e062b6..e129cd3 100644 --- a/pytest_lab/locker.py +++ b/pytest_lab/locker.py @@ -122,22 +122,31 @@ def __init__(self, config, backend, ttl=30): self._thread = None self._stop = threading.Event() - def aquire(self, key, user=None): + def aquire(self, key, wait_on_locks, user=None): record = self.backend.read(key) - if record and record.ttl: - logger.error('{} is locked by {}, waiting {} seconds for lock ' - 'to expire...'.format(key, record.value, record.ttl + 1)) - start = time.time() - while time.time() - start < record.ttl + 1: - record = self.backend.read(key) - if not record: - break - time.sleep(0.5) - - if record: - raise ResourceLocked( - '{} is currently locked by {}'.format(key, record.value)) + def check_record(record): + if record and record.ttl: + logger.error( + '{} is locked by {}, waiting {} seconds for re-checking ' + 'lock to expire...'.format(key, record.value, record.ttl + 1)) + start = time.time() + while time.time() - start < record.ttl + 1: + record = self.backend.read(key) + if not record: + return True + time.sleep(0.5) + else: + return True + + if not check_record(record): + if wait_on_locks: + while True: + if check_record(record): + break + else: + raise ResourceLocked( + '{} is currently locked by {}'.format(key, record.value)) # acquire lockid = get_lock_id(user) @@ -173,7 +182,7 @@ def pytest_unconfigure(self, config): @pytest.hookimpl def pytest_lab_aquire_lock(self, config, identifier): - self.aquire(identifier) + self.aquire(identifier, config.getoption('--wait-on-locks')) return True @pytest.hookimpl