Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
ci(cypress): ucs shadow config testing (#10349)
Jeeva Ramachandranefea6a06553e
diff --git a/cypress-tests/cypress/e2e/spec/Payment/00001-AccountCreate.cy.js b/cypress-tests/cypress/e2e/spec/Payment/00001-AccountCreate.cy.jsindex 8557c6c3c8..62f733d35a 100644--- a/cypress-tests/cypress/e2e/spec/Payment/00001-AccountCreate.cy.js+++ b/cypress-tests/cypress/e2e/spec/Payment/00001-AccountCreate.cy.js@@ -20,4 +20,10 @@ describe("Account Create flow test", () => {it("api-key-create-call-test", () => {cy.apiKeyCreateTest(fixtures.apiKeyCreateBody, globalState);});++ it("create-shadow-config-if-shadow-mode-enabled", () => {+ // Automatically create rollout configs and shadow config after successful merchant creation+ cy.createRolloutConfig(globalState);+ cy.createShadowRolloutConfig(globalState);+ });});diff --git a/cypress-tests/cypress/e2e/spec/Payment/00035-DiffCheckValidation.cy.js b/cypress-tests/cypress/e2e/spec/Payment/00035-DiffCheckValidation.cy.jsnew file mode 100644index 0000000000..e649c4f8d6--- /dev/null+++ b/cypress-tests/cypress/e2e/spec/Payment/00035-DiffCheckValidation.cy.js@@ -0,0 +1,19 @@+import State from "../../../utils/State";++let globalState;++describe("Diff Check Result Validation Tests", () => {+ before("seed global state", () => {+ cy.task("getGlobalState").then((state) => {+ globalState = new State(state);+ });+ });++ after("flush global state", () => {+ cy.task("setGlobalState", globalState.data);+ });++ it("diff-check-result-test", () => {+ cy.diffCheckResult(globalState);+ });+});diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex 14d7801520..d186f52720 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -35,6 +35,380 @@ import * as RequestBodyUtils from "../utils/RequestBodyUtils";import { isoTimeTomorrow, validateEnv } from "../utils/RequestBodyUtils.js";import { handleRedirection } from "./redirectionHandler";+// Helper function for creating individual rollout config+function createIndividualRolloutConfig(+ methodFlow,+ globalState,+ configType = "rollout"+) {+ const merchantId = globalState.get("merchantId");+ const adminApiKey = globalState.get("adminApiKey");+ const baseUrl = globalState.get("baseUrl");+ const connector = globalState.get("connectorId");+ const httpUrl = globalState.get("proxyHttp");+ const httpsUrl = globalState.get("proxyHttps");++ const keySuffix = configType === "shadow" ? "_shadow" : "";+ const rolloutPercent = configType === "shadow" ? 0.9 : 0.1;+ const key = `ucs_rollout_config_${merchantId}_${connector}_${methodFlow}${keySuffix}`;++ const configValue = {+ rollout_percent: rolloutPercent,+ http_url: httpUrl,+ https_url: httpsUrl,+ };+ const value = JSON.stringify(configValue);++ const headers = {+ "Content-Type": "application/json",+ "api-key": adminApiKey,+ };++ const requestBody = {+ key: key,+ value: value,+ };++ const url = `${baseUrl}/configs/`;++ return cy+ .request({+ method: "POST",+ url: url,+ headers: headers,+ body: requestBody,+ failOnStatusCode: false,+ })+ .then((response) => {+ if (response.status === 200) {+ expect(response.body).to.have.property("key").to.equal(key);+ expect(response.body).to.have.property("value").to.equal(value);+ return cy+ .task(+ "cli_log",+ `PASS: ${configType} config created successfully: ${merchantId}_${connector}_${methodFlow}`+ )+ .then(() => {+ return cy.wrap({ success: true, flow: methodFlow });+ });+ } else {+ const errorMsg = response.body?.error?.message || "Unknown error";+ return cy+ .task(+ "cli_log",+ `FAIL: ${configType} config creation failed: ${merchantId}_${connector}_${methodFlow}`+ )+ .then(() => {+ return cy+ .task("cli_log", ` Status: ${response.status}`)+ .then(() => {+ return cy.task("cli_log", ` Error: ${errorMsg}`).then(() => {+ return cy.wrap({+ success: false,+ flow: methodFlow,+ error: errorMsg,+ });+ });+ });+ });+ }+ });+}++function parseMethodFlows(methodFlowInput) {+ if (!methodFlowInput) {+ throw new Error("methodFlow input is required");+ }++ return methodFlowInput.includes(",")+ ? methodFlowInput+ .split(",")+ .map((flow) => flow.trim())+ .filter((flow) => flow.length > 0)+ : [methodFlowInput.trim()];+}++function createUcsConfigs(globalState, flow, type) {+ // --- Phase 1: Environment Setup & Validation ---+ const ucsEnabled = globalState.get("ucsEnabled");+ if (!ucsEnabled) {+ cy.task(+ "cli_log",+ `UCS ${type} config creation skipped - ucsEnabled is false or not set`+ );+ return;+ }++ const httpUrl = globalState.get("proxyHttp");+ const httpsUrl = globalState.get("proxyHttps");+ const connector = globalState.get("connectorId");+ const methodFlowInput = flow || globalState.get("methodFlow");++ if (!httpUrl || !httpsUrl) {+ throw new Error("Missing proxyHttp or proxyHttps in globalState");+ }++ if (!connector || !methodFlowInput) {+ throw new Error("Missing connectorId or methodFlow in globalState");+ }++ if (!globalState) {+ throw new Error("Missing required parameter: globalState");+ }++ // --- Phase 2: Data Preparation ---+ const merchantId = globalState.get("merchantId");+ const adminApiKey = globalState.get("adminApiKey");+ const baseUrl = globalState.get("baseUrl");++ if (!merchantId || !adminApiKey || !baseUrl) {+ throw new Error(+ "Missing merchantId, adminApiKey, or baseUrl in globalState"+ );+ }++ const methodFlows = parseMethodFlows(methodFlowInput);++ return cy+ .task(+ "cli_log",+ `Creating ${type} rollout config for merchant: ${merchantId}`+ )+ .then(() => {+ return cy+ .task(+ "cli_log",+ `Processing ${methodFlows.length} flows: ${methodFlows.join(", ")}`+ )+ .then(() => {+ // --- Phase 3: Sequential Config Creation ---+ function processFlowsSequentially(flows, index, results) {+ if (index >= flows.length) {+ // --- Phase 4: Final Summary ---+ const successCount = results.filter((r) => r.success).length;+ const failureCount = results.filter((r) => !r.success).length;+ const failedConfigs = results.filter((r) => !r.success);++ return cy+ .task(+ "cli_log",+ `${type} rollout config creation completed: ${successCount} success, ${failureCount} failures`+ )+ .then(() => {+ if (failedConfigs.length > 0) {+ return cy.task(+ "cli_log",+ `Failed configs: ${JSON.stringify(failedConfigs)}`+ );+ }+ });+ }++ const currentFlow = flows[index];+ return cy+ .task(+ "cli_log",+ `INFO: Creating ${type} config ${index + 1}/${flows.length}: ${currentFlow}`+ )+ .then(() => {+ return createIndividualRolloutConfig(+ currentFlow,+ globalState,+ type+ );+ })+ .then((result) => {+ results.push(result);+ return processFlowsSequentially(flows, index + 1, results);+ });+ }++ return processFlowsSequentially(methodFlows, 0, []);+ });+ });+}++function storeRequestId(xRequestId, globalState) {+ if (xRequestId && globalState) {+ // Get existing request IDs array or initialize empty array+ const requestIds = globalState.get("requestIds") || [];+ requestIds.push(xRequestId);+ globalState.set("requestIds", requestIds);+ cy.task("cli_log", "x-request-id stored in global state: " + xRequestId);+ }+}++// Helper function for validating diff check input+function validateDiffCheckInput(globalState) {+ if (!globalState || !globalState.get("ucsEnabled")) {+ cy.task(+ "cli_log",+ "ERROR: globalState parameter is required for diffCheckResult"+ );+ return {+ isValid: false,+ reason: "Missing globalState or ucsEnabled is false",+ };+ }++ const storedRequestIds = globalState.get("requestIds") || [];+ if (storedRequestIds.length === 0) {+ cy.task(+ "cli_log",+ "No stored request IDs found. Skipping diff check validation."+ );+ return { isValid: false, reason: "No request IDs" };+ }++ return { isValid: true, requestIds: storedRequestIds };+}++// Helper function for filtering matching validation results+function filterMatchingResults(allResults, storedRequestIds) {+ const matchingResults = [];+ allResults.forEach((resultId) => {+ const isMatching = storedRequestIds.some((storedId) => {+ return resultId.includes(storedId);+ });+ if (isMatching) {+ matchingResults.push(resultId);+ }+ });+ return matchingResults;+}++// Helper function for safely encoding result IDs+function encodeResultId(resultId) {+ return encodeURIComponent(resultId);+}++// Helper function for validating comparison results+function validateComparisonResult(comparisonResult, resultId) {+ let validationsFailed = 0;++ // Validate headerComparison+ if (comparisonResult.headerComparison) {+ try {+ expect(+ comparisonResult.headerComparison.keyDiff,+ "headerComparison.keyDiff"+ ).to.deep.equal({});+ expect(+ comparisonResult.headerComparison.valueDiff,+ "headerComparison.valueDiff"+ ).to.deep.equal({});+ } catch (error) {+ validationsFailed++;+ cy.task(+ "cli_log",+ `FAIL: headerComparison validation failed for ${resultId}: ${error.message}`+ );+ }+ }++ // Validate methodComparison+ if (comparisonResult.methodComparison) {+ try {+ expect(comparisonResult.methodComparison.match, "methodComparison.match")+ .to.be.true;+ } catch (error) {+ validationsFailed++;+ cy.task(+ "cli_log",+ `FAIL: methodComparison validation failed for ${resultId}: ${error.message}`+ );+ }+ }++ // Validate bodyComparison+ if (comparisonResult.bodyComparison) {+ try {+ expect(+ comparisonResult.bodyComparison.keyDiff,+ "bodyComparison.keyDiff"+ ).to.deep.equal({});+ expect(+ comparisonResult.bodyComparison.valueDiff,+ "bodyComparison.valueDiff"+ ).to.deep.equal({});+ expect(+ comparisonResult.bodyComparison.typeDiff,+ "bodyComparison.typeDiff"+ ).to.deep.equal({});+ } catch (error) {+ validationsFailed++;+ cy.task(+ "cli_log",+ `FAIL: bodyComparison validation failed for ${resultId}: ${error.message}`+ );+ }+ }++ return validationsFailed === 0;+}++// Helper function for processing individual validation results+function processValidationResult(resultId, validationServiceUrl) {+ const encodedResultId = encodeResultId(resultId);+ const detailUrl = `${validationServiceUrl}/${encodedResultId}`;++ return cy+ .request({+ method: "GET",+ url: detailUrl,+ headers: {+ "Content-Type": "application/json",+ },+ timeout: 30000,+ failOnStatusCode: false,+ })+ .then((detailResponse) => {+ if (detailResponse.status === 200) {+ try {+ if (detailResponse.body?.data?.data?.comparisonResult) {+ const comparisonResult =+ detailResponse.body.data.data.comparisonResult;+ const isValid = validateComparisonResult(+ comparisonResult,+ resultId+ );+ return cy.wrap({ success: isValid, resultId });+ } else {+ cy.task(+ "cli_log",+ `FAIL: comparisonResult not found in response for ${resultId}`+ );+ return cy.wrap({ success: false, resultId });+ }+ } catch (error) {+ cy.task(+ "cli_log",+ `FAIL: Validation error for ${resultId}: ${error.message}`+ );+ return cy.wrap({ success: false, resultId });+ }+ } else {+ cy.task(+ "cli_log",+ `FAIL: Request failed for ${resultId} (Status: ${detailResponse.status})`+ );+ return cy.wrap({ success: false, resultId });+ }+ });+}++// Helper function for cleaning up processed request IDs+function cleanupProcessedRequestIds(+ globalState,+ matchingResults,+ storedRequestIds+) {+ const remainingRequestIds = storedRequestIds.filter((storedId) => {+ return !matchingResults.some((resultId) => resultId.includes(storedId));+ });+ globalState.set("requestIds", remainingRequestIds);+}+function logRequestId(xRequestId) {if (xRequestId) {cy.task("cli_log", "x-request-id -> " + xRequestId);@@ -1672,6 +2046,7 @@ Cypress.Commands.add(body: confirmBody,}).then((response) => {logRequestId(response.headers["x-request-id"]);+ storeRequestId(response.headers["x-request-id"], globalState);cy.wrap(response).then(() => {expect(response.headers["content-type"]).to.include("application/json");@@ -2103,6 +2478,7 @@ Cypress.Commands.add(body: createConfirmPaymentBody,}).then((response) => {logRequestId(response.headers["x-request-id"]);+ storeRequestId(response.headers["x-request-id"], globalState);cy.wrap(response).then(() => {globalState.set("clientSecret", response.body.client_secret);@@ -2244,7 +2620,7 @@ Cypress.Commands.add(body: saveCardConfirmBody,}).then((response) => {logRequestId(response.headers["x-request-id"]);-+ storeRequestId(response.headers["x-request-id"], globalState);cy.wrap(response).then(() => {expect(response.headers["content-type"]).to.include("application/json");if (response.status === 200) {@@ -2394,7 +2770,7 @@ Cypress.Commands.add("captureCallTest", (requestBody, data, globalState) => {body: requestBody,}).then((response) => {logRequestId(response.headers["x-request-id"]);-+ storeRequestId(response.headers["x-request-id"], globalState);cy.wrap(response).then(() => {expect(response.headers["content-type"]).to.include("application/json");if (response.body.capture_method !== undefined) {@@ -2438,6 +2814,7 @@ Cypress.Commands.add("voidCallTest", (requestBody, data, globalState) => {body: requestBody,}).then((response) => {logRequestId(response.headers["x-request-id"]);+ storeRequestId(response.headers["x-request-id"], globalState);cy.wrap(response).then(() => {expect(response.headers["content-type"]).to.include("application/json");@@ -2473,6 +2850,7 @@ Cypress.Commands.add(failOnStatusCode: false,}).then((response) => {logRequestId(response.headers["x-request-id"]);+ storeRequestId(response.headers["x-request-id"], globalState);cy.wrap(response).then(() => {if (response.status === 200) {@@ -4268,6 +4646,16 @@ Cypress.Commands.add("cleanupUCSConfigs", (globalState, connector) => {cy.setConfigs(globalState, "ucs_enabled", "true", "DELETE");});+Cypress.Commands.add("createRolloutConfig", (globalState, flow = null) => {+ return createUcsConfigs(globalState, flow, "rollout");+});++Cypress.Commands.add(+ "createShadowRolloutConfig",+ (globalState, flow = null) => {+ return createUcsConfigs(globalState, flow, "shadow");+ }+);// Blocklist and Eligibility API CommandsCypress.Commands.add("blocklistCreateRule",@@ -4507,3 +4895,104 @@ Cypress.Commands.add();});++Cypress.Commands.add("diffCheckResult", (globalState) => {+ // Phase 1: Input Validation+ const validation = validateDiffCheckInput(globalState);+ if (!validation.isValid) {+ return;+ }++ const storedRequestIds = validation.requestIds;+ cy.task(+ "cli_log",+ `Diff check validation started for ${storedRequestIds.length} request ID(s)`+ );++ // Phase 2: Fetch Validation Results+ const validationServiceUrl = globalState.get("validationServiceUrl");++ cy.request({+ method: "GET",+ url: validationServiceUrl,+ headers: {+ "Content-Type": "application/json",+ },+ failOnStatusCode: false,+ }).then((response) => {+ // Handle service unavailability+ if (response.status !== 200) {+ cy.task(+ "cli_log",+ `Validation service unavailable (Status: ${response.status}). Skipping diff check validation.`+ );+ return;+ }++ // Validate response structure+ if (+ !response.body ||+ !response.body.data ||+ !Array.isArray(response.body.data)+ ) {+ cy.task("cli_log", "Invalid response structure from validation service");+ return;+ }++ // Phase 3: Filter and Process Results+ const allResults = response.body.data;+ const matchingResults = filterMatchingResults(allResults, storedRequestIds);++ if (matchingResults.length === 0) {+ cy.task("cli_log", "No matching results found for stored request IDs");+ return;+ }++ // Phase 4: Sequential Processing with Summary+ cy.then(() => {+ function processResultsSequentially(+ results,+ index,+ successCount,+ errorCount+ ) {+ if (index >= results.length) {+ // Final summary+ const message =+ errorCount === 0+ ? `Diff check validation completed: ${successCount} passed, ${errorCount} failed`+ : `Diff check validation completed with failures: ${successCount} passed, ${errorCount} failed`;+ cy.task("cli_log", message);++ // Cleanup processed request IDs+ cleanupProcessedRequestIds(+ globalState,+ matchingResults,+ storedRequestIds+ );+ return;+ }++ const currentResult = results[index];+ return processValidationResult(+ currentResult,+ validationServiceUrl+ ).then((result) => {+ const newSuccessCount = result.success+ ? successCount + 1+ : successCount;+ const newErrorCount = result.success ? errorCount : errorCount + 1;++ return processResultsSequentially(+ results,+ index + 1,+ newSuccessCount,+ newErrorCount+ );+ });+ }++ return processResultsSequentially(matchingResults, 0, 0, 0);+ });+ });+});diff --git a/cypress-tests/cypress/utils/State.js b/cypress-tests/cypress/utils/State.jsindex 84f96c0bda..48b31702fa 100644--- a/cypress-tests/cypress/utils/State.js+++ b/cypress-tests/cypress/utils/State.js@@ -10,6 +10,11 @@ class State {this.data["connectorAuthFilePath"] = Cypress.env("CONNECTOR_AUTH_FILE_PATH");+ this.data["ucsEnabled"] = Cypress.env("UCS_ENABLED");+ this.data["proxyHttp"] = Cypress.env("PROXY_HTTP");+ this.data["proxyHttps"] = Cypress.env("PROXY_HTTPS");+ this.data["methodFlow"] = Cypress.env("METHOD_FLOW");+ this.data["validationServiceUrl"] = Cypress.env("VALIDATION_SERVICE_URL");}set(key, val) {