"""Tests for Sentry connector and utils.""" from unittest import mock import pytest import sentry @mock.patch('sentry.raven.Client', return_value='sentry_client') @mock.patch('sentry.common_config') def test_sentry_enabled(mock_config, mock_raven_client): """Test sentry.sentry_client is setup when config.SENTRY_DSN is set.""" mock_config.SENTRY_DSN = 'SENTRY_DSN_VALUE' sentry_client = sentry.get_sentry_client() assert sentry.sentry_client mock_raven_client.assert_called_with('SENTRY_DSN_VALUE') assert sentry_client == 'sentry_client' @mock.patch('sentry.raven.Client', return_value='sentry_client') @mock.patch('sentry.common_config') def test_sentry_disabled(mock_config, mock_raven_client): """Test sentry.sentry_client initialized with DSN set to None.""" mock_config.SENTRY_DSN = None sentry_client = sentry.get_sentry_client() mock_raven_client.assert_called_with(None) assert sentry_client == 'sentry_client' @pytest.mark.parametrize( 'exc_cls, expected_to_capture', ( # Expected to capture Exception instances: (ValueError, True), (ZeroDivisionError, True), (Exception, True), # Expected not to capture anything else: (KeyboardInterrupt, False), (SystemExit, False), ) ) def test_sentry_capture_exception(exc_cls, expected_to_capture, mocker): """Test decorator sending errors to Sentry on exception.""" @sentry.sentry_capture_exception def func_that_raises(): raise exc_cls() mock_sentry_client = mocker.patch('sentry.sentry_client') with pytest.raises(exc_cls): func_that_raises() if expected_to_capture: assert mock_sentry_client.captureException.called is True else: assert mock_sentry_client.captureException.called is False def test_sentry_capture_exception_noop(mocker): """Test decorator not modifying return value on successful execution.""" @sentry.sentry_capture_exception def func_that_does_not_raise(): return True mock_sentry_client = mocker.patch('sentry.sentry_client') assert func_that_does_not_raise() is True assert mock_sentry_client.captureException.called is False