|
| 1 | +import unittest |
| 2 | +from datetime import datetime |
| 3 | +from unittest.mock import Mock, patch |
| 4 | + |
| 5 | +import requests |
| 6 | +from holidays import get_holidays, is_weekday |
| 7 | +from requests.exceptions import Timeout |
| 8 | + |
| 9 | + |
| 10 | +class TestCalendar(unittest.TestCase): |
| 11 | + @classmethod |
| 12 | + def setUpClass(cls): |
| 13 | + cls.wednesday = datetime(year=2025, month=1, day=1) |
| 14 | + cls.sunday = datetime(year=2025, month=1, day=5) |
| 15 | + cls.holidays = {"12/25": "Christmas", "7/4": "Independence Day"} |
| 16 | + cls.response_setup_dict = { |
| 17 | + "json.return_value": cls.holidays, |
| 18 | + "status_code": 200, |
| 19 | + } |
| 20 | + |
| 21 | + def log_request(self, url): |
| 22 | + """Helper function that logs and returns a mock successful request.""" |
| 23 | + print(f"Making a request to {url}.") |
| 24 | + print("Request received!") |
| 25 | + return Mock(**self.response_setup_dict) |
| 26 | + |
| 27 | + @patch("holidays.datetime") |
| 28 | + def test_is_weekday_returns_true_on_weekdays(self, mock_datetime): |
| 29 | + mock_datetime.today.return_value = self.wednesday |
| 30 | + self.assertTrue(is_weekday()) |
| 31 | + |
| 32 | + @patch("holidays.datetime") |
| 33 | + def test_is_weekday_returns_false_on_weekends(self, mock_datetime): |
| 34 | + mock_datetime.today.return_value = self.sunday |
| 35 | + self.assertFalse(is_weekday()) |
| 36 | + |
| 37 | + # Example of patching only a specific object |
| 38 | + @patch.object(requests, "get", side_effect=requests.exceptions.Timeout) |
| 39 | + def test_get_holidays_timeout(self, mock_requests): |
| 40 | + with self.assertRaises(requests.exceptions.Timeout): |
| 41 | + get_holidays() |
| 42 | + |
| 43 | + # Example of using the `with` statement with `patch()` |
| 44 | + def test_get_holidays_logging(self): |
| 45 | + with patch("holidays.requests") as mock_requests: |
| 46 | + mock_requests.get.side_effect = self.log_request |
| 47 | + self.assertEqual(get_holidays()["12/25"], "Christmas") |
| 48 | + |
| 49 | + @patch("holidays.requests") |
| 50 | + def test_get_holidays_retry(self, mock_requests): |
| 51 | + response_mock = Mock(**self.response_setup_dict) |
| 52 | + # Set the side effect of .get() |
| 53 | + mock_requests.get.side_effect = [Timeout, response_mock] |
| 54 | + # Test that the first request raises a Timeout |
| 55 | + with self.assertRaises(Timeout): |
| 56 | + get_holidays() |
| 57 | + # Now retry, expecting a successful response |
| 58 | + self.assertEqual(get_holidays()["12/25"], "Christmas") |
| 59 | + # Finally, assert .get() was called twice |
| 60 | + self.assertEqual(mock_requests.get.call_count, 2) |
| 61 | + |
| 62 | + |
| 63 | +if __name__ == "__main__": |
| 64 | + unittest.main() |
0 commit comments