test_p2p_daemon.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import subprocess
  2. from time import perf_counter
  3. import pytest
  4. import hivemind.p2p
  5. from hivemind.p2p import P2P
  6. RUNNING = 'running'
  7. NOT_RUNNING = 'not running'
  8. CHECK_PID_CMD = '''
  9. if ps -p {0} > /dev/null;
  10. then
  11. echo "{1}"
  12. else
  13. echo "{2}"
  14. fi
  15. '''
  16. def is_process_running(pid: int) -> bool:
  17. cmd = CHECK_PID_CMD.format(pid, RUNNING, NOT_RUNNING)
  18. return subprocess.check_output(cmd, shell=True).decode('utf-8').strip() == RUNNING
  19. @pytest.fixture()
  20. def mock_p2p_class():
  21. P2P.LIBP2P_CMD = "sleep"
  22. def test_daemon_killed_on_del(mock_p2p_class):
  23. start = perf_counter()
  24. p2p_daemon = P2P('10s')
  25. child_pid = p2p_daemon._child.pid
  26. assert is_process_running(child_pid)
  27. del p2p_daemon
  28. assert not is_process_running(child_pid)
  29. assert perf_counter() - start < 1
  30. def test_daemon_killed_on_exit(mock_p2p_class):
  31. start = perf_counter()
  32. with P2P('10s') as daemon:
  33. child_pid = daemon.pid
  34. assert is_process_running(child_pid)
  35. assert not is_process_running(child_pid)
  36. assert perf_counter() - start < 1
  37. def test_daemon_raises_on_faulty_args():
  38. with pytest.raises(RuntimeError):
  39. P2P(faulty='argument')