""" Тестирование геттеров с данными из локального storage """ import pytest import sys from pathlib import Path # Добавляем путь к проекту project_root = Path(__file__).parent.parent sys.path.insert(0, str(project_root / "python_parser")) from core.services import ReportService, PARSERS from core.models import DataRequest, UploadRequest from adapters.local_storage import LocalStorageAdapter from adapters.parsers import SvodkaPMParser, SvodkaCAParser, MonitoringFuelParser # Регистрируем парсеры PARSERS.update({ 'svodka_pm': SvodkaPMParser, 'svodka_ca': SvodkaCAParser, 'monitoring_fuel': MonitoringFuelParser, }) class TestGettersWithLocalStorage: """Тестирование геттеров с локальным storage""" @pytest.fixture(autouse=True) def setup_storage(self, clean_storage): """Настройка локального storage для каждого теста""" self.storage = clean_storage self.report_service = ReportService(self.storage) def test_svodka_pm_single_og_with_local_data(self, upload_file): """Тест svodka_pm single_og с данными из локального storage""" # Сначала загружаем данные file_path = upload_file("pm_plan.zip") with open(file_path, 'rb') as f: file_content = f.read() request = UploadRequest( report_type='svodka_pm', file_name=file_path.name, file_content=file_content, parse_params={} ) upload_result = self.report_service.upload_report(request) assert upload_result.success is True, f"Загрузка не удалась: {upload_result.message}" # Теперь тестируем геттер data_request = DataRequest( report_type='svodka_pm', get_params={ 'mode': 'single_og', 'id': 'SNPZ', 'codes': [78, 79], 'columns': ['ПП', 'СЭБ'] } ) result = self.report_service.get_data(data_request) if result.success: print(f"✅ svodka_pm/single_og работает с локальными данными") print(f" Получено данных: {len(result.data) if isinstance(result.data, list) else 'не список'}") else: print(f"❌ svodka_pm/single_og не работает: {result.message}") # Не делаем assert, чтобы увидеть все ошибки def test_svodka_pm_total_ogs_with_local_data(self, upload_file): """Тест svodka_pm total_ogs с данными из локального storage""" # Сначала загружаем данные file_path = upload_file("pm_plan.zip") with open(file_path, 'rb') as f: file_content = f.read() request = UploadRequest( report_type='svodka_pm', file_name=file_path.name, file_content=file_content, parse_params={} ) upload_result = self.report_service.upload_report(request) assert upload_result.success is True, f"Загрузка не удалась: {upload_result.message}" # Теперь тестируем геттер data_request = DataRequest( report_type='svodka_pm', get_params={ 'mode': 'total_ogs', 'codes': [78, 79, 394, 395, 396, 397, 81, 82, 83, 84], 'columns': ['БП', 'ПП', 'СЭБ'] } ) result = self.report_service.get_data(data_request) if result.success: print(f"✅ svodka_pm/total_ogs работает с локальными данными") print(f" Получено данных: {len(result.data) if isinstance(result.data, list) else 'не список'}") else: print(f"❌ svodka_pm/total_ogs не работает: {result.message}") def test_svodka_ca_get_ca_data_with_local_data(self, upload_file): """Тест svodka_ca get_ca_data с данными из локального storage""" # Сначала загружаем данные file_path = upload_file("svodka_ca.xlsx") with open(file_path, 'rb') as f: file_content = f.read() request = UploadRequest( report_type='svodka_ca', file_name=file_path.name, file_content=file_content, parse_params={} ) upload_result = self.report_service.upload_report(request) assert upload_result.success is True, f"Загрузка не удалась: {upload_result.message}" # Теперь тестируем геттер data_request = DataRequest( report_type='svodka_ca', get_params={ 'mode': 'get_ca_data', 'modes': ['fact', 'plan'], 'tables': ['table1', 'table2'] } ) result = self.report_service.get_data(data_request) if result.success: print(f"✅ svodka_ca/get_ca_data работает с локальными данными") print(f" Получено данных: {len(result.data) if isinstance(result.data, list) else 'не список'}") else: print(f"❌ svodka_ca/get_ca_data не работает: {result.message}") def test_monitoring_fuel_get_total_by_columns_with_local_data(self, upload_file): """Тест monitoring_fuel get_total_by_columns с данными из локального storage""" # Сначала загружаем данные file_path = upload_file("monitoring.zip") with open(file_path, 'rb') as f: file_content = f.read() request = UploadRequest( report_type='monitoring_fuel', file_name=file_path.name, file_content=file_content, parse_params={} ) upload_result = self.report_service.upload_report(request) assert upload_result.success is True, f"Загрузка не удалась: {upload_result.message}" # Теперь тестируем геттер data_request = DataRequest( report_type='monitoring_fuel', get_params={ 'mode': 'total_by_columns', 'columns': ['total', 'normativ'] } ) result = self.report_service.get_data(data_request) if result.success: print(f"✅ monitoring_fuel/get_total_by_columns работает с локальными данными") print(f" Получено данных: {len(result.data) if isinstance(result.data, list) else 'не список'}") else: print(f"❌ monitoring_fuel/get_total_by_columns не работает: {result.message}") def test_monitoring_fuel_get_month_by_code_with_local_data(self, upload_file): """Тест monitoring_fuel get_month_by_code с данными из локального storage""" # Сначала загружаем данные file_path = upload_file("monitoring.zip") with open(file_path, 'rb') as f: file_content = f.read() request = UploadRequest( report_type='monitoring_fuel', file_name=file_path.name, file_content=file_content, parse_params={} ) upload_result = self.report_service.upload_report(request) assert upload_result.success is True, f"Загрузка не удалась: {upload_result.message}" # Теперь тестируем геттер data_request = DataRequest( report_type='monitoring_fuel', get_params={ 'mode': 'month_by_code', 'month': '02' } ) result = self.report_service.get_data(data_request) if result.success: print(f"✅ monitoring_fuel/get_month_by_code работает с локальными данными") print(f" Получено данных: {len(result.data) if isinstance(result.data, list) else 'не список'}") else: print(f"❌ monitoring_fuel/get_month_by_code не работает: {result.message}") def test_monitoring_fuel_get_series_by_id_and_columns_with_local_data(self, upload_file): """Тест monitoring_fuel get_series_by_id_and_columns с данными из локального storage""" # Сначала загружаем данные file_path = upload_file("monitoring.zip") with open(file_path, 'rb') as f: file_content = f.read() request = UploadRequest( report_type='monitoring_fuel', file_name=file_path.name, file_content=file_content, parse_params={} ) upload_result = self.report_service.upload_report(request) assert upload_result.success is True, f"Загрузка не удалась: {upload_result.message}" # Теперь тестируем геттер data_request = DataRequest( report_type='monitoring_fuel', get_params={ 'mode': 'series_by_id_and_columns', 'columns': ['total', 'normativ'] } ) result = self.report_service.get_data(data_request) if result.success: print(f"✅ monitoring_fuel/get_series_by_id_and_columns работает с локальными данными") print(f" Получено данных: {len(result.data) if isinstance(result.data, list) else 'не список'}") else: print(f"❌ monitoring_fuel/get_series_by_id_and_columns не работает: {result.message}") def test_all_getters_with_loaded_data(self, upload_file): """Тест всех геттеров с предварительно загруженными данными""" # Загружаем все данные files_to_upload = [ ("svodka_ca.xlsx", "svodka_ca", "file"), ("pm_plan.zip", "svodka_pm", "zip"), ("monitoring.zip", "monitoring_fuel", "zip") ] for filename, report_type, upload_type in files_to_upload: file_path = upload_file(filename) # Читаем файл и создаем UploadRequest with open(file_path, 'rb') as f: file_content = f.read() upload_request = UploadRequest( report_type=report_type, file_name=file_path.name, file_content=file_content, parse_params={} ) result = self.report_service.upload_report(upload_request) assert result.success is True, f"Загрузка {filename} не удалась: {result.message}" print(f"✅ {filename} загружен") # Тестируем все геттеры test_cases = [ # svodka_pm { 'report_type': 'svodka_pm', 'mode': 'single_og', 'params': {'id': 'SNPZ', 'codes': [78, 79], 'columns': ['ПП', 'СЭБ']}, 'name': 'svodka_pm/single_og' }, { 'report_type': 'svodka_pm', 'mode': 'total_ogs', 'params': {'codes': [78, 79, 394, 395, 396, 397, 81, 82, 83, 84], 'columns': ['БП', 'ПП', 'СЭБ']}, 'name': 'svodka_pm/total_ogs' }, # svodka_ca { 'report_type': 'svodka_ca', 'mode': 'get_ca_data', 'params': {'modes': ['fact', 'plan'], 'tables': ['table1', 'table2']}, 'name': 'svodka_ca/get_ca_data' }, # monitoring_fuel { 'report_type': 'monitoring_fuel', 'mode': 'total_by_columns', 'params': {'columns': ['total', 'normativ']}, 'name': 'monitoring_fuel/get_total_by_columns' }, { 'report_type': 'monitoring_fuel', 'mode': 'month_by_code', 'params': {'month': '02'}, 'name': 'monitoring_fuel/get_month_by_code' }, { 'report_type': 'monitoring_fuel', 'mode': 'series_by_id_and_columns', 'params': {'columns': ['total', 'normativ']}, 'name': 'monitoring_fuel/get_series_by_id_and_columns' } ] print("\n🧪 Тестирование всех геттеров с локальными данными:") for test_case in test_cases: request_params = test_case['params'].copy() request_params['mode'] = test_case['mode'] data_request = DataRequest( report_type=test_case['report_type'], get_params=request_params ) result = self.report_service.get_data(data_request) if result.success: print(f"✅ {test_case['name']}: работает") else: print(f"❌ {test_case['name']}: {result.message}") # Показываем содержимое storage objects = self.storage.list_objects() print(f"\n📊 Объекты в локальном storage: {len(objects)}") for obj_id in objects: metadata = self.storage.get_object_metadata(obj_id) if metadata: print(f" 📁 {obj_id}: {metadata['shape']} колонки: {metadata['columns'][:3]}...")