Skip to content
This repository has been archived by the owner on Dec 3, 2021. It is now read-only.

Commit

Permalink
playlist: Refactor run_if_locking and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jbochi committed Jan 29, 2013
1 parent 8677b9c commit 85595d3
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 7 deletions.
12 changes: 5 additions & 7 deletions hlsclient/workers/playlist.py
Expand Up @@ -106,17 +106,15 @@ def worker_id(self):
return hashlib.md5(self.playlist).hexdigest()

def run_if_locking(self):
if self.can_run():
self.lock.update_lock()
self.run()

def can_run(self):
if self.other_is_running():
logging.warning("Someone else acquired the lock")
self.stop()
elif not self.lock.is_locked():
return
if not self.lock.is_locked():
self.lock.acquire(timeout=self.lock_timeout)
return self.lock.i_am_locking()
if self.lock.i_am_locking():
self.lock.update_lock()
self.run()

def other_is_running(self):
other = self.lock.is_locked() and not self.lock.i_am_locking()
Expand Down
66 changes: 66 additions & 0 deletions tests/test_worker.py
@@ -0,0 +1,66 @@
import random

from hlsclient.workers.playlist import PlaylistWorker

def test_second_worker_should_see_that_other_is_running(monkeypatch):
stream_name = "%0x" % random.randint(0, 2**64)
run_calls = []
def fake_run(*args):
run_calls.append(args)
def fake_stop(*args):
pass

first = PlaylistWorker(stream_name)
monkeypatch.setattr(first, 'run', fake_run)
monkeypatch.setattr(first, 'stop', fake_stop)

first.run_if_locking()
assert 1 == len(run_calls)

second = PlaylistWorker(stream_name)
assert True == second.other_is_running()

def test_lock_should_be_updated_when_run(monkeypatch):
stream_name = "%0x" % random.randint(0, 2**64)
run_calls = []
lock_update_calls = []
def fake_run(*args):
run_calls.append(args)
def fake_lock_update(*args):
lock_update_calls.append(args)
def fake_stop(*args):
pass

worker = PlaylistWorker(stream_name)
monkeypatch.setattr(worker, 'run', fake_run)
monkeypatch.setattr(worker, 'stop', fake_stop)
monkeypatch.setattr(worker.lock, 'update_lock', fake_lock_update)

worker.run_if_locking()
assert 1 == len(run_calls)
assert 1 == len(lock_update_calls)

def test_worker_should_stop_if_someone_else_acquires_lock(monkeypatch):
stream_name = "%0x" % random.randint(0, 2**64)
run_calls = []
stop_calls = []
def fake_run(*args):
run_calls.append(args)
def fake_stop(*args):
stop_calls.append(args)

first = PlaylistWorker(stream_name)
monkeypatch.setattr(first, 'run', fake_run)
monkeypatch.setattr(first, 'stop', fake_stop)
first.run_if_locking()

assert 1 == len(run_calls)
assert 0 == len(stop_calls)

run_calls = []
second = PlaylistWorker(stream_name)
monkeypatch.setattr(second, 'run', fake_run)
monkeypatch.setattr(second, 'stop', fake_stop)
second.run_if_locking()
assert 0 == len(run_calls)
assert 1 == len(stop_calls)

0 comments on commit 85595d3

Please sign in to comment.