import json
import unittest
from unittest.mock import patch, MagicMock
from bot.lib import http


class TestFetchJson(unittest.TestCase):
    def test_returns_parsed_json_on_success(self):
        fake_resp = MagicMock()
        fake_resp.read.return_value = b'{"hello": "world"}'
        fake_resp.__enter__ = lambda s: s
        fake_resp.__exit__ = lambda *a: None
        with patch("urllib.request.urlopen", return_value=fake_resp):
            self.assertEqual(http.fetch_json("https://example/x"), {"hello": "world"})

    def test_retries_once_then_raises(self):
        with patch("urllib.request.urlopen", side_effect=OSError("boom")) as m:
            with patch("time.sleep") as sleep_mock:
                with self.assertRaises(http.HTTPError):
                    http.fetch_json("https://example/x")
                self.assertEqual(m.call_count, 2)
                sleep_mock.assert_called_once_with(http.RETRY_DELAY_SECONDS)


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