def test_single_message(self): """Tests if utils.publish_body is called with one message.""" self.counter = CountPublishBody() self.handler = pubsub_logging.AsyncPubsubHandler( topic=self.topic, client=self.mocked_client, retry=self.RETRY, worker_num=1, publish_body=self.counter) log_msg = 'Test message' r = logging.LogRecord('test', logging.CRITICAL, None, 0, log_msg, [], None) self.handler.emit(r) self.handler.close() with self.counter.lock: self.assertEqual(1, self.counter.cnt.value)
def test_formated_message(self): """Tests if a formatter assigned to the handler is used.""" self.log_msg = 'Test message' self.expected_payload = compat_urlsafe_b64encode( 'Test Formatter - test - CRITICAL - ' + self.log_msg) self.expected_body = {'messages': [{'data': self.expected_payload}]} self.handler = pubsub_logging.AsyncPubsubHandler( topic=self.topic, client=self.mocked_client, retry=self.RETRY, worker_num=1, publish_body=self.mock_publish_body) self.handler.setFormatter( logging.Formatter( 'Test Formatter - %(name)s - %(levelname)s - %(message)s')) r = logging.LogRecord('test', logging.CRITICAL, None, 0, self.log_msg, [], None) self.handler.emit(r) self.handler.close()
def test_handler_ignores_error(self): """Tests if the handler ignores errors and throws the logs away.""" mock_publish_body = mock.MagicMock() mock_publish_body.side_effect = [RecoverableError(), mock.DEFAULT] self.counter = CountPublishBody(mock=mock_publish_body) # For suppressing the output. devnull = logging.Logger('devnull') devnull.addHandler(logging.NullHandler()) self.handler = pubsub_logging.AsyncPubsubHandler( topic=self.topic, client=self.mocked_client, retry=self.RETRY, worker_num=1, publish_body=self.counter, stderr_logger=devnull) log_msg = 'Test message' r = logging.LogRecord('test', logging.CRITICAL, None, 0, log_msg, [], None) # RecoverableError should be ignored, and retried. self.handler.emit(r) self.handler.close() with self.counter.lock: self.assertEqual(1, self.counter.cnt.value)
def create_handler(): pubsub_logging.AsyncPubsubHandler(topic=self.topic, client=self.mocked_client, worker_num=1)