Skip to content

Add integration tests for mock endpoint feature#14209

Open
YasasRangika wants to merge 5 commits into
wso2:masterfrom
YasasRangika:mock-ep-tests
Open

Add integration tests for mock endpoint feature#14209
YasasRangika wants to merge 5 commits into
wso2:masterfrom
YasasRangika:mock-ep-tests

Conversation

@YasasRangika

Copy link
Copy Markdown
Contributor

This pull request introduces a comprehensive integration test suite for the mock endpoint (inline mediation script) feature in the API Gateway, following the official Mock Implementation guide. It adds a new test class, supporting OpenAPI and mediation script resources, and updates the test suite configuration to ensure these tests are executed. The main focus is to validate the generation, modification, and invocation of inline mock scripts for APIs, including advanced scenarios such as custom response branching and HTTP status handling.

The most important changes are:

New Integration Test Implementation:

  • Added a new test class MockEndpointIntegrationTestCase that covers end-to-end scenarios for inline mock endpoint implementation, including script generation, manual modification, and runtime invocation with various parameters. The tests verify correct payloads for different petId values and response codes, and ensure the API's implementation type is set to INLINE.

Test Resource Additions:

  • Added petstore_oas.json, an OpenAPI 3.0 definition for the mock pet store API, used as the base for import and testing.
  • Added additionalProperties.json, specifying API import properties such as context, version, policies, and endpoint configuration for the mock API.
  • Added get_pet_modified_mediation_script.js, containing a sample mediation script that demonstrates both generated and manually added logic for response branching and custom HTTP status handling.

Test Suite Configuration:

  • Updated testng.xml to include the new MockEndpointIntegrationTestCase in the integration test suite, ensuring these tests are executed as part of the automated pipeline.

@coderabbitai

coderabbitai Bot commented May 21, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5fc9ee09-3ff9-4c11-bdd6-e228794d0879

📥 Commits

Reviewing files that changed from the base of the PR and between e24ef90 and f773931.

📒 Files selected for processing (1)
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java

📝 Walkthrough

Walkthrough

Adds an integration test and supporting OpenAPI/resources that import a mock petstore OAS as a prototype API, generate and replace mock mediation scripts, deploy the API, create/subscribe an app with JWT keys, invoke gateway mock endpoints across scenarios, and assert responses and API metadata.

Changes

Mock Endpoint Integration Tests

Layer / File(s) Summary
Test Class Structure
all-in-one-apim/.../MockEndpointIntegrationTestCase.java, all-in-one-apim/.../get_pet_modified_mediation_script.js
Test class definition, TestNG factory constructor for multitenant modes, constants, instance state, lifecycle hooks, and classpath resource reader helper.
Environment Setup & Mock Generation
all-in-one-apim/.../petstore_oas.json, all-in-one-apim/.../additionalProperties.json, all-in-one-apim/.../MockEndpointIntegrationTestCase.java
Read OAS and additionalProperties, inject name/provider/context, write OAS to a temp JSON, import the petstore OAS as a prototype API via publisher import, and normalize invocation context.
Apply Custom Mediation Script
all-in-one-apim/.../MockEndpointIntegrationTestCase.java, all-in-one-apim/.../get_pet_modified_mediation_script.js
Load modified mediation JS from classpath, replace GET /pet/{petId} x-mediation-script in the API Swagger, and update the API via restAPIPublisher.updateSwagger.
Gateway Invocation Tests
all-in-one-apim/.../MockEndpointIntegrationTestCase.java
Deploy and wait for readiness, create and subscribe an unlimited-tier JWT application, generate JWT keys and access token, invoke gateway endpoints /pet/0, /pet/1, /pet/0?responseCode=501, and assert statuses and payload markers; verify endpointImplementationType is INLINE.
Teardown / Cleanup
all-in-one-apim/.../MockEndpointIntegrationTestCase.java
Delete the created application if present and call superclass cleanup to remove test artifacts.
Temp File & Import Helpers
all-in-one-apim/.../MockEndpointIntegrationTestCase.java
Helpers to inject name/provider/context into OAS/additionalProperties, write OAS to a temp .json file for import, and read classpath resources as UTF-8.
Test Resources: OpenAPI and Configuration
all-in-one-apim/.../petstore_oas.json, .../additionalProperties.json, .../get_pet_modified_mediation_script.js
OpenAPI v3 petstore specification, additionalProperties JSON for MockPetStore (context, transports, security, inline endpoint), and a mediation script mapping status codes and conditionally overriding the 200 payload.
TestNG Suite Registration
all-in-one-apim/.../testng.xml
Register new MockEndpointIntegrationTestCase in the apim-publisher-tests TestNG suite.
sequenceDiagram
  participant Test as MockEndpointIntegrationTestCase
  participant Publisher as restAPIPublisher
  participant Store as restAPIStore
  participant Gateway as Gateway
  Test->>Publisher: importOASDefinition(temp OAS + additionalProperties)
  Publisher->>Gateway: generate mock scripts / deploy revision
  Test->>Publisher: updateSwagger (apply modified x-mediation-script)
  Test->>Store: create application, subscribe, generate JWT keys
  Test->>Gateway: invoke /pet endpoints with Bearer token
Loading

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title clearly and concisely summarizes the main change: adding integration tests for the mock endpoint feature, which is the core objective of this PR.
Description check ✅ Passed The pull request description is comprehensive and directly related to the changeset, covering the new test class, supporting resources, and test suite configuration updates with clear context about the mock endpoint feature.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java`:
- Around line 187-189: The code calls
getClass().getClassLoader().getResourceAsStream(...) and passes the result
straight into IOUtils.toString(...), which will throw an opaque NPE if the
resource is missing; update both occurrences (the creation of modifiedScript and
the similar block around lines 243-246) to first assign the InputStream to a
local variable (e.g., is =
getClass().getClassLoader().getResourceAsStream(RESOURCE_PATH + "...")), check
if is == null and throw or fail with a clear message that the classpath resource
was not found (including the resource name), then pass the non-null stream to
IOUtils.toString(...). Ensure the streams are closed appropriately
(try-with-resources) and reference the getResourceAsStream and IOUtils.toString
usages for locating the fixes.

In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/get_pet_modified_mediation_script.js`:
- Line 38: Replace the typo in the mock response payload by changing the value
for the JSON key "name" that currently reads "German Sheperd" to the correct
spelling "German Shepherd" so the mock endpoint returns the correct breed name.
- Around line 44-57: The responses object is returning JSON strings for 400 and
404 and a mismatched shape for 501; update responses[400]["application/json"]
and responses[404]["application/json"] to be objects that match the OpenAPI
error schema/example (not the empty string), and change
responses[501]["application/json"] to use the same error object shape and fields
as specified in the OAS example. Locate the assignments to responses[400],
responses[404], and responses[501] in get_pet_modified_mediation_script.js and
replace the string payloads and the current 501 object with objects that mirror
the OpenAPI contract’s error model.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5c75bbab-8b30-42ba-bb75-25eb1054da72

📥 Commits

Reviewing files that changed from the base of the PR and between b1d6bf2 and bd64c6f.

📒 Files selected for processing (5)
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/additionalProperties.json
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/get_pet_modified_mediation_script.js
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/petstore_oas.json
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java`:
- Around line 170-172: Before deserializing the API response, verify that the
HTTP call succeeded: check the HttpResponse returned by
restAPIPublisher.getAPI(apiId) for a successful status (or non-error) and assert
it (e.g., status code or isSuccess) before calling new Gson().fromJson(...).
Update the test around restAPIPublisher.getAPI, HttpResponse apiResponse and
APIDTO apiDto to assert the response is OK and include a helpful message if it
is not, then only deserialize into APIDTO when the response check passes.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 331a9118-552c-4f34-bd12-9399a3aebcce

📥 Commits

Reviewing files that changed from the base of the PR and between bd64c6f and 5c661ab.

📒 Files selected for processing (5)
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/additionalProperties.json
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/get_pet_modified_mediation_script.js
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/petstore_oas.json
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/testng.xml

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java (1)

237-241: 💤 Low value

Consider checking application creation response code for consistency.

For consistency with the pattern at line 194 (where response code is checked before using the data), consider validating the HTTP response code before treating applicationResponse.getData() as a valid application ID. While subsequent operations would fail if creation didn't succeed, an explicit check provides clearer diagnostics.

💡 Suggested improvement
         HttpResponse applicationResponse = restAPIStore.createApplication(
                 APPLICATION_NAME + userMode, "Mock Endpoint Test Application",
                 APIMIntegrationConstants.APPLICATION_TIER.UNLIMITED, ApplicationDTO.TokenTypeEnum.JWT);
+        Assert.assertEquals(applicationResponse.getResponseCode(), Response.Status.OK.getStatusCode(),
+                "Application creation failed. Response: " + applicationResponse.getData());
         Assert.assertNotNull(applicationResponse.getData(), "Application creation failed");
         applicationId = applicationResponse.getData();
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java`
around lines 237 - 241, Check the HTTP response code from
restAPIStore.createApplication before using applicationResponse.getData():
assert that applicationResponse.getResponseCode() equals the expected success
code (e.g., 201/CREATED) and only then assign applicationId =
applicationResponse.getData(); update the assertion to mirror the pattern used
earlier (line ~194) so failures give clear diagnostics about creation vs.
missing data.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java`:
- Around line 237-241: Check the HTTP response code from
restAPIStore.createApplication before using applicationResponse.getData():
assert that applicationResponse.getResponseCode() equals the expected success
code (e.g., 201/CREATED) and only then assign applicationId =
applicationResponse.getData(); update the assertion to mirror the pattern used
earlier (line ~194) so failures give clear diagnostics about creation vs.
missing data.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 4c21ec7c-6bd3-4f5f-b725-c28bbdb4b1aa

📥 Commits

Reviewing files that changed from the base of the PR and between 5c661ab and ccc29d1.

📒 Files selected for processing (1)
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java

coderabbitai[bot]
coderabbitai Bot previously approved these changes May 21, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java (1)

169-183: ⚡ Quick win

Prefer structural JSON assertions over contains(...) checks.

These assertions are brittle to serialization formatting and can still miss payload-shape regressions. Parsing the response body and asserting fields directly would make this test much more stable.

Suggested refactor
-        Assert.assertTrue(petZeroResponse.getData().contains("\"id\":10")
-                        || petZeroResponse.getData().contains("\"id\": 10"),
-                "petId=0 should return default mock payload with id 10. Response: " + petZeroResponse.getData());
-        Assert.assertTrue(petZeroResponse.getData().contains("Dogs"),
-                "petId=0 should return default mock payload with Dogs category. Response: " + petZeroResponse.getData());
+        JSONObject petZeroBody = new JSONObject(petZeroResponse.getData());
+        Assert.assertEquals(petZeroBody.getInt("id"), 10,
+                "petId=0 should return default mock payload. Response: " + petZeroResponse.getData());
+        Assert.assertEquals(petZeroBody.getJSONObject("category").getString("name"), "Dogs",
+                "petId=0 should return Dogs category. Response: " + petZeroResponse.getData());

...
-        Assert.assertTrue(petOneResponse.getData().contains("German Shepherd"),
-                "petId=1 should return manually modified mock payload. Response: " + petOneResponse.getData());
-        Assert.assertTrue(petOneResponse.getData().contains("\"id\":1")
-                        || petOneResponse.getData().contains("\"id\": 1"),
-                "petId=1 should return mock payload with id 1. Response: " + petOneResponse.getData());
+        JSONObject petOneBody = new JSONObject(petOneResponse.getData());
+        Assert.assertEquals(petOneBody.getString("name"), "German Shepherd",
+                "petId=1 should return manually modified mock payload. Response: " + petOneResponse.getData());
+        Assert.assertEquals(petOneBody.getInt("id"), 1,
+                "petId=1 should return mock payload with id 1. Response: " + petOneResponse.getData());
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java`
around lines 169 - 183, Replace brittle contains(...) string checks in
MockEndpointIntegrationTestCase by parsing the response JSON from
petZeroResponse.getData() and petOneResponse.getData() (responses obtained via
HTTPSClientUtils.doGet) and asserting structure/values: assert the numeric "id"
equals 10 for petZeroResponse and 1 for petOneResponse, assert the category name
equals "Dogs" for petZeroResponse, and assert the relevant name/title field
contains "German Shepherd" (or the appropriate JSON field) for petOneResponse;
use a JSON parser (e.g., ObjectMapper.readTree or new JSONObject) to extract
fields rather than substring matching so assertions target fields like
root.get("id").asInt() and root.path("category").path("name").asText().
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java`:
- Around line 141-146: The test currently only asserts
applicationResponse.getData() is not null before using it; instead assert the
createApplication call succeeded by checking applicationResponse's HTTP status
is a 2xx (e.g., assertTrue(applicationResponse.getStatusCode() >= 200 &&
applicationResponse.getStatusCode() < 300)) and include the response body in the
assertion message for debugging, then only assign applicationId =
applicationResponse.getData() and call restAPIStore.subscribeToAPI(...) after
that success check; reference createApplication, applicationResponse,
applicationId, and restAPIStore.subscribeToAPI in the change.

---

Nitpick comments:
In
`@all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java`:
- Around line 169-183: Replace brittle contains(...) string checks in
MockEndpointIntegrationTestCase by parsing the response JSON from
petZeroResponse.getData() and petOneResponse.getData() (responses obtained via
HTTPSClientUtils.doGet) and asserting structure/values: assert the numeric "id"
equals 10 for petZeroResponse and 1 for petOneResponse, assert the category name
equals "Dogs" for petZeroResponse, and assert the relevant name/title field
contains "German Shepherd" (or the appropriate JSON field) for petOneResponse;
use a JSON parser (e.g., ObjectMapper.readTree or new JSONObject) to extract
fields rather than substring matching so assertions target fields like
root.get("id").asInt() and root.path("category").path("name").asText().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a15f9c18-8981-4fd9-841d-c67455e0785e

📥 Commits

Reviewing files that changed from the base of the PR and between ccc29d1 and e24ef90.

📒 Files selected for processing (2)
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/prototype/MockEndpointIntegrationTestCase.java
  • all-in-one-apim/modules/integration/tests-integration/tests-backend/src/test/resources/oas/v3/mock-endpoint/get_pet_modified_mediation_script.js

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.

1 participant