# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Tests for log filters."""

import logging
from unittest.mock import Mock

from django.db.utils import OperationalError
from django.test import SimpleTestCase

from debusine.django.log_filters import SuppressDatabaseErrors


class TestSuppressDatabaseErrors(SimpleTestCase):
    """Tests for the SuppressDatabaseErrors logging filter."""

    def setUp(self) -> None:
        self.filter = SuppressDatabaseErrors()
        self.record = Mock(spec=logging.LogRecord)

    def test_suppress_operational_error(self) -> None:
        """OperationalError should be suppressed."""
        self.record.exc_info = (OperationalError, OperationalError(), None)
        self.assertFalse(self.filter.filter(self.record))

    def test_allow_other_error(self) -> None:
        """Other errors like ValueError should be allowed."""
        self.record.exc_info = (ValueError, ValueError(), None)
        self.assertTrue(self.filter.filter(self.record))

    def test_allow_no_exception_type(self) -> None:
        """Records with exc_info but no exception type should be allowed."""
        self.record.exc_info = (None, None, None)
        self.assertTrue(self.filter.filter(self.record))

    def test_allow_no_exc_info(self) -> None:
        """Records without exc_info should be allowed."""
        self.record.exc_info = None
        self.assertTrue(self.filter.filter(self.record))

    def test_suppress_operational_error_subclass(self) -> None:
        """Subclasses of OperationalError should also be suppressed."""

        class MyOperationalError(OperationalError):
            pass

        self.record.exc_info = (MyOperationalError, MyOperationalError(), None)
        self.assertFalse(self.filter.filter(self.record))
