from dogpile.cache.api import NO_VALUE from unittest.mock import Mock import pytest from labelaudit import config from labelaudit.connectors import cache from labelaudit.tasks.task_lock import TaskLock @pytest.fixture def task_name(): return 'labelaudit.tasks.report_generation_tasks.find' @pytest.fixture def ok_lock_id(task_name): return '{}-{}-lock-{}'.format( config.ENVIRONMENT, task_name, 'f2a1cd77045c78cef2858f54e965c71d') def test_key_value(monkeypatch, ok_lock_id, task_name): """Test cache key value format is as expected.""" lock = TaskLock(task_name) assert lock.lock_id == ok_lock_id def test_acquire_task_successfully_creates_lock(monkeypatch, task_name): """If task is available to be locked, return True.""" monkeypatch.setattr(cache.region, 'get', Mock(return_value=NO_VALUE)) monkeypatch.setattr(cache.region, 'set', Mock(return_value='')) lock = TaskLock(task_name) assert lock.acquire_task() is True assert cache.region.set.called def test_acquire_task_returns_false_if_already_locked( monkeypatch, task_name, ok_lock_id): """If task is already acquired somewhere else, return False.""" monkeypatch.setattr(cache.region, 'get', Mock(return_value=ok_lock_id)) lock = TaskLock(task_name) assert lock.acquire_task() is False