"""Unit tests for error handler functions.""" from unittest import mock import pymysql from sqlalchemy import exc from product_digital import api from product_digital.utils import error_handling def test_log_db_exception(test_request_context, mocker, valid_get_header): """Test that the exception is sent to Sentry and Loggly.""" message = 'something did not work' exception = exc.SQLAlchemyError(message) mocker.spy(error_handling, 'capture_exception') with api.app.test_request_context(headers=valid_get_header): mock_g_ows = mocker.patch('product_digital.utils.error_handling.g') error_handling.log_db_exception(exception) error_handling.capture_exception.assert_called_with(exception) mock_g_ows.ows.log.error.assert_called_with('DB error: {}'.format(message)) def test_log_unexpected_response(test_request_context, mocker, valid_get_header): """Test that an error is sent to Sentry and Loggly.""" mocker.spy(error_handling, 'capture_message') service_name = 'ows-awesome' bad_response = mock.MagicMock(status_code=418, text=None) with api.app.test_request_context(headers=valid_get_header): mock_g_ows = mocker.patch('product_digital.utils.error_handling.g') error_handling.log_unexpected_response(service_name, bad_response) expected_message = '{} returned unexpected status {}'.format( service_name, bad_response.status_code) mock_g_ows.ows.log.error.assert_called_with(expected_message) error_handling.capture_message.assert_called_with(expected_message) def test_log_unexpected_response_with_body(test_request_context, mocker, valid_get_header): """Test that an error is sent to Sentry and Loggly.""" mocker.spy(error_handling, 'capture_message') service_name = 'ows-awesome' bad_response = mock.MagicMock(status_code=418, text='{"foo": "bar"}') with api.app.test_request_context(headers=valid_get_header): mock_g_ows = mocker.patch('product_digital.utils.error_handling.g') error_handling.log_unexpected_response(service_name, bad_response) expected_message = '{} returned unexpected status {} with body: {}'.format( service_name, bad_response.status_code, bad_response.text) mock_g_ows.ows.log.error.assert_called_with(expected_message) error_handling.capture_message.assert_called_with(expected_message) def test_non_deadlock_error_is_deadlock(): """Test a deadlock returns False.""" pymysql_deadlock_error = pymysql.err.InternalError( 1213, 'Deadlock found when trying to get lock; try restarting transaction') assert not error_handling.non_deadlock_error(pymysql_deadlock_error) def test_non_deadlock_error_is_not_deadlock(): """Test a non-deadlock returns True.""" pymysql_deadlock_error = pymysql.err.InternalError(1000, 'Non deadlock') assert error_handling.non_deadlock_error(pymysql_deadlock_error)