Wednesday, August 27, 2025

 groovy to showcase difference-

import groovy.json.JsonSlurper

import groovy.json.JsonOutput


def slurper = new JsonSlurper()


def json1 = slurper.parseText(vars.get("response1"))

def json2 = slurper.parseText(vars.get("response2"))


// Recursive difference function

def getDiff(Map map1, Map map2) {

    def diff = [:]

    (map1.keySet() + map2.keySet()).each { key ->

        def val1 = map1[key]

        def val2 = map2[key]

        if (val1 instanceof Map && val2 instanceof Map) {

            def subDiff = getDiff(val1, val2)

            if (subDiff) {

                diff[key] = subDiff

            }

        } else if (val1 != val2) {

            diff[key] = [expected: val1, actual: val2]

        }

    }

    return diff

}


def diff = getDiff(json1, json2)


if (!diff.isEmpty()) {

    def diffStr = JsonOutput.prettyPrint(JsonOutput.toJson(diff))

    log.info("🟥 JSON differences:\n" + diffStr)

    AssertionResult.setFailure(true)

    AssertionResult.setFailureMessage("JSON responses differ. Check log for details.")

}