from unittest.mock import Mock

from django.test import TestCase

from newsreader.news.collection.favicon import FaviconBuilder
from newsreader.news.collection.tests.factories import CollectionRuleFactory
from newsreader.news.collection.tests.favicon.builder.mocks import (
    mock_with_multiple_icons,
    mock_with_other_url,
    mock_with_weird_path,
    mock_without_header,
    mock_without_url,
    simple_mock,
)


class FaviconBuilderTestCase(TestCase):
    def setUp(self):
        self.maxDiff = None

    def test_simple(self):
        rule = CollectionRuleFactory(favicon=None)

        with FaviconBuilder(simple_mock, Mock(rule=rule)) as builder:
            builder.build()
            builder.save()

        rule.refresh_from_db()

        self.assertEquals(rule.favicon, "https://www.bbc.com/favicon.ico")

    def test_without_url(self):
        rule = CollectionRuleFactory(
            website_url="https://www.theguardian.com/", favicon=None
        )

        with FaviconBuilder(mock_without_url, Mock(rule=rule)) as builder:
            builder.build()
            builder.save()

        rule.refresh_from_db()

        self.assertEquals(rule.favicon, "https://www.theguardian.com/favicon.ico")

    def test_without_header(self):
        rule = CollectionRuleFactory(favicon=None)

        with FaviconBuilder(mock_without_header, Mock(rule=rule)) as builder:
            builder.build()
            builder.save()

        rule.refresh_from_db()

        self.assertEquals(rule.favicon, None)

    def test_weird_path(self):
        rule = CollectionRuleFactory(favicon=None)

        with FaviconBuilder(mock_with_weird_path, Mock(rule=rule)) as builder:
            builder.build()
            builder.save()

        rule.refresh_from_db()

        self.assertEquals(
            rule.favicon, "https://www.theguardian.com/jabadaba/doe/favicon.ico"
        )

    def test_other_url(self):
        rule = CollectionRuleFactory(favicon=None)

        with FaviconBuilder(mock_with_other_url, Mock(rule=rule)) as builder:
            builder.build()
            builder.save()

        rule.refresh_from_db()

        self.assertEquals(rule.favicon, "https://www.theguardian.com/icon.png")

    def test_url_with_favicon_takes_precedence(self):
        rule = CollectionRuleFactory(favicon=None)

        with FaviconBuilder(mock_with_multiple_icons, Mock(rule=rule)) as builder:
            builder.build()
            builder.save()

        rule.refresh_from_db()

        self.assertEquals(rule.favicon, "https://www.bbc.com/favicon.ico")
