from json import JSONDecodeError
from unittest.mock import patch

from django.test import TestCase

from newsreader.accounts.tests.factories import UserFactory
from newsreader.news.collection.exceptions import StreamException
from newsreader.news.collection.twitter import TwitterTimeLineScheduler


class TwitterTimeLineSchedulerTestCase(TestCase):
    def setUp(self):
        patched_fetch = patch("newsreader.news.collection.twitter.fetch")
        self.mocked_fetch = patched_fetch.start()

    def test_simple(self):
        user = UserFactory(twitter_oauth_token="foo", twitter_oauth_token_secret="bar")

        self.mocked_fetch.return_value.json.return_value = {
            "rate_limit_context": {"application": "dummykey"},
            "resources": {
                "statuses": {
                    "/statuses/user_timeline": {
                        "limit": 1500,
                        "remaining": 1500,
                        "reset": 1601141386,
                    }
                }
            },
        }

        scheduler = TwitterTimeLineScheduler(user)

        self.assertEquals(scheduler.get_current_ratelimit(), 1500)

    def test_stream_exception(self):
        user = UserFactory(twitter_oauth_token=None, twitter_oauth_token_secret=None)

        self.mocked_fetch.side_effect = StreamException

        scheduler = TwitterTimeLineScheduler(user)

        self.assertEquals(scheduler.get_current_ratelimit(), None)

    def test_json_decode_error(self):
        user = UserFactory(twitter_oauth_token="foo", twitter_oauth_token_secret="bar")

        self.mocked_fetch.return_value.json.side_effect = JSONDecodeError(
            "foo", "bar", 10
        )

        scheduler = TwitterTimeLineScheduler(user)

        self.assertEquals(scheduler.get_current_ratelimit(), None)

    def test_unexpected_contents(self):
        user = UserFactory(twitter_oauth_token="foo", twitter_oauth_token_secret="bar")

        self.mocked_fetch.return_value.json.return_value = {"foo": "bar"}

        scheduler = TwitterTimeLineScheduler(user)

        self.assertEquals(scheduler.get_current_ratelimit(), None)
