Илья Глазунов 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

5.1 KiB
Raw Blame History

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")
  • Regex с именованными группами
  • Множественные regex маршруты
  • Кастомные заголовки в маршрутах
  • Обработка отсутствия маршрута

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 (X-Cache header)
  • Кэширование только GET запросов
  • Разные пути = разные ключи кэша
  • Query string влияет на ключ кэша
  • Ошибки не кэшируются
  • Конкурентный доступ к кэшу
  • Множественные паттерны кэширования

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

Запуск тестов

# Все интеграционные тесты
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-тестов:

# .github/workflows/test.yml
jobs:
  unit-tests:
    run: go test ./internal/...
  
  integration-tests:
    run: go test ./tests/integration/... -timeout 120s