import os import datetime import pytest from tadas.platform import locking as lock_utils def test_try_lock(tmp_path): lock_path = tmp_path / '.lock' with lock_utils.try_lock(lock_path=lock_path): assert True def test_try_lock_blocked(tmp_path): lock_path = tmp_path / '.lock' lock_path.write_text('foo') with pytest.raises(lock_utils.LockAcquireException): with lock_utils.try_lock(lock_path=lock_path): pytest.fail('Should not reach this point') def test_try_lock_expired(tmp_path): lock_path = tmp_path / '.lock' now = datetime.datetime.now() lock_path.write_text('foo') created_at = (now - datetime.timedelta(minutes=61)).timestamp() os.utime(lock_path, (created_at, created_at)) ttl = datetime.timedelta(hours=1) # created 61 minutes ago, ttl is 1 hour, so it is expired with lock_utils.try_lock(lock_path=lock_path, ttl=ttl): assert True, 'Can acquire expired lock' def test_try_lock_not_yet_expired(tmp_path): lock_path = tmp_path / '.lock' now = datetime.datetime.now() lock_path.write_text('foo') created_at = (now - datetime.timedelta(minutes=59)).timestamp() os.utime(lock_path, (created_at, created_at)) ttl = datetime.timedelta(hours=1) # created less 1 hours ago, ttl is 1 hour, so it is not expired -> should raise with pytest.raises(lock_utils.LockAcquireException): with lock_utils.try_lock(lock_path=lock_path, ttl=ttl): pytest.fail('lock is not expired -> should not acquire lock')