"""Запуск: cd scripts && ./venv/bin/python -m unittest discover -s tests"""
import os
import sys
import unittest
from unittest import mock

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from requests.exceptions import TooManyRedirects

import check_site


class FakeSite:
    url = "https://example.test"
    login_url = None


class CheckSiteRetryTest(unittest.TestCase):
    def test_redirect_loop_retries_on_next_proxy(self):
        # Первая попытка — редирект-петля (зависит от IP), вторая — успех.
        calls = {"n": 0}

        def fake_try(site, **kwargs):
            calls["n"] += 1
            if calls["n"] == 1:
                raise TooManyRedirects("Exceeded 30 redirects.")
            return True, "OK"

        with mock.patch.object(check_site, "try_check_site", side_effect=fake_try), \
             mock.patch.object(check_site, "get_proxy_config", return_value={"auth": "a", "host": "h"}), \
             mock.patch.object(check_site, "get_random_proxy_port", return_value=1000):
            ok, msg = check_site.check_site(FakeSite(), max_attempts=5)

        self.assertTrue(ok)
        self.assertEqual(msg, "OK")
        self.assertEqual(calls["n"], 2)  # была вторая попытка, а не мгновенный провал


if __name__ == "__main__":
    unittest.main()
