Skip to content

Comments

Improve code coverage#120

Open
MohamedSabthar wants to merge 18 commits intoballerina-platform:mainfrom
MohamedSabthar:code-cov
Open

Improve code coverage#120
MohamedSabthar wants to merge 18 commits intoballerina-platform:mainfrom
MohamedSabthar:code-cov

Conversation

@MohamedSabthar
Copy link
Member

@MohamedSabthar MohamedSabthar commented Feb 19, 2026

Purpose

Fixes:

Examples

Checklist

  • Linked to an issue
  • Updated the changelog
  • Added tests
  • Updated the spec
  • Checked native-image compatibility

This pull request updates coverage and build configurations, adds targeted tests for AI providers and HTTP tooling, and removes an unused dispatcher service file to align repository structure and coverage with the AI module.

Key changes

  • Narrow coverage scope in Gradle builds (ballerina/build.gradle and ballerina-tests/build.gradle) by changing broad ballerina.* includes to focus on the AI module (io.ballerina.stdlib.ai*:ballerina.ai*), so coverage reporting targets the intended package.
  • Update codecov.yml:
    • Fixes compiler-plugin path mapping to the repository layout.
    • Adds ignore entries (ballerina-tests, native/src/test, ballerina/modules/intelligence, ballerina/modules/observe) to exclude generated/native tests and modules requiring manual verification.
    • Adds coverage settings: rounding (round: down), range ("60...80"), and a project default target of 80%.
  • Tests added:
    • ballerina/tests/http-service-toolkit-execution-test.bal — parameterized HTTP service toolkit tests covering multiple methods, header handling, and not-found responses using a mock service.
    • ballerina/tests/wso2-embedding-provider-test.bal — mock embedding service and tests for single/batch embeddings and error handling.
    • ballerina/tests/wso2-model-provider-test.bal — mock model/chat service and tests covering text and function-call responses, temperature and multi-message scenarios.
    • ballerina/tests/to_json_schema_test.bal — comprehensive tests for JSON Schema generation utilities (isSimpleType, type string mapping, arrays, nilable types, and error handling).
  • Removal:
    • Deletes ballerina/dispatcher_service.bal, removing the DispatcherService file and its public methods for registering/deregistering chat services and forwarding chat messages.

No public API additions aside from the new test modules; the DispatcherService public API was removed. Commit history includes a test-focused commit ("Add test for to_json_schema").

@coderabbitai
Copy link

coderabbitai bot commented Feb 19, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Narrowed test/coverage filters to AI-specific packages, updated codecov paths/ignores/thresholds, removed the DispatcherService implementation, and added several new Ballerina test modules that start mock HTTP services to exercise AI-related providers and an HTTP toolkit.

Changes

Cohort / File(s) Summary
Gradle build files
ballerina-tests/build.gradle, ballerina/build.gradle
Restricted test coverage/include patterns from ballerina.* to AI-only (io.ballerina.stdlib.ai*:ballerina.ai*), changing which packages are included in test invocation and coverage.
Codecov configuration
codecov.yml
Adjusted fixes path, added ignore entries (native/src/test, ballerina/modules/intelligence, ballerina/modules/observe), and expanded coverage settings (round: down, range: 60...80, default/target: 80).
New tests — HTTP toolkit
ballerina/tests/http-service-toolkit-execution-test.bal
Adds parameterized tests that spin a mock HTTP service on port 9095 and validate HttpToolKit execution across GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS, custom headers, and 404 handling.
New tests — WSO2 embedding & model providers
ballerina/tests/wso2-embedding-provider-test.bal, ballerina/tests/wso2-model-provider-test.bal
Adds mock HTTP services (e.g., port 9097 / chat/completions) and tests for embedding and model/chat provider behaviors, covering single/batch embeddings and function-call/tool responses.
New tests — JSON schema utilities
ballerina/tests/to_json_schema_test.bal
Adds comprehensive tests for JSON Schema generation utilities (simple types, arrays, nilable types, error cases).
Removed implementation
ballerina/dispatcher_service.bal
Deleted the DispatcherService class and its public methods/resources (addServiceRef, removeServiceRef, post chatMessage) and related private function executeRemoteFunc, removing service registration and chat-message forwarding logic.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • shafreenAnfar
  • RadCod3

Poem

🐰 I hopped through lines in nimble cheer,
Tuned the scope so tests stay near,
Mock servers hummed on ports in tune,
Lost a dispatcher, gained test fest soon,
A carrot clap — code springtime near! 🥕

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Improve code coverage' is partially related to the changeset; it references codecov configuration updates but does not capture the primary changes including new test modules and removal of DispatcherService. Consider a more descriptive title that captures the main changes, such as 'Add HTTP toolkit and embedding provider tests, update codecov config' or clarify if 'code coverage' is the primary objective.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 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.

@MohamedSabthar MohamedSabthar added the Skip GraalVM Check This will skip the GraalVM compatibility check label Feb 19, 2026
@codecov
Copy link

codecov bot commented Feb 19, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 77.96%. Comparing base (82d83c8) to head (0c09526).
⚠️ Report is 12 commits behind head on main.

❌ Your project check has failed because the head coverage (77.96%) is below the target coverage (80.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files
@@              Coverage Diff              @@
##               main     #120       +/-   ##
=============================================
+ Coverage     56.11%   77.96%   +21.85%     
  Complexity      238      238               
=============================================
  Files            80       62       -18     
  Lines          5587     4493     -1094     
  Branches       1098     1032       -66     
=============================================
+ Hits           3135     3503      +368     
+ Misses         2305      843     -1462     
  Partials        147      147               

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link

@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.

🧹 Nitpick comments (2)
ballerina/tests/http-service-toolkit-execution-test.bal (2)

20-21: Consider using the port constant in the URL to avoid duplication.

The port 9095 is hardcoded in both MOCK_HTTP_SVC_PORT and MOCK_HTTP_SVC_URL. Using string interpolation would ensure consistency if the port changes.

♻️ Suggested improvement
 const int MOCK_HTTP_SVC_PORT = 9095;
-const MOCK_HTTP_SVC_URL = "http://localhost:9095/api";
+const string MOCK_HTTP_SVC_URL = string `http://localhost:${MOCK_HTTP_SVC_PORT}/api`;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ballerina/tests/http-service-toolkit-execution-test.bal` around lines 20 -
21, MOCK_HTTP_SVC_URL duplicates the port number from MOCK_HTTP_SVC_PORT; update
MOCK_HTTP_SVC_URL to build the URL using the MOCK_HTTP_SVC_PORT constant (string
interpolation or concatenation) so the port is defined in one place and changing
MOCK_HTTP_SVC_PORT automatically updates MOCK_HTTP_SVC_URL; adjust the
declaration of MOCK_HTTP_SVC_URL to reference MOCK_HTTP_SVC_PORT instead of
hardcoding 9095.

187-210: Custom headers are not validated by the mock service.

The test verifies that HttpServiceToolKit accepts custom headers without error, but the mock service doesn't echo or validate that headers were actually received. Consider enhancing the mock service to return received headers for verification.

♻️ Suggested improvement

Add a resource that echoes headers back:

resource function get echo\-headers(http:Request req) returns json {
    return {
        "X-Custom-Header": check req.getHeader("X-Custom-Header"),
        "X-Request-Id": check req.getHeader("X-Request-Id")
    };
}

Then update the test to use this endpoint and verify the echoed header values.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ballerina/tests/http-service-toolkit-execution-test.bal` around lines 187 -
210, The test testHttpSvcToolKitWithCustomHeaders currently sets customHeaders
on HttpServiceToolKit but the mock service never verifies them; add a resource
function on the mock HTTP service (e.g., resource function get
echo-headers(http:Request req) returns json) that reads and returns the incoming
X-Custom-Header and X-Request-Id values, then change the test's request path to
hit that endpoint (e.g., "/echo-headers" or similar) and assert the returned
JSON contains the expected header values, keeping references to
HttpServiceToolKit, toolkit, ToolStore, and output to locate and update the test
and mock service.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@ballerina/tests/http-service-toolkit-execution-test.bal`:
- Around line 20-21: MOCK_HTTP_SVC_URL duplicates the port number from
MOCK_HTTP_SVC_PORT; update MOCK_HTTP_SVC_URL to build the URL using the
MOCK_HTTP_SVC_PORT constant (string interpolation or concatenation) so the port
is defined in one place and changing MOCK_HTTP_SVC_PORT automatically updates
MOCK_HTTP_SVC_URL; adjust the declaration of MOCK_HTTP_SVC_URL to reference
MOCK_HTTP_SVC_PORT instead of hardcoding 9095.
- Around line 187-210: The test testHttpSvcToolKitWithCustomHeaders currently
sets customHeaders on HttpServiceToolKit but the mock service never verifies
them; add a resource function on the mock HTTP service (e.g., resource function
get echo-headers(http:Request req) returns json) that reads and returns the
incoming X-Custom-Header and X-Request-Id values, then change the test's request
path to hit that endpoint (e.g., "/echo-headers" or similar) and assert the
returned JSON contains the expected header values, keeping references to
HttpServiceToolKit, toolkit, ToolStore, and output to locate and update the test
and mock service.

Copy link

@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.

🧹 Nitpick comments (3)
ballerina/tests/wso2-embedding-provider-test.bal (1)

27-52: Mock service implementation looks correct.

The service properly handles both single input and array input cases, returning appropriate embedding structures. One observation: the authorization validation on line 31-33 returns an error type, but this code path is never exercised by the tests since all tests use the valid "test-token".

Consider adding a negative test case for invalid authorization if you want to verify that error path, or simplify the mock by removing the unused validation.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ballerina/tests/wso2-embedding-provider-test.bal` around lines 27 - 52, Add a
negative test to exercise the authorization failure path: update the test suite
to call the mock service's resource function post embeddings with an invalid
Authorization header (not "Bearer test-token") and assert it returns an error
with message "invalid authorization token"; locate the mock service
implementation (resource function post embeddings) and ensure the test sends
requests to the same listener (MOCK_EMBED_PORT) and verifies the error response
instead of removing the Authorization check so the existing validation is
covered by tests.
ballerina/tests/wso2-model-provider-test.bal (1)

104-112: Temperature parameter is not actually verified.

The test testWso2ModelProviderChatWithCustomTemperature passes a custom temperature (0.2d) to the provider but only verifies that a response is returned. The mock service doesn't validate or echo back the temperature value, so this test doesn't confirm the parameter is correctly propagated.

If the intent is to verify temperature handling, consider having the mock service echo the received temperature in the response and asserting on it. Otherwise, rename the test to clarify it's testing provider instantiation with optional parameters.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ballerina/tests/wso2-model-provider-test.bal` around lines 104 - 112, The
test testWso2ModelProviderChatWithCustomTemperature sets temperature = 0.2d on
Wso2ModelProvider but never verifies it; either update the mock to echo back the
received temperature and assert the echoed value in the test, or rename the test
to reflect it only verifies provider instantiation with optional params. Locate
the test function testWso2ModelProviderChatWithCustomTemperature and the mock
chat endpoint (MOCK_CHAT_URL) used by provider->chat; if choosing the echo
approach, modify the mock to include the temperature in its response and add an
assertion checking that response.content (or a new response field) contains 0.2,
otherwise rename the test to something like
testWso2ModelProviderChatWithOptionalTemperature to avoid implying temperature
behavior is validated.
ballerina/tests/http-service-toolkit-execution-test.bal (1)

187-210: Custom headers test does not verify header propagation.

The test testHttpSvcToolKitWithCustomHeaders creates a toolkit with custom headers but only verifies a 200 response is returned. The mock service doesn't echo or validate that X-Custom-Header and X-Request-Id were received.

To fully validate header propagation, consider modifying the mock service to echo received headers or return them in the response body for assertion.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ballerina/tests/http-service-toolkit-execution-test.bal` around lines 187 -
210, The test testHttpSvcToolKitWithCustomHeaders creates an HttpServiceToolKit
with customHeaders but never asserts that those headers were sent; update the
mock HTTP service used by MOCK_HTTP_SVC_URL (or its handler in the test harness)
to echo back incoming request headers (at least X-Custom-Header and
X-Request-Id) in the response body or response headers, then extend the test
after obtaining ToolOutput output (and casting to HttpOutput) to assert the
echoed values match customHeaders (e.g., check value.body or value.headers
contain "X-Custom-Header":"test-value" and "X-Request-Id":"12345"), keeping
references to HttpServiceToolKit, customHeaders, ToolStore, execute, and
HttpOutput so the assertions validate header propagation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@ballerina/tests/http-service-toolkit-execution-test.bal`:
- Around line 187-210: The test testHttpSvcToolKitWithCustomHeaders creates an
HttpServiceToolKit with customHeaders but never asserts that those headers were
sent; update the mock HTTP service used by MOCK_HTTP_SVC_URL (or its handler in
the test harness) to echo back incoming request headers (at least
X-Custom-Header and X-Request-Id) in the response body or response headers, then
extend the test after obtaining ToolOutput output (and casting to HttpOutput) to
assert the echoed values match customHeaders (e.g., check value.body or
value.headers contain "X-Custom-Header":"test-value" and
"X-Request-Id":"12345"), keeping references to HttpServiceToolKit,
customHeaders, ToolStore, execute, and HttpOutput so the assertions validate
header propagation.

In `@ballerina/tests/wso2-embedding-provider-test.bal`:
- Around line 27-52: Add a negative test to exercise the authorization failure
path: update the test suite to call the mock service's resource function post
embeddings with an invalid Authorization header (not "Bearer test-token") and
assert it returns an error with message "invalid authorization token"; locate
the mock service implementation (resource function post embeddings) and ensure
the test sends requests to the same listener (MOCK_EMBED_PORT) and verifies the
error response instead of removing the Authorization check so the existing
validation is covered by tests.

In `@ballerina/tests/wso2-model-provider-test.bal`:
- Around line 104-112: The test testWso2ModelProviderChatWithCustomTemperature
sets temperature = 0.2d on Wso2ModelProvider but never verifies it; either
update the mock to echo back the received temperature and assert the echoed
value in the test, or rename the test to reflect it only verifies provider
instantiation with optional params. Locate the test function
testWso2ModelProviderChatWithCustomTemperature and the mock chat endpoint
(MOCK_CHAT_URL) used by provider->chat; if choosing the echo approach, modify
the mock to include the temperature in its response and add an assertion
checking that response.content (or a new response field) contains 0.2, otherwise
rename the test to something like
testWso2ModelProviderChatWithOptionalTemperature to avoid implying temperature
behavior is validated.

Copy link

@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.

🧹 Nitpick comments (1)
ballerina/tests/to_json_schema_test.bal (1)

245-283: No coverage for generateJsonSchemaForTypedesc with nilableType = true on scalar types

Every scalar test passes false for nilableType. It's unclear whether the function generates a oneOf schema (analogous to what the nilable-array tests expect) or returns an error when nilableType = true is combined with a simple type. Consider adding at least one case, e.g.:

`@test`:Config {
    groups: ["json-schema", "generateJsonSchemaForTypedesc"]
}
function testGenerateJsonSchemaForNilableStringType() {
    JsonSchema|JsonArraySchema|map<json>|Error result = generateJsonSchemaForTypedesc(string, true);
    // assert the expected shape, e.g. oneOf or error
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ballerina/tests/to_json_schema_test.bal` around lines 245 - 283, Add a test
that calls generateJsonSchemaForTypedesc with nilableType = true for a scalar
(e.g., string) to cover the missing branch; create a new test function (e.g.,
testGenerateJsonSchemaForNilableStringType) alongside the existing tests (like
testGenerateJsonSchemaForStringType) and assert the expected output shape —
either a oneOf schema containing the scalar type and null (e.g., oneOf with
{"type":"string"} and {"type":"null"}) or an Error if that’s the intended
behavior; ensure the test uses the same return type annotation
(JsonSchema|JsonArraySchema|map<json>|Error) and test:assertEquals/assertTrue to
validate the result.
ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f949262 and c39ea42.

📒 Files selected for processing (1)
  • ballerina/tests/to_json_schema_test.bal
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@ballerina/tests/to_json_schema_test.bal`:
- Around line 245-283: Add a test that calls generateJsonSchemaForTypedesc with
nilableType = true for a scalar (e.g., string) to cover the missing branch;
create a new test function (e.g., testGenerateJsonSchemaForNilableStringType)
alongside the existing tests (like testGenerateJsonSchemaForStringType) and
assert the expected output shape — either a oneOf schema containing the scalar
type and null (e.g., oneOf with {"type":"string"} and {"type":"null"}) or an
Error if that’s the intended behavior; ensure the test uses the same return type
annotation (JsonSchema|JsonArraySchema|map<json>|Error) and
test:assertEquals/assertTrue to validate the result.

@MohamedSabthar MohamedSabthar changed the title [WIP] Fix codecov path Improve code coverage Feb 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Skip GraalVM Check This will skip the GraalVM compatibility check

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant