def test_prepare_inits_daemon_variable(self, tcp_server, caplog):
        with self._tcp_patcher(tcp_server), caplog.atLevel(logging.DEBUG):
            daemon = hooks_daemon.HttpHooksCallbackDaemon()
        assert daemon._daemon == tcp_server

        assert_message_in_log(
            caplog.records(),
            'Preparing callback daemon and registering hook object',
            levelno=logging.DEBUG,
            module='hooks_daemon')
    def test_prepare_inits_hooks_uri_and_logs_it(self, tcp_server, caplog):
        with self._tcp_patcher(tcp_server), caplog.atLevel(logging.DEBUG):
            daemon = hooks_daemon.HttpHooksCallbackDaemon()

        _, port = tcp_server.server_address
        expected_uri = '{}:{}'.format(daemon.IP_ADDRESS, port)
        assert daemon.hooks_uri == expected_uri

        assert_message_in_log(caplog.records(),
                              'Hooks uri is: {}'.format(expected_uri),
                              levelno=logging.DEBUG,
                              module='hooks_daemon')
    def test_run_logs(self, tcp_server, caplog):

        with self._tcp_patcher(tcp_server):
            daemon = hooks_daemon.HttpHooksCallbackDaemon()

        with self._thread_patcher(mock.Mock()), caplog.atLevel(logging.DEBUG):
            daemon._run()

        assert_message_in_log(
            caplog.records(),
            'Running event loop of callback daemon in background thread',
            levelno=logging.DEBUG,
            module='hooks_daemon')
    def test_run_creates_a_thread(self, tcp_server):
        thread = mock.Mock()

        with self._tcp_patcher(tcp_server):
            daemon = hooks_daemon.HttpHooksCallbackDaemon()

        with self._thread_patcher(thread) as thread_mock:
            daemon._run()

        thread_mock.assert_called_once_with(
            target=tcp_server.serve_forever,
            kwargs={'poll_interval': daemon.POLL_INTERVAL})
        assert thread.daemon is True
        thread.start.assert_called_once_with()
    def test_stop_cleans_up_the_connection(self, tcp_server, caplog):
        thread = mock.Mock()

        with self._tcp_patcher(tcp_server):
            daemon = hooks_daemon.HttpHooksCallbackDaemon()

        with self._thread_patcher(thread), caplog.atLevel(logging.DEBUG):
            with daemon:
                assert daemon._daemon == tcp_server
                assert daemon._callback_thread == thread

        assert daemon._daemon is None
        assert daemon._callback_thread is None
        tcp_server.shutdown.assert_called_with()
        thread.join.assert_called_once_with()

        assert_message_in_log(caplog.records(),
                              'Waiting for background thread to finish.',
                              levelno=logging.DEBUG,
                              module='hooks_daemon')