/
liquid-g
/
liquid-code
Обзор
Документация
Войти
/
liquid-g
/
liquid-code
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
develop-0.2.0
tests/test_config.py
238 строк
8 KB
User
ci: настроен Black и flake8 для автоматического форматирования кода
04 июл 2026, 08:14
04 июл 2026, 08:14
4778ed6
Код
Авторство
О чём код?
"""Тесты для модуля конфигурации config.py.""" import pytest import os import tempfile import json from liquidcode.config import load_config, ConfigError class TestLoadConfigYAML: """Тесты загрузки YAML конфигураций.""" def test_load_yaml_config_success(self, tmp_path): """Успешная загрузка YAML конфига.""" config_file = tmp_path / "config.yaml" config_file.write_text("key: value\nnumber: 42") result = load_config(str(config_file)) assert result == {"key": "value", "number": 42} def test_load_yml_extension_success(self, tmp_path): """Успешная загрузка с расширением .yml.""" config_file = tmp_path / "config.yml" config_file.write_text("database:\n host: localhost") result = load_config(str(config_file)) assert result == {"database": {"host": "localhost"}} def test_load_yaml_empty_file(self, tmp_path): """Загрузка пустого YAML файла.""" config_file = tmp_path / "empty.yaml" config_file.write_text("") result = load_config(str(config_file)) assert result == {} def test_load_yaml_with_comments(self, tmp_path): """Загрузка YAML с комментариями.""" config_file = tmp_path / "config.yaml" config_file.write_text("# This is a comment\n\n# Another comment\nkey: value") result = load_config(str(config_file)) assert result == {"key": "value"} def test_load_yaml_with_null_value(self, tmp_path): """Загрузка YAML с null значением.""" config_file = tmp_path / "config.yaml" config_file.write_text("key: null\nother: value") result = load_config(str(config_file)) assert result == {"key": None, "other": "value"} def test_load_yaml_invalid_syntax(self, tmp_path): """Обработка ошибки синтаксиса YAML.""" config_file = tmp_path / "invalid.yaml" config_file.write_text("key: [unclosed") with pytest.raises(ConfigError) as exc_info: load_config(str(config_file)) assert "Invalid YAML" in str(exc_info.value) def test_load_yaml_requires_pyyaml(self, tmp_path): """Ошибочная загрузка YAML без PyYAML.""" config_file = tmp_path / "config.yaml" config_file.write_text("key: value") # Мокаем отсутствие yaml with pytest.raises(ConfigError) as exc_info: with pytest.MonkeyPatch().context() as mp: mp.setattr("liquidcode.config.yaml", None) load_config(str(config_file)) assert "PyYAML is required" in str(exc_info.value) class TestLoadConfigJSON: """Тесты загрузки JSON конфигураций.""" def test_load_json_config_success(self, tmp_path): """Успешная загрузка JSON конфига.""" config_file = tmp_path / "config.json" config_file.write_text('{"key": "value", "number": 42}') result = load_config(str(config_file)) assert result == {"key": "value", "number": 42} def test_load_json_empty_object(self, tmp_path): """Загрузка пустого JSON объекта.""" config_file = tmp_path / "empty.json" config_file.write_text("{}") result = load_config(str(config_file)) assert result == {} def test_load_json_empty_file(self, tmp_path): """Загрузка пустого JSON файла.""" config_file = tmp_path / "empty.json" config_file.write_text("") # Пустой JSON файл возвращает пустой словарь (как и YAML) result = load_config(str(config_file)) assert result == {} def test_load_json_invalid_syntax(self, tmp_path): """Обработка ошибки синтаксиса JSON.""" config_file = tmp_path / "invalid.json" config_file.write_text('{"key": "value"') # Missing closing brace with pytest.raises(ConfigError) as exc_info: load_config(str(config_file)) assert "Invalid JSON" in str(exc_info.value) def test_load_json_with_array(self, tmp_path): """Загрузка JSON с массивом.""" config_file = tmp_path / "config.json" config_file.write_text('{"items": [1, 2, 3]}') result = load_config(str(config_file)) assert result == {"items": [1, 2, 3]} def test_load_json_with_nested_object(self, tmp_path): """Загрузка JSON с вложенными объектами.""" config_file = tmp_path / "config.json" config_file.write_text('{"db": {"host": "localhost", "port": 5432}}') result = load_config(str(config_file)) assert result == {"db": {"host": "localhost", "port": 5432}} class TestLoadConfigErrors: """Тесты обработки ошибок при загрузке конфигурации.""" def test_file_not_found(self): """Обработка ошибки отсутствия файла.""" with pytest.raises(ConfigError) as exc_info: load_config("/nonexistent/path/config.yaml") assert "Config file not found" in str(exc_info.value) def test_unsupported_extension(self, tmp_path): """Обработка неподдерживаемого расширения файла.""" config_file = tmp_path / "config.txt" config_file.write_text("key: value") with pytest.raises(ConfigError) as exc_info: load_config(str(config_file)) assert "Unsupported config format" in str(exc_info.value) def test_failed_to_read_file(self, tmp_path): """Обработка ошибки чтения файла.""" config_file = tmp_path / "config.yaml" config_file.write_text("key: value") # Мокаем ошибку чтения with pytest.raises(ConfigError) as exc_info: with pytest.MonkeyPatch().context() as mp: def mock_open(*args, **kwargs): raise OSError("Permission denied") mp.setattr("builtins.open", mock_open) load_config(str(config_file)) assert "Failed to read config file" in str(exc_info.value) def test_yaml_file_with_invalid_yaml_syntax(self, tmp_path): """Ошибочный YAML синтаксис.""" config_file = tmp_path / "config.yaml" config_file.write_text("key: [unclosed bracket") with pytest.raises(ConfigError) as exc_info: load_config(str(config_file)) assert "Invalid YAML" in str(exc_info.value) def test_json_file_with_invalid_json_syntax(self, tmp_path): """Ошибочный JSON синтаксис.""" config_file = tmp_path / "config.json" config_file.write_text('{"key": "value"') # Missing closing brace with pytest.raises(ConfigError) as exc_info: load_config(str(config_file)) assert "Invalid JSON" in str(exc_info.value) class TestLoadConfigEdgeCases: """Тесты граничных случаев.""" def test_case_insensitive_extension(self, tmp_path): """Чувствительность к регистру расширения.""" config_file = tmp_path / "config.YAML" config_file.write_text("key: value") result = load_config(str(config_file)) assert result == {"key": "value"} def test_yaml_list_root(self, tmp_path): """Корень YAML - список.""" config_file = tmp_path / "config.yaml" config_file.write_text("- item1\n- item2") result = load_config(str(config_file)) assert result == ["item1", "item2"] def test_yaml_number_value(self, tmp_path): """Корень YAML - число.""" config_file = tmp_path / "config.yaml" config_file.write_text("42") result = load_config(str(config_file)) assert result == 42 def test_yaml_string_value(self, tmp_path): """Корень YAML - строка.""" config_file = tmp_path / "config.yaml" config_file.write_text("some string") result = load_config(str(config_file)) assert result == "some string"