Skip to content

Commit

Permalink
test: daemonizer
Browse files Browse the repository at this point in the history
  • Loading branch information
u8slvn committed Jul 21, 2019
1 parent 3663002 commit d570c83
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 3 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@ htmlcov/
\~/
settings.env
log
test_pid
6 changes: 3 additions & 3 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
-r requirements.txt
pytest==3.2.3
pytest==5.0.1
pytest-cov==2.7.1
pytest-mock==1.10.4
freezegun==0.2.3
pytest-cov==2.5.1
coverage==4.5.2
coverage==4.5.3
flake8==3.7.7
78 changes: 78 additions & 0 deletions tests/test_daemon.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import os
import signal

import pytest

from rerwatcher.daemon import Daemon

base_dir = os.getcwd()
pidfile = f'{base_dir}/test_pid'


class DaemonApp(Daemon):
def __init__(self):
super(DaemonApp, self).__init__(
pidfile=pidfile,
app_name='TestApp'
)

def run(self):
print('Daemon working!')


# TODO: find a better way to test the real case.
def test_daemon(mocker, capsys):
os = mocker.patch('rerwatcher.daemon.os', **{
'fork.return_value': 0,
'path.exists.side_effect': [False, True],
'getpid.return_value': 42,
})
mocker.patch('rerwatcher.daemon.sys')
daemon_app = DaemonApp()

daemon_app.start()
daemon_app.stop()

assert os.fork.call_count == 2
captured = capsys.readouterr()
assert 'Daemon working!\n' == captured.out
assert os.remove.called_once_with(pidfile)
assert os.kill.called_once_with(42, signal.SIGTERM)


def test_daemon_do_not_start_if_os_fork_fails(mocker):
mocker.patch('rerwatcher.daemon.os', **{
'path.exists.return_value': False,
'fork.return_value': 1,
})
daemon_app = DaemonApp()

with pytest.raises(SystemExit):
daemon_app.start()


def test_daemon_do_not_start_if_os_fork2_fails(mocker):
mocker.patch('rerwatcher.daemon.os', **{
'path.exists.return_value': False,
'fork.side_effect': [0, 1],
})
daemon_app = DaemonApp()

with pytest.raises(SystemExit):
daemon_app.start()


def test_daemon_do_not_start_if_already_running(mocker):
mocker.patch('rerwatcher.daemon.os.path.exists', return_value=True)
daemon_app = DaemonApp()

with pytest.raises(RuntimeError):
daemon_app.start()


def test_daemon_do_not_stop_if_not_running(mocker):
mocker.patch('rerwatcher.daemon.os.path.exists', return_value=False)
daemon_app = DaemonApp()

with pytest.raises(SystemExit):
daemon_app.stop()

0 comments on commit d570c83

Please sign in to comment.