from unittest.mock import Mock, patch

from django.apps import apps
from django.core.management import call_command
from django.test import TestCase

from ocyan.plugin.sentry_logging import entrypoint


class GetDSNTestCase(TestCase):
    def test_app_is_installed(self):
        self.assertTrue(apps.is_installed("ocyan.plugin.sentry_logging"))

    def test_django_checks_pass(self):
        call_command("check")

    def test_disabled(self):
        with patch.dict("os.environ", {"DJANGO_SETTINGS_MODULE": "env.base"}):
            self.assertEqual(entrypoint.get_dsn(), None)

    @patch("ocyan.plugin.sentry_logging.entrypoint._get_fender_config")
    def test_enabled(self, mocked_config):
        mocked_config.return_value = Mock(get=Mock(return_value="een dsn"))
        with patch.dict("os.environ", {"DJANGO_SETTINGS_MODULE": "env.dev"}):
            self.assertEqual(entrypoint.get_dsn(), "een dsn")

    @patch("ocyan.plugin.sentry_logging.entrypoint.sentry_sdk.init")
    @patch("ocyan.plugin.sentry_logging.entrypoint._get_fender_config")
    def test_initialize_sentry_skips_without_dsn(self, mocked_config, init_mock):
        mocked_config.return_value = Mock(get=Mock(return_value=""))
        with patch.dict("os.environ", {"DJANGO_SETTINGS_MODULE": "env.dev"}):
            self.assertFalse(entrypoint.initialize_sentry())
        init_mock.assert_not_called()

    @patch("ocyan.plugin.sentry_logging.entrypoint.sentry_sdk.init")
    @patch("ocyan.plugin.sentry_logging.entrypoint._get_fender_config")
    def test_initialize_sentry_uses_configured_dsn(self, mocked_config, init_mock):
        mocked_config.return_value = Mock(get=Mock(return_value="een dsn"))
        with patch.dict("os.environ", {"DJANGO_SETTINGS_MODULE": "env.dev"}):
            self.assertTrue(entrypoint.initialize_sentry())
        init_mock.assert_called_once()
