import json from pathlib import Path from unittest import mock from config import Config import unittest class TestConfig(unittest.TestCase): def test_creates_new_config_file_if_not_exists(self): config_path = Path("test_config.json") if config_path.exists(): config_path.unlink() config = Config(config_file=config_path) self.assertTrue(config_path.exists()) config_path.unlink() def test_writes_default_configuration_to_config_file(self): config_path = Path("test_config.json") if config_path.exists(): config_path.unlink() config = Config(config_file=config_path) with open(config_path, "r") as f: data = json.load(f) self.assertEqual(data, {"database_path": "~/.iottb.db", "log_level": "INFO"}) config_path.unlink() @unittest.mock.patch("builtins.open", side_effect=PermissionError) def test_config_file_path_not_writable(self, mock_open): config_path = Path("test_config.json") with self.assertRaises(PermissionError): config = Config(config_file=config_path) config.create_default_config() def test_config_file_path_is_directory(self): config_dir = Path("test_config_dir") config_dir.mkdir(exist_ok=True) with self.assertRaises(IsADirectoryError): config = Config(config_file=config_dir) config.create_default_config() config_dir.rmdir()