def test_clear_stale_pids(): from metrique.utils import clear_stale_pids, remove_file pid_dir = '/tmp' # we assume we'll have a pid 1, but never -1 pids = map(unicode, [1, -1]) pids_str = '1, -1' pid_files = [os.path.join(pid_dir, '%s.pid' % pid) for pid in pids] prefix = '' for pid, pid_file in zip(pids, pid_files): with open(pid_file, 'w') as f: f.write(str(pid)) running = clear_stale_pids(pids, pid_dir, prefix) assert '1' in running assert '-1' not in running assert exists(pid_files[0]) assert not exists(pid_files[1]) running = clear_stale_pids(pids_str, pid_dir, prefix) assert '1' in running assert '-1' not in running assert exists(pid_files[0]) assert not exists(pid_files[1]) remove_file(pid_files[0])
def test_terminate(): from metrique.utils import terminate, sys_call, get_pid, clear_stale_pids import signal pid_file = os.path.join(cache_dir, 'test.pid') sys_call('sleep 30', fork=True, pid_file=pid_file, shell=False) sleep(1) pid = get_pid(pid_file) running = clear_stale_pids(pid) assert running terminate(pid, sig=signal.SIGTERM) sleep(1) running = clear_stale_pids(pid) assert not running # since we didn't tell it where to find the pid_file # it won't be cleaned up assert exists(pid_file) # this time we point to a pid_file and it gets cleaned up terminate(pid_file, sig=signal.SIGTERM) assert not exists(pid_file) # invalid pids are ignored assert terminate(-1) is None