This directory contains comprehensive unit tests for the C++ HTTP Server implementation using Google Test framework.
- Total Test Cases: 138 tests across 10 test suites (all passing)
- Testing Framework: Google Test (gtest)
- Coverage: Core HTTP server functionality including request parsing, response generation, server configuration, thread pool management, security testing, performance validation, comprehensive HTTP/1.1 protocol compliance including chunked transfer encoding, full HTTPS/SSL support, complete WebSocket implementation with RFC 6455 compliance, advanced rate limiting with multiple algorithms, and ETag conditional request handling
# Using the build script (recommended)
./scripts/build.sh debug --tests
# Or manually with CMake
mkdir -p build && cd build
cmake -DBUILD_TESTING=ON ..
cmake --build .
./test_runner
# Or build with debug configuration (automatically enables testing)
cmake -DCMAKE_BUILD_TYPE=Debug ..
cmake --build .
./test_runner# Run only HttpServerTest suite
./test_runner --gtest_filter="HttpServerTest.*"
# Run only HttpRequestTest suite
./test_runner --gtest_filter="HttpRequestTest.*"
# Run only HttpResponseTest suite
./test_runner --gtest_filter="HttpResponseTest.*"
# Run only SecurityTest suite
./test_runner --gtest_filter="SecurityTest.*"
# Run only PerformanceTest suite
./test_runner --gtest_filter="PerformanceTest.*"
# Run only HttpProtocolTest suite
./test_runner --gtest_filter="HttpProtocolTest.*"
# Run only HttpsServerTest suite
./test_runner --gtest_filter="HttpsServerTest.*"
# Run only WebSocketTest suite
./test_runner --gtest_filter="WebSocketTest.*"
# Run only RateLimiterTest suite
./test_runner --gtest_filter="RateLimiterTest.*"
# Run only ETagTest suite
./test_runner --gtest_filter="ETagTest.*"# Run a specific test
./test_runner --gtest_filter="HttpServerTest.ServerConfigDefaults"
# Run tests matching a pattern
./test_runner --gtest_filter="*Config*"
# Run only HTTPS-related tests
./test_runner --gtest_filter="*Https*"
# Run SSL-specific functionality tests
./test_runner --gtest_filter="*Ssl*"
# Run only WebSocket-related tests
./test_runner --gtest_filter="*WebSocket*"
# Run only rate limiting tests
./test_runner --gtest_filter="*RateLimit*"File: test_server.cpp
Tests the core HTTP server functionality, configuration management, and thread pool operations.
ServerConfigDefaults- Validates default server configuration valuesServerConfigFromJson- Tests JSON configuration file parsing and loadingServerConfigToJson- Tests configuration serialization to JSON formatConfigurationUpdate- Tests runtime configuration updatesConfigFileHandling- Tests reading configuration from fileConfigFileNotFound- Tests handling of missing configuration filesInvalidJsonConfig- Tests error handling for malformed JSON configuration
ServerCreation- Tests HTTP server instantiation and initializationRouteRegistration- Tests adding and managing HTTP routesMultipleRouteTypes- Tests registration of different HTTP method routesMiddlewareRegistration- Tests middleware pipeline setup and registration
StaticFileConfiguration- Tests static file serving configurationMimeTypeConfiguration- Tests MIME type mapping configurationDefaultMimeTypeInitialization- Tests default MIME type setup
StatisticsInitialization- Tests server statistics system initializationStatisticsJsonSerialization- Tests statistics data serialization to JSON
ThreadPoolInitialization- Tests thread pool creation and setupThreadPoolTaskExecution- Tests basic task execution in thread poolThreadPoolTaskWithParameters- Tests parameterized task executionThreadPoolException- Tests exception handling in thread pool tasksThreadPoolShutdown- Tests proper thread pool shutdown and cleanupThreadPoolStoppedEnqueue- Tests task submission to stopped thread pool
File: test_request.cpp
Tests HTTP request parsing, validation, and data extraction functionality.
ParseSimpleGetRequest- Tests parsing basic GET requestsParsePostRequestWithBody- Tests parsing POST requests with body contentParseRequestWithQueryParams- Tests URL query parameter extractionParseDifferentHttpMethods- Tests support for various HTTP methods (GET, POST, PUT, DELETE, etc.)
MethodToStringConversion- Tests converting HTTP method enums to stringsStringToMethodConversion- Tests parsing HTTP method strings to enums
HeaderCaseInsensitivity- Tests case-insensitive header name handlingLargeHeaderValues- Tests handling of headers with large values
KeepAliveDetection- Tests HTTP keep-alive connection detectionInvalidRequests- Tests error handling for malformed HTTP requestsToStringRoundTrip- Tests request serialization and deserializationSpecialCharactersInPath- Tests URL path handling with special characters
File: test_response.cpp
Tests HTTP response generation, header management, and content handling.
DefaultConstructor- Tests default HTTP response initializationStatusConstructor- Tests response creation with specific status codesSetAndGetStatus- Tests status code setting and retrieval
HeaderManagement- Tests adding, updating, and removing response headersHeaderCaseNormalization- Tests header name case normalizationSpecialHeaders- Tests handling of special HTTP headers (Content-Length, etc.)
BodyManagement- Tests response body setting and retrievalContentTypeHelpers- Tests content type header management utilitiesLargeBodyHandling- Tests handling of large response bodiesEmptyBodyHandling- Tests handling of empty response bodies
FileContent- Tests serving file content as HTTP responseMimeTypeDetection- Tests automatic MIME type detection for files
StaticFactoryMethods- Tests convenience methods for creating common responsesStatusMessages- Tests HTTP status code to message mappingFluentInterface- Tests method chaining for response building
HttpStringGeneration- Tests conversion of response to HTTP protocol stringToStringDebugOutput- Tests debug string representation of responses
File: test_security.cpp
Tests security aspects of the HTTP server including protection against common vulnerabilities.
PathTraversalPrevention- Tests protection against directory traversal attacksRequestSizeLimits- Tests enforcement of request size limits to prevent DoSHeaderInjectionPrevention- Tests prevention of HTTP header injection attacks through CRLF validation
HttpMethodSecurity- Tests handling of potentially dangerous HTTP methodsUrlEncodingSecurity- Tests proper URL encoding and decoding securityContentTypeValidation- Tests validation of Content-Type headers
SecurityHeaders- Tests implementation of security-related HTTP headersCookieSecurity- Tests secure cookie handling and attributesRateLimitingConcept- Tests rate limiting mechanisms and concepts
File: test_performance.cpp
Tests performance, concurrency, and scalability aspects of the HTTP server.
ConcurrentRequestParsing- Tests parsing 1000 concurrent HTTP requestsConcurrentStatisticsUpdates- Tests thread-safe statistics updatesThreadPoolStressTest- Tests thread pool under high concurrent load
MemoryUsageUnderLoad- Tests memory usage patterns under sustained loadMemoryFragmentation- Tests memory allocation patterns and fragmentationLargeResponseGeneration- Tests generation of large HTTP responses
RapidConfigurationUpdates- Tests rapid configuration changesMalformedHttpParsing- Tests performance of parsing malformed HTTP data
BinaryDataHandling- Tests handling of large binary data in requestsTimeoutSimulation- Tests timeout handling and resource cleanup
File: test_http_protocol.cpp
Tests advanced HTTP/1.1 protocol compliance including chunked encoding, compression, and protocol-specific features. All chunked transfer encoding features are fully implemented and tested.
ChunkedEncodingParsing- Tests parsing of chunked transfer encodingChunkedEncodingWithEmptyChunks- Tests handling of empty chunksChunkedEncodingWithExtensions- Tests chunk extensions supportChunkedEncodingResponse- Tests generation of chunked responses
GzipCompressionSupport- Tests gzip compression and decompression utilitiesContentEncodingHeaders- Tests Content-Encoding header handlingAcceptEncodingProcessing- Tests Accept-Encoding header parsing
PersistentConnections- Tests HTTP/1.1 keep-alive connection handlingTransferEncodingPriority- Tests Transfer-Encoding vs Content-Length priorityMultipleTransferEncodings- Tests multiple transfer encoding valuesHostHeaderRequired- Tests HTTP/1.1 Host header requirement validation
UpgradeHeader- Tests protocol upgrade mechanisms (WebSocket handshake)ExpectContinue- Tests Expect: 100-continue header supportRangeRequests- Tests HTTP range request and partial content supportTrailerHeaders- Tests trailer headers with chunked encodingHttpVersionValidation- Tests HTTP version validation and compatibility
Note: All tests are currently passing.
File: test_https.cpp
Tests HTTPS/SSL functionality including SSL context initialization, certificate handling, and encrypted connections.
HttpsConfigurationParsing- Tests parsing of HTTPS-specific configuration from JSONHttpsConfigurationSerialization- Tests serialization of HTTPS configuration to JSONMixedHttpHttpsConfiguration- Tests mixed HTTP and HTTPS server configurationHttpsDisabledConfiguration- Tests server behavior when HTTPS is disabled
HttpsServerInitialization- Tests HTTPS server initialization with SSL contextSslContextValidation- Tests SSL context creation and certificate loadingSslConnectionBasics- Tests basic SSL connection handling and lifecycle
HttpsStatisticsTracking- Tests statistics collection for HTTPS connectionsHttpsConfigFileLoading- Tests loading HTTPS configuration from external filesHttpsRoutingBasics- Tests HTTP routing functionality over SSL connectionsSslCipherConfiguration- Tests SSL cipher suite configuration and validation
Dependencies: Requires OpenSSL for SSL/TLS support and test certificates for validation.
File: test_websocket.cpp
Tests comprehensive WebSocket functionality including RFC 6455 protocol compliance, frame handling, connection management, and real-time communication features.
FrameSerializationAndParsing- Tests WebSocket frame serialization and parsing with various opcodesBinaryFrameHandling- Tests handling of binary WebSocket frames and data integrityMaskedFrames- Tests client-side frame masking and unmasking according to RFC 6455ControlFrames- Tests PING, PONG, and CLOSE control frame handling
KeyGeneration- Tests WebSocket key generation and Sec-WebSocket-Accept computationRequestValidation- Tests WebSocket handshake request validation and header checkingInvalidRequestHandling- Tests rejection of invalid WebSocket upgrade requestsHandshakeResponseGeneration- Tests proper WebSocket handshake response generation
RouteRegistration- Tests WebSocket route registration in HTTP serverServerStatistics- Tests WebSocket connection statistics trackingConnectionStateManagement- Tests WebSocket connection lifecycle and state transitions
FrameSizeLimits- Tests enforcement of WebSocket frame size limitsFrameParsingErrors- Tests error handling for malformed WebSocket framesFramePerformance- Tests WebSocket frame processing performance under load
ProtocolCompliance- Tests comprehensive RFC 6455 protocol complianceConcurrentOperations- Tests thread-safe WebSocket operations and concurrent connectionsConnectionCleanup- Tests proper WebSocket connection cleanup and resource management
Dependencies: Requires Boost.Asio for async I/O and OpenSSL for SHA1 hashing in handshake processing.
File: test_rate_limiter.cpp
Tests comprehensive rate limiting functionality including multiple algorithms, key extraction strategies, middleware integration, and protection against abuse.
TokenBucketAllowsBurstRequests- Tests token bucket algorithm allowing burst capacity requests immediatelyTokenBucketRefillsOverTime- Tests token bucket refill mechanism over time intervalsFixedWindowEnforcesLimit- Tests fixed window algorithm enforcing request limits per time windowFixedWindowResetsAfterDuration- Tests fixed window reset behavior after time window expiresSlidingWindowEnforcesLimit- Tests sliding window algorithm with timestamp-based tracking
DifferentClientsHaveSeparateLimits- Tests that different clients (by IP) have separate rate limitsCustomKeyExtractor- Tests custom key extraction functions for user-based limitingKeyExtractors- Tests various built-in key extractors (IP, API key, user ID, endpoint path)
DisabledLimiterAllowsAllRequests- Tests that disabled rate limiter allows unlimited requestsConfigurationUpdate- Tests runtime configuration updates and algorithm switchingMiddlewareIntegration- Tests rate limiting middleware integration with HTTP pipeline
ConcurrentAccess- Tests thread-safe concurrent access to rate limiting algorithmsCleanupExpiredEntries- Tests automatic cleanup of expired rate limiting entries
Features Tested:
- Token Bucket: Burst handling, refill rates, capacity management
- Fixed Window: Request counting, window resets, limit enforcement
- Sliding Window: Timestamp tracking, rolling window behavior
- Key Strategies: IP-based, user-based, API key-based, endpoint-based limiting
- Middleware: HTTP 429 responses, rate limit headers, custom responses
- Configuration: JSON config, runtime updates, algorithm switching
- Concurrency: Thread-safe operations, concurrent client handling
- Cleanup: Automatic expired entry removal, memory management
File: test_etag.cpp
Tests ETag generation, conditional request handling, and HTTP cache validation functionality.
GenerateETag- Tests ETag generation from content strings with consistent hashingGenerateFileETag- Tests file-based ETag generation using file metadata and modification timesSetAndGetETag- Tests ETag header setting and retrieval with strong and weak ETag formats
ConditionalRequestHeaders- Tests If-None-Match and If-Modified-Since header parsing and detectionETagMatching- Tests ETag comparison logic including weak ETags, multiple ETags, and wildcard matchingLastModified- Tests Last-Modified header setting, formatting, and time handling
ConditionalFileResponse_NotModified_ETag- Tests HTTP 304 Not Modified responses for unchanged files using ETagsConditionalFileResponse_NotModified_LastModified- Tests Last-Modified header infrastructure and conditional request handlingConditionalFileResponse_Modified- Tests full file responses when content has been modified
HTTPTimeFormatting- Tests HTTP date/time formatting for cache headersCacheHeaders- Tests cache control headers including public caching and max-age directives
Features Tested:
- ETag Generation: Content-based and file-based ETag creation with consistent hashing
- Conditional Requests: If-None-Match header processing and HTTP 304 responses
- Cache Headers: Last-Modified, Cache-Control, and ETag header management
- File Modification Detection: File timestamp tracking and modification detection
- HTTP Time Formatting: RFC 1123 date formatting for cache-related headers
- Weak vs Strong ETags: Proper handling of both ETag validation types
The tests use various mock data and fixtures:
- Sample HTTP Requests: GET, POST, PUT, DELETE requests with different headers and bodies
- WebSocket Frames: Various frame types including text, binary, control frames with different sizes and masking
- WebSocket Handshakes: Valid and invalid WebSocket upgrade requests and response validation
- Rate Limiting Scenarios: Multiple client IPs, user IDs, API keys, different algorithms and configurations
- HTTPS Test Certificates: Self-signed certificates for SSL/TLS testing
- Configuration Files: Valid and invalid JSON configuration samples including HTTPS settings and rate limiting policies
- Static Files: Mock file content for testing file serving functionality
- Error Scenarios: Malformed requests, invalid configurations, network errors, SSL handshake failures, invalid WebSocket frames, rate limit violations
- Google Test: Unit testing framework (automatically fetched by CMake)
- nlohmann/json: JSON parsing and serialization
- Boost.Asio: Networking and I/O operations
- OpenSSL: SSL/TLS support for HTTPS functionality
- ZLIB: Compression support for testing
- C++20: Modern C++ features used throughout the codebase
All dependencies except the C++ compiler are automatically fetched and configured by CMake.
HTTPS Testing Requirements: HTTPS tests require OpenSSL to be installed on the system. Test certificates are automatically generated in the certs/ directory for development and testing purposes.
The test suite validates:
HTTP Protocol Compliance: Request/response parsing and generation
HTTPS/SSL Support: Certificate handling, SSL context management, encrypted connections
WebSocket Implementation: RFC 6455 compliance, frame handling, connection management, real-time communication
Rate Limiting: Multiple algorithms (Token Bucket, Fixed Window, Sliding Window), key extraction, middleware integration
Configuration Management: JSON config loading, validation, and updates
Concurrency: Thread pool operations and thread safety
Error Handling: Graceful handling of invalid inputs and edge cases
File Operations: Static file serving and MIME type detection
Performance: Large data handling and resource management
Standards Compliance: HTTP headers, status codes, and method handling
When adding new test cases:
- Follow the existing naming convention:
TestSuite.TestName - Use descriptive test names that explain what is being validated
- Include both positive and negative test cases
- Test edge cases and error conditions
- Keep tests isolated and independent
- Use appropriate Google Test assertions (
EXPECT_*,ASSERT_*)
These tests are automatically executed in the CI/CD pipeline on:
- Every pull request
- Every push to main branch
- Nightly builds across multiple platforms (Ubuntu, macOS)
- Multiple compiler configurations (GCC, Clang)