/
liquid-g
/
liquid-code
Обзор
Документация
Войти
/
liquid-g
/
liquid-code
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
tests/test_discovery.py
307 строк
9 KB
User
0.3.0-RC - дописаны тесты и мелкие исправления
04 июл 2026, 13:07
04 июл 2026, 13:07
40ad8b8
Код
Авторство
О чём код?
"""Тесты для обнаружения контроллеров.""" import pytest import tempfile import os from unittest.mock import Mock from liquidcode.discovery import ( has_route_methods, discover_controllers, discover_services, discover_classes, ) # Импортируем Service для тестов from liquidcode.service import Service @pytest.fixture def container(): """DI-контейнер для тестов.""" from liquidcode.container import Container return Container() class TestHasRouteMethods: """Тесты has_route_methods.""" def test_class_with_route(self): """Класс с методом, помеченным @route.""" class TestController: def index(self): return {} TestController.index._route_path = "/" TestController.index._route_methods = ["GET"] assert has_route_methods(TestController) is True def test_class_without_route(self): """Класс без методов с @route.""" class TestController: def index(self): return {} assert has_route_methods(TestController) is False def test_class_with_multiple_routes(self): """Класс с несколькими маршрутами.""" class TestController: def index(self): return {} def show(self): return {} TestController.index._route_path = "/" TestController.index._route_methods = ["GET"] TestController.show._route_path = "/{id}" TestController.show._route_methods = ["GET"] assert has_route_methods(TestController) is True def test_empty_class(self): """Пустой класс.""" class EmptyClass: pass assert has_route_methods(EmptyClass) is False class TestDiscoverControllers: """Тесты discover_controllers.""" def test_discover_from_existing_directory(self, tmp_path): """Обнаружение из существующей директории.""" test_file = tmp_path / "test_module.py" test_file.write_text("# Test module\n") register_func = Mock() register_func.side_effect = Exception("Not implemented") try: discover_controllers(str(tmp_path), register_func) except Exception: pass assert True def test_discover_from_nonexistent_directory(self): """Обнаружение из несуществующей директории.""" register_func = Mock() discover_controllers("/nonexistent/path", register_func) register_func.assert_not_called() def test_discover_with_package(self, tmp_path): """Обнаружение из пакета.""" pkg_dir = tmp_path / "controllers" pkg_dir.mkdir() init_file = pkg_dir / "__init__.py" init_file.write_text("") controller_file = pkg_dir / "user.py" controller_file.write_text("class UserController: pass") register_func = Mock() register_func.side_effect = Exception("Not implemented") try: discover_controllers(str(pkg_dir), register_func) except Exception: pass assert True def test_discover_with_absolute_path(self, tmp_path): """Обнаружение с абсолютным путем.""" controller_file = tmp_path / "test.py" controller_file.write_text("# Test module") register_func = Mock() register_func.side_effect = Exception("Not implemented") try: discover_controllers(str(controller_file.parent), register_func) except Exception: pass assert True def test_discover_with_import_error(self, tmp_path): """Обнаружение с ImportError.""" bad_file = tmp_path / "bad_module.py" bad_file.write_text("syntax error here !!!") register_func = Mock() # Должен обработать ошибку и продолжить discover_controllers(str(tmp_path), register_func) # Не должно вызвать исключение assert True class TestDiscoverPackage: """Тесты для discover_controllers с пакетами.""" def test_discover_from_package_with_controllers(self, tmp_path): """Обнаружение из пакета с контроллерами.""" pkg_dir = tmp_path / "controllers" pkg_dir.mkdir() init_file = pkg_dir / "__init__.py" init_file.write_text("") controller_file = pkg_dir / "user.py" controller_file.write_text(""" class UserController: def index(self): return {} UserController.index._route_path = '/' UserController.index._route_methods = ['GET'] """) register_func = Mock() import sys sys.path.insert(0, str(tmp_path)) try: import controllers from liquidcode.discovery import discover_controllers discover_controllers(str(pkg_dir), register_func) # Контроллер должен быть найден assert register_func.call_count == 1 finally: sys.path.remove(str(tmp_path)) if "controllers" in sys.modules: del sys.modules["controllers"] class TestDiscoveryEdgeCases: """Тесты discovery edge cases.""" def test_discover_with_syntax_error(self, tmp_path): """Обнаружение с синтаксической ошибкой в файле.""" bad_file = tmp_path / "bad.py" bad_file.write_text("def broken(") register_func = Mock() # Должен обработать ошибку и продолжить discover_controllers(str(tmp_path), register_func) # Не должно вызвать исключение assert True class TestDiscoveryClasses: """Тесты discover_classes.""" def test_discover_classes_with_predicate(self, tmp_path): """Обнаружение классов с предикатом.""" test_file = tmp_path / "test.py" test_file.write_text(""" class MyClass: pass class AnotherClass: pass """) found_classes = [] def predicate(cls): return cls.__name__ == "MyClass" def handler(cls): found_classes.append(cls) discover_classes(str(tmp_path), predicate, handler, "test") assert len(found_classes) == 1 assert found_classes[0].__name__ == "MyClass" def test_discover_classes_with_directory_predicate(self, tmp_path): """Обнаружение классов с предикатом для директорий.""" pkg_dir = tmp_path / "test_package" pkg_dir.mkdir() init_file = pkg_dir / "__init__.py" init_file.write_text("") module_file = pkg_dir / "module.py" module_file.write_text(""" class SomeClass: pass """) found_classes = [] def predicate(cls): return cls.__name__ == "SomeClass" def handler(cls): found_classes.append(cls) discover_classes(str(pkg_dir), predicate, handler, "test") assert len(found_classes) == 1 class TestDiscoverServices: """Тесты discover_services.""" def test_discover_services_from_directory(self, tmp_path, container): """Обнаружение сервисов из директории.""" service_dir = tmp_path / "services" service_dir.mkdir() service_file = service_dir / "test_service.py" service_file.write_text(""" from liquidcode.service import Service class TestService(Service): def get_data(self): return "test" """) discover_services(str(service_dir), container) # Сервис должен быть создан и кэширован # Импортируем после discover_services, чтобы класс был определен import sys sys.path.insert(0, str(service_dir)) try: from test_service import TestService service = container.get(TestService) assert isinstance(service, TestService) assert service.get_data() == "test" finally: sys.path.remove(str(service_dir)) if "test_service" in sys.modules: del sys.modules["test_service"] def test_discover_services_empty_directory(self, tmp_path, container): """Обнаружение сервисов из пустой директории.""" service_dir = tmp_path / "services" service_dir.mkdir() discover_services(str(service_dir), container) # Не должно вызвать исключение assert True def test_discover_services_nonexistent_directory(self, container): """Обнаружение сервисов из несуществующей директории.""" discover_services("/nonexistent/path", container) # Не должно вызвать исключение assert True