import json import unittest from unittest.mock import mock_open, patch from dependabro.utils import save_module_versions_cache class TestSaveModuleVersionsCache(unittest.TestCase): @patch("builtins.open", new_callable=mock_open) def test_returns_true_when_cache_is_saved_successfully(self, mock_open): module_versions = {"module1": "v1.0.0"} result = save_module_versions_cache("/path/to/cache_file.json", module_versions) self.assertTrue(result) mock_open.assert_called_once_with( "/path/to/cache_file.json", "w", encoding="UTF-8" ) mock_open().write.assert_called_once_with(json.dumps(module_versions)) @patch("builtins.open", side_effect=IOError("Unable to open file")) def test_returns_false_when_io_error_occurs(self, mock_open): module_versions = {"module1": "v1.0.0"} with self.assertLogs(level="ERROR") as log: result = save_module_versions_cache( "/path/to/cache_file.json", module_versions ) self.assertFalse(result) self.assertIn("Error saving cache file: Unable to open file", log.output[0]) @patch("builtins.open", new_callable=mock_open) @patch( "json.dump", side_effect=TypeError("Object of type set is not JSON serializable"), ) def test_returns_false_when_json_serialization_fails( self, mock_json_dumps, mock_open ): module_versions = {"module1": {"v1.0.0"}} with self.assertLogs(level="ERROR") as log: result = save_module_versions_cache( "/path/to/cache_file.json", module_versions ) self.assertFalse(result) self.assertIn( "Error saving cache file: Object of type set is not JSON serializable", log.output[0], ) if __name__ == "__main__": unittest.main()