brief-rags-bench/tests/README.md

223 lines
6.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Brief Bench Tests
Полная система тестирования для Brief Bench FastAPI.
## Структура тестов
```
tests/
├── unit/ # Unit тесты (моки, изоляция)
│ ├── conftest.py # Фикстуры для unit тестов
│ ├── test_analysis.py # Тесты analysis endpoints
│ ├── test_auth.py # Тесты аутентификации
│ ├── test_base_interface.py # Тесты TgBackendInterface
│ ├── test_db_api_client.py # Тесты DB API клиента
│ ├── test_dependencies.py # Тесты dependencies
│ ├── test_main.py # Тесты main endpoints
│ ├── test_models.py # Тесты Pydantic моделей
│ ├── test_query.py # Тесты query endpoints
│ ├── test_security.py # Тесты JWT security
│ └── test_settings.py # Тесты settings endpoints
├── integration/ # Integration тесты (реальный DB API)
│ ├── conftest.py # Фикстуры для integration тестов
│ ├── README.md # Документация integration тестов
│ ├── .env.integration.example # Пример конфигурации
│ ├── test_auth_integration.py
│ ├── test_settings_integration.py
│ ├── test_analysis_integration.py
│ └── test_query_integration.py
└── README.md # Этот файл
```
## Быстрый старт
### 1. Только Unit тесты (без внешних зависимостей)
```bash
# Windows
run_unit_tests.bat
# Linux/Mac
pytest tests/unit/ -v --cov=app --cov-report=term-missing
```
**Результат:** 119 тестов, 99% coverage
### 2. Integration тесты (требуется DB API)
```bash
# Windows
run_integration_tests.bat
# Linux/Mac
pytest tests/integration/ -v -m integration
```
⚙️ **Требуется:** DB API на http://localhost:8081
### 3. Все тесты
```bash
# Windows
run_all_tests.bat
# Linux/Mac
pytest tests/ -v
```
## Установка
```bash
pip install -r requirements.txt
pip install -r requirements-dev.txt
```
## Команды pytest
### Базовые команды
```bash
# Все тесты
pytest
# Unit тесты
pytest tests/unit/
# Integration тесты
pytest tests/integration/
# С coverage
pytest --cov=app --cov-report=html
# Конкретный файл
pytest tests/unit/test_auth.py
# Конкретный тест
pytest tests/unit/test_auth.py::TestAuthEndpoints::test_login_success
# Verbose вывод
pytest -v
# Остановиться на первой ошибке
pytest -x
# Показать print statements
pytest -s
```
## Покрытие тестами
### Unit Tests: **99%** (567 строк, 4 непокрыто)
| Модуль | Coverage | Тесты |
|--------|----------|-------|
| app/api/v1/analysis.py | 100% | 20 |
| app/api/v1/auth.py | 100% | 6 |
| app/api/v1/query.py | 97% | 10 |
| app/api/v1/settings.py | 100% | 14 |
| app/dependencies.py | 100% | 6 |
| app/interfaces/base.py | 100% | 24 |
| app/interfaces/db_api_client.py | 100% | 8 |
| app/services/rag_service.py | 100% | 17 |
| app/services/auth_service.py | 100% | 3 |
| app/utils/security.py | 100% | 5 |
| app/models/*.py | 100% | 14 |
| app/main.py | 92% | 3 |
**Непокрытые строки (4):**
- `query.py:190-191` - Logger в exception handler
- `main.py:56-57` - `if __name__ == "__main__"` блок
## Что тестируется
### 1. Authentication (test_auth.py)
- Успешная авторизация с валидным 8-значным логином
- Отклонение невалидных форматов логина
- Обработка ошибок DB API
- Генерация JWT токенов
- Валидация токенов
### 2. Settings (test_settings.py)
- Получение настроек пользователя
- Обновление настроек
- Обработка несуществующих пользователей
- Валидация формата настроек
- Требование авторизации
### 3. Query (test_query.py)
- Bench mode запросы
- Backend mode запросы
- Валидация окружений (ift/psi/prod)
- Проверка соответствия apiMode
- Обработка ошибок RAG backend
- Построение headers для RAG
- Session reset в Backend mode
### 4. Analysis (test_analysis.py)
- Создание сессий анализа
- Получение списка сессий
- Фильтрация по окружению
- Пагинация
- Получение конкретной сессии
- Удаление сессии
- Требование авторизации
### 5. Security (test_security.py)
- Создание JWT токенов
- Декодирование токенов
- Обработка невалидных токенов
- Обработка истекших токенов
- Кастомное время жизни токенов
### 6. Models (test_models.py)
- Валидация LoginRequest (8 цифр)
- Валидация QuestionRequest
- Валидация BenchQueryRequest
- Валидация BackendQueryRequest
- Валидация EnvironmentSettings
- Дефолтные значения
## Моки
Все внешние зависимости замоканы:
- **DB API Client**: AsyncMock без реальных HTTP запросов
- **RAG Service**: AsyncMock без реальных запросов к RAG backends
- **httpx.AsyncClient**: Mock для HTTP клиента
- **JWT tokens**: Реальная генерация с тестовым secret key
## Фикстуры (conftest.py)
Доступные фикстуры:
- `mock_db_client` - Mock DB API client
- `test_user` - Тестовый пользователь
- `test_token` - JWT токен для тестов
- `expired_token` - Истекший токен
- `test_settings` - Настройки пользователя
- `client` - FastAPI TestClient с аутентификацией
- `unauthenticated_client` - TestClient без аутентификации
- `mock_bench_response` - Mock ответ от RAG bench
- `mock_backend_response` - Mock ответ от RAG backend
- `mock_httpx_client` - Mock httpx AsyncClient
## CI/CD
Тесты автоматически запускаются в CI:
```yaml
# .github/workflows/test.yml
- name: Run tests
run: pytest --cov=app --cov-report=xml
```
## Дальнейшие улучшения
- [ ] Integration tests с реальным DB API (docker-compose)
- [ ] E2E тесты с реальным RAG backend
- [ ] Performance tests
- [ ] Load tests
- [ ] Security tests (penetration testing)