def test_get_pid(): from metrique.utils import get_pid, rand_chars, remove_file assert get_pid() == 0 assert get_pid(None) == 0 path = os.path.join(cache_dir, '%s.pid' % rand_chars(prefix='get_pid')) # invalid path returns 0 assert get_pid(path) == 0 with open(path, 'w') as f: f.write("1") assert exists(path) assert get_pid(path) == 1 remove_file(path) with open(path, 'w') as f: f.write("a") try: get_pid(path) except ValueError: pass else: assert False remove_file(path) # invalid path returns 0 assert get_pid("boomboompow") == 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