Илья Глазунов 881028c1e6 feat: Add reverse proxy functionality with enhanced routing capabilities
- Introduced IgnoreRequestPath option in proxy configuration to allow exact match routing.
- Implemented proxy_pass directive in routing extension to handle backend requests.
- Enhanced error handling for backend unavailability and timeouts.
- Added integration tests for reverse proxy, including basic requests, exact match routes, regex routes, header forwarding, and query string preservation.
- Created helper functions for setting up test servers and backends, along with assertion utilities for response validation.
- Updated server initialization to support extension management and middleware chaining.
- Improved logging for debugging purposes during request handling.
2025-12-12 00:38:30 +03:00

128 lines
4.6 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.

# Integration Tests
Интеграционные тесты для Konduktor — полноценное тестирование сервера с реальными HTTP запросами.
## Отличие от unit-тестов
| Аспект | Unit-тесты | Интеграционные тесты |
|--------|------------|---------------------|
| Scope | Отдельный модуль в изоляции | Весь сервер целиком |
| Backend | Mock (httptest.Server) | Реальные HTTP серверы |
| Config | Программный | YAML конфигурация |
| Extensions | Не тестируются | Полная цепочка обработки |
## Структура тестов
```
tests/integration/
├── README.md # Эта документация
├── helpers_test.go # Общие хелперы и утилиты
├── reverse_proxy_test.go # Тесты reverse proxy
├── routing_test.go # Тесты маршрутизации (TODO)
├── security_test.go # Тесты security extension (TODO)
├── caching_test.go # Тесты caching extension (TODO)
└── static_files_test.go # Тесты статических файлов (TODO)
```
## Что тестируют интеграционные тесты
### 1. Reverse Proxy (`reverse_proxy_test.go`)
- [ ] Базовое проксирование GET/POST/PUT/DELETE
- [ ] Exact match routes (`=/api/version`)
- [ ] Regex routes с параметрами (`~^/api/resource/(?P<id>\d+)$`)
- [ ] Подстановка параметров в target URL (`{id}`, `{tag}`)
- [ ] Подстановка переменных в заголовки (`$remote_addr`)
- [ ] Передача заголовков X-Forwarded-For, X-Real-IP
- [ ] Сохранение query string
- [ ] Обработка ошибок backend (502, 504)
- [ ] Таймауты соединения
### 2. Routing Extension (`routing_test.go`)
- [ ] Приоритет маршрутов (exact > regex > default)
- [ ] Case-sensitive regex (`~`)
- [ ] Case-insensitive regex (`~*`)
- [ ] Default route (`__default__`)
- [ ] Return directive (`return 200 "OK"`)
- [ ] Конфликт маршрутов
### 3. Security Extension (`security_test.go`)
- [ ] IP whitelist
- [ ] IP blacklist
- [ ] CIDR нотация (10.0.0.0/8)
- [ ] Security headers (X-Frame-Options, X-Content-Type-Options)
- [ ] Rate limiting
- [ ] Комбинация с другими extensions
### 4. Caching Extension (`caching_test.go`)
- [ ] Cache hit/miss
- [ ] TTL expiration
- [ ] Pattern-based caching
- [ ] Cache-Control headers
- [ ] Cache invalidation
- [ ] Max cache size и eviction
### 5. Static Files (`static_files_test.go`)
- [ ] Serving статических файлов
- [ ] Index file (index.html)
- [ ] MIME types
- [ ] Cache-Control для static
- [ ] SPA fallback
- [ ] Directory traversal protection
- [ ] 404 для несуществующих файлов
### 6. Extension Chain (`extension_chain_test.go`)
- [ ] Порядок выполнения extensions (security → caching → routing)
- [ ] Прерывание цепочки при ошибке
- [ ] Совместная работа extensions
## Запуск тестов
```bash
# Все интеграционные тесты
go test ./tests/integration/... -v
# Конкретный файл
go test ./tests/integration/... -v -run TestReverseProxy
# С таймаутом (интеграционные тесты медленнее)
go test ./tests/integration/... -v -timeout 60s
# С покрытием
go test ./tests/integration/... -v -coverprofile=coverage.out
```
## Требования
- Свободные порты: тесты используют случайные порты (`:0`)
- Сетевой доступ: для localhost соединений
- Время: интеграционные тесты занимают больше времени (~5-10 сек)
## Добавление новых тестов
1. Создайте файл `*_test.go` в `tests/integration/`
2. Используйте хелперы из `helpers_test.go`:
- `startTestServer()` — запуск Konduktor сервера
- `startBackend()` — запуск mock backend
- `makeRequest()` — отправка HTTP запроса
3. Добавьте описание в этот README
## CI/CD
Интеграционные тесты запускаются отдельно от unit-тестов:
```yaml
# .github/workflows/test.yml
jobs:
unit-tests:
run: go test ./internal/...
integration-tests:
run: go test ./tests/integration/... -timeout 120s
```