Илья Глазунов bd0b381195 feat(caching): Implement cache hit detection and response header management
- Added functionality to mark responses as cache hits to prevent incorrect X-Cache headers.
- Introduced setCacheHitFlag function to traverse response writer wrappers and set cache hit flag.
- Updated cachingResponseWriter to manage cache hit state and adjust X-Cache header accordingly.
- Enhanced ProcessRequest and ProcessResponse methods to utilize new caching logic.

feat(extension): Introduce ResponseWriterWrapper and ResponseFinalizer interfaces

- Added ResponseWriterWrapper interface for extensions to wrap response writers.
- Introduced ResponseFinalizer interface for finalizing responses after processing.

refactor(manager): Improve response writer wrapping and finalization

- Updated Manager.Handler to wrap response writers through all enabled extensions.
- Implemented finalization of response writers after processing requests.

test(caching): Add comprehensive integration tests for caching behavior

- Created caching_test.go with tests for cache hit/miss, TTL expiration, pattern-based caching, and more.
- Ensured that caching logic works correctly for various scenarios including query strings and error responses.

test(routing): Add integration tests for routing behavior

- Created routing_test.go with tests for route priority, case sensitivity, default routes, and return directives.
- Verified that routing behaves as expected with multiple regex routes and named groups.
2025-12-12 01:03:32 +03:00

135 lines
5.1 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`)
- [x] Базовое проксирование GET/POST/PUT/DELETE
- [x] Exact match routes (`=/api/version`)
- [x] Regex routes с параметрами (`~^/api/resource/(?P<id>\d+)$`)
- [x] Подстановка параметров в target URL (`{id}`, `{tag}`)
- [x] Подстановка переменных в заголовки (`$remote_addr`)
- [x] Передача заголовков X-Forwarded-For, X-Real-IP
- [x] Сохранение query string
- [x] Обработка ошибок backend (502, 504)
- [x] Таймауты соединения
### 2. Routing Extension (`routing_test.go`)
- [x] Приоритет маршрутов (exact > regex > default)
- [x] Case-sensitive regex (`~`)
- [x] Case-insensitive regex (`~*`)
- [x] Default route (`__default__`)
- [x] Return directive (`return 200 "OK"`)
- [x] Regex с именованными группами
- [x] Множественные regex маршруты
- [x] Кастомные заголовки в маршрутах
- [x] Обработка отсутствия маршрута
### 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`)
- [x] Cache hit/miss
- [x] TTL expiration
- [x] Pattern-based caching
- [x] Cache-Control headers (X-Cache header)
- [x] Кэширование только GET запросов
- [x] Разные пути = разные ключи кэша
- [x] Query string влияет на ключ кэша
- [x] Ошибки не кэшируются
- [x] Конкурентный доступ к кэшу
- [x] Множественные паттерны кэширования
### 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
```