Skip to content

Test/improve code cov#914

Merged
Krishanx92 merged 15 commits intowso2:mainfrom
Saadha123:test/improve-code-cov
Feb 5, 2026
Merged

Test/improve code cov#914
Krishanx92 merged 15 commits intowso2:mainfrom
Saadha123:test/improve-code-cov

Conversation

@Saadha123
Copy link
Contributor

@Saadha123 Saadha123 commented Feb 3, 2026

Purpose

Improve unit test coverage for the gateway-controller component to catch regressions and ensure code reliability.

Goals

Add unit tests for pkg/config, pkg/controlplane, pkg/utils, and pkg/xds packages.

Approach

Added new tests across 5 test files:

  • llm_validator_additional_test.go
    
  • controlplane_test.go
    
  • api_deployment_test.go
    
  • api_key_test.go
    
  • translator_test.go
    

User stories

Summary of user stories addressed by this change>

Documentation

Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter “N/A” plus brief explanation of why there’s no doc impact

Automation tests

  • Unit tests

    Code coverage information

  • Integration tests

    Details about the test cases and coverage

Security checks

Samples

Provide high-level details about the samples related to this feature

Related PRs

List any other related PRs

Test environment

List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested

Summary by CodeRabbit

  • Tests

    • Expanded unit tests for LLM configuration validation (nil/malformed inputs, metadata/name/version/URL checks and exact error messages).
    • Extended control‑plane client tests for connection, heartbeat/reconnect, retry backoff, lifecycle, event handling, and concurrent state access.
    • Added tests for API deployment/WebSub/topic flows, API key expiry/regeneration, XDS/WebSub translation, and end‑to‑end LLM provider API invocation scenarios (proxy invocation scenarios duplicated).
  • Tests (Integration)

    • New health-step to poll an endpoint with an arbitrary HTTP method and request body.
  • Chores

    • Internal proxy-to-provider routing simplified to use local HTTP loopback.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 3, 2026

Walkthrough

Adds extensive test coverage and integration scenarios across gateway-controller and integration tests, a new health-step for polling endpoints with method/body, and a production change forcing LLM internal upstreams to use http://localhost:<port> for loopback routing.

Changes

Cohort / File(s) Summary
LLM Validation Tests
gateway/gateway-controller/pkg/config/llm_validator_additional_test.go
New unit tests for LLMValidator covering nil checks, metadata.name rules, spec/version/format validation, upstream URL/scheme checks, access control, and detailed field-level error assertions.
Control Plane Client Tests
gateway/gateway-controller/pkg/controlplane/controlplane_test.go
Added tests for client lifecycle and state: connect error paths, heartbeat timeout detection, connection loop/backoff, Start/Stop, concurrent state access, message handling, and API deploy/undeploy event handling.
API Deployment / WebSub Tests
gateway/gateway-controller/pkg/utils/api_deployment_test.go
New tests for WebSub parsing errors, topic register/deregister flows, hub communication timeouts/errors, memory-store rollback on save/update, DeployAPIConfiguration scenarios, UUID handling, and timeout/connection error paths.
API Key Expiration Tests
gateway/gateway-controller/pkg/utils/api_key_test.go
Tests for API key generation/regeneration expiration behavior: ExpiresIn handling, past expiry rejection, inheritance of existing durations, absolute expiry behavior, and related error cases.
XDS WebSub Translation Tests
gateway/gateway-controller/pkg/xds/translator_test.go
Extensive tests for WebSub/AsyncAPI translation: URL parsing edge cases, listener/cluster generation (HTTP/HTTPS), TLS and transport socket checks, dynamic forward proxy listeners, access logs/tracing permutations, and a createTestTranslator() helper.
Integration Feature Scenarios
gateway/it/features/llm-provider.feature, gateway/it/features/llm-proxies.feature
Added API invocation scenarios for LLM providers and proxies (create resources, invoke chat/completions, validate responses, cleanup). Note: llm-proxies.feature contains duplicated scenario blocks.
Health Step (IT)
gateway/it/steps_health.go
Added step I wait for the endpoint "<url>" to be ready with method "<method>" and body '<body>' and implementation iWaitForEndpointToBeReadyWithMethodAndBody to poll endpoints with arbitrary HTTP methods and bodies until 200 OK or timeout.
LLM Transformer (runtime change)
gateway/gateway-controller/pkg/utils/llm_transformer.go
Production change: internal upstream construction now always uses http://localhost:<listenerPort> (SchemeHTTP + localhost) for provider loopback routing, removing previous dynamic HTTP/HTTPS selection and TLS considerations.
Misc Test Helpers & Imports
various ..._test.go files
Added imports and small test helpers across tests (httptest, net/http, Envoy test types, sync/atomic, context, etc.) to support new scenarios.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐇 I hopped through tests both near and far,
sniffed nils, URLs, and heartbeat sparks,
nudged proxies to localhost paths,
chased WebSub topics, keys, and marks,
now CI carrots wink — ready for flight! 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning The description addresses Purpose, Goals, and Approach sections but leaves most required sections (User stories, Documentation, Automation tests details, Security checks, Samples, Related PRs, Test environment) incomplete with placeholder text. Complete all template sections: clarify documentation impact, provide specific code coverage metrics, detail security verification, list test environment specifics, and address all placeholder sections with actual content.
Title check ❓ Inconclusive The title 'Test/improve code cov' is vague and uses an abbreviation; it doesn't clearly convey the main change even though it relates to test improvements. Expand the title to be more descriptive, e.g., 'Add comprehensive unit tests for gateway-controller packages' or 'Improve gateway-controller test coverage across config, controlplane, utils, and xds'.
✅ Passed checks (1 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🤖 Fix all issues with AI agents
In `@gateway/gateway-controller/pkg/controlplane/controlplane_test.go`:
- Around line 580-597: The test currently ignores the error returned by
client.Start(); update the "Client lifecycle with Start and Stop" subtest to
capture and assert the Start() error (e.g., err := client.Start()) and fail the
test if it returns non-nil so failures aren't silently ignored; keep the rest of
the flow (sleep, client.Stop(), and IsConnected() assertion) intact and
reference the same createTestClient, Start, Stop and IsConnected calls.
- Around line 651-667: The test TestClient_CalculateNextRetryDelay_CappedAtMax
is calling calculateNextRetryDelay() repeatedly but never increments
client.state.RetryCount, so the exponential backoff never progresses and the max
cap isn't exercised; update the loop to increment client.state.RetryCount on
each iteration (or set it appropriately before each call) so
calculateNextRetryDelay uses increasing retry counts, ensuring
client.state.NextRetryDelay can reach and be capped by
client.config.ReconnectMax; reference the calculateNextRetryDelay method and
client.state.RetryCount (created via createTestClient) when making the change.
- Around line 478-540: The tests use long fixed sleeps and the second subtest
doesn't call the real monitor; replace the custom goroutine in the second
subtest with a real invocation of client.heartbeatMonitor() (use
client.wg.Add(1) and go client.heartbeatMonitor()), and shorten both waits by
deriving them from the client's monitoring parameters: set/compare
atomic.StoreInt64(&client.state.LastHeartbeat, ...) and then sleep for small,
calculated durations like a fraction of client.heartbeatTimeout or
client.heartbeatInterval plus a small margin so the "timeout" case sleeps just
past the timeout and the "recent heartbeat" case sleeps well under the timeout;
ensure you still close(client.stopChan) and client.wg.Wait() after each subtest.

In `@gateway/gateway-controller/pkg/utils/api_deployment_test.go`:
- Around line 415-523: The tests in
TestDeployAPIConfiguration_WebSubTopicOperations assume port 8084 is free,
causing flakiness; replace the hardcoded port usage in the test setup by
creating an in-process deterministic HTTP test server via httptest.NewServer
that simulates the failing WebSub hub (returning non-200 or delayed responses)
and configure the APIDeploymentService routerConfig.EventGateway to point at
that server (use the server's listener address/port or URL) so
DeployAPIConfiguration and any topic operations hit the controllable server;
ensure the test server is closed at the end of each subtest to avoid port leaks
and keep references like NewAPIDeploymentService, DeployAPIConfiguration, and
store.TopicManager unchanged.

In `@gateway/gateway-controller/pkg/xds/translator_test.go`:
- Around line 1107-1178: The tests call Configuration.Spec.FromWebhookAPIData
and currently discard its returned error (e.g. "_ =
webhookConfig.Configuration.Spec.FromWebhookAPIData(...)") which can hide setup
failures; update both calls in TestTranslator_TranslateAsyncAPIConfig to assert
the setup succeeded by replacing the ignored assignment with require.NoError(t,
webhookConfig.Configuration.Spec.FromWebhookAPIData(...)) so any
parsing/validation errors surface before calling
translator.translateAsyncAPIConfig and make the test assertions meaningful.
🧹 Nitpick comments (3)
gateway/gateway-controller/pkg/utils/api_deployment_test.go (3)

21-23: Rebuild gateway images and run gateway-controller unit tests before verification.

These changes touch a gateway component, so rebuild local gateway images before validating, and run the gateway-controller unit suite.

As per coding guidelines: gateway/**/*.{go,yaml,yml,Dockerfile}: When modifying code in gateway components (gateway-controller, policy-engine, router, etc., excluding gateway/it/), rebuild Docker images using cd gateway && make build-local.
Based on learnings: Run unit tests for gateway-controller using cd gateway/gateway-controller && go test ./....


525-607: Test name doesn’t match behavior.

Both subtests cover success paths, but the function name implies a failure scenario.

✏️ Rename to reflect what’s actually tested
-func TestSaveOrUpdateConfig_MemoryStoreFailure(t *testing.T) {
+func TestSaveOrUpdateConfig_MemoryStoreSuccessPaths(t *testing.T) {

609-663: “Rollback” test only exercises the success path.

Consider renaming or add a failing store stub if you want rollback coverage.

✏️ Rename if keeping success-only coverage
-func TestUpdateExistingConfig_Rollback(t *testing.T) {
+func TestUpdateExistingConfig_SuccessPath(t *testing.T) {

@Krishanx92 Krishanx92 merged commit bb1e87d into wso2:main Feb 5, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants