from unittest.mock import patch

from django.core.cache import cache
from django.test import TestCase
from django.urls import reverse

from newsreader.accounts.tests.factories import UserFactory


class FaviconRedirectViewTestCase(TestCase):
    def setUp(self):
        self.user = UserFactory(email="test@test.nl", password="test")
        self.client.force_login(self.user)

        self.patch = patch("newsreader.accounts.views.favicon.FaviconTask")
        self.mocked_task = self.patch.start()

    def tearDown(self):
        cache.clear()

    def test_simple(self):
        response = self.client.get(reverse("accounts:settings:favicon"))

        self.assertRedirects(response, reverse("accounts:settings:home"))

        self.mocked_task.delay.assert_called_once_with(self.user.pk)

        self.assertEqual(1, cache.get(f"{self.user.email}-favicon-task"))

    def test_not_active(self):
        cache.set(f"{self.user.email}-favicon-task", 1)

        response = self.client.get(reverse("accounts:settings:favicon"))

        self.assertRedirects(response, reverse("accounts:settings:home"))

        self.mocked_task.delay.assert_not_called()
