package direct;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.skyscreamer.jsonassert.JSONCompareResult;
import org.skyscreamer.jsonassert.comparator.DefaultComparator;
import org.skyscreamer.jsonassert.JSONCompare; import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map; import static org.skyscreamer.jsonassert.comparator.JSONCompareUtil.*; /**
* Created by jenny zhang on 2017/9/19.
*/
public class LooseyJSONComparator extends DefaultComparator {
private int scale; //精度,scale=5,表示精确到小数点后5位
private Double accuracy; //精度,accuracy=0.00001,表示精确到小数点后5位
String extraInfo;
def log; public LooseyJSONComparator(JSONCompareMode mode, int scale,String extraInfo,def log) {
super(mode);
this.scale = scale;
this.accuracy = 1.0/Math.pow(10,scale);
this.extraInfo = extraInfo;
this.log = log;
} public static void assertEquals( String expected, String actual, int scale, String extraInfo, def log) throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, new LooseyJSONComparator(JSONCompareMode.NON_EXTENSIBLE,scale,extraInfo,log));
if (result.failed()) {
def failMessage = result.getMessage();
throw new AssertionError(extraInfo + failMessage);
}
else{
log.info "pass";
}
} @Override
protected void compareJSONArrayOfJsonObjects(String key, JSONArray expected, JSONArray actual, JSONCompareResult result) throws JSONException {
String uniqueKey = findUniqueKey(expected);
if (uniqueKey == null || !isUsableAsUniqueKey(uniqueKey, actual)) {
// An expensive last resort
recursivelyCompareJSONArray(key, expected, actual, result);
return;
} Map<Object, JSONObject> expectedValueMap = arrayOfJsonObjectToMap(expected, uniqueKey, log);
Map<Object, JSONObject> actualValueMap = arrayOfJsonObjectToMap(actual, uniqueKey, log); for (Object id : expectedValueMap.keySet()) {
if (!actualValueMap.containsKey(id)) {
result.missing(formatUniqueKey(key, uniqueKey, expectedValueMap.get(id).get(uniqueKey)),
expectedValueMap.get(id));
continue;
}
JSONObject expectedValue = expectedValueMap.get(id);
JSONObject actualValue = actualValueMap.get(id);
compareValues(formatUniqueKey(key, uniqueKey, id), expectedValue, actualValue, result);
}
for (Object id : actualValueMap.keySet()) {
if (!expectedValueMap.containsKey(id)) {
result.unexpected(formatUniqueKey(key, uniqueKey, actualValueMap.get(id).get(uniqueKey)), actualValueMap.get(id));
}
}
} private String getCompareValue(String value) {
try{
return new BigDecimal(value).setScale(scale, RoundingMode.HALF_EVEN).toString();
} catch (NumberFormatException e) {
return value; //value may = NaN, in this case, return value directly.
}
} private boolean isNumeric(Object value) {
try {
Double.parseDouble(value.toString());
return true;
} catch (NumberFormatException e) {
return false;
}
} public Map<Object, JSONObject> arrayOfJsonObjectToMap(JSONArray array, String uniqueKey,def log) throws JSONException {
Map<Object, JSONObject> valueMap = new HashMap<Object, JSONObject>();
for (int i = 0; i < array.length(); ++i) {
JSONObject jsonObject = (JSONObject) array.get(i);
Object id = jsonObject.get(uniqueKey);
id = isNumeric(id) ? getCompareValue(id.toString()) : id;
valueMap.put(id, jsonObject);
}
return valueMap;
} @Override
public void compareValues(String prefix, Object expectedValue, Object actualValue, JSONCompareResult result) throws JSONException {
if (areLeaf(expectedValue, actualValue)) { if (isNumeric(expectedValue) && isNumeric(actualValue)) {
//For special numeric, such as NaN, convert to string to compare
boolean equalsAsSpecialNumeric = (expectedValue.toString().equals(actualValue.toString())) //For normal numeric, such as 153.6960001, 1.56E5, subtract and then get abosolute value
boolean equalsAsGeneralNumeric = Math.abs(Double.parseDouble(expectedValue.toString())-Double.parseDouble(actualValue.toString()))<accuracy; if (equalsAsSpecialNumeric||equalsAsGeneralNumeric) {
result.passed();
} else {
result.fail(prefix, expectedValue, actualValue);
}
return;
}
}
super.compareValues(prefix, expectedValue, actualValue, result);
} private boolean areLeaf(Object expectedValue, Object actualValue) {
boolean isLeafExpectedValue = !(expectedValue instanceof JSONArray)&&!(expectedValue instanceof JSONObject);
boolean isLeafActualValue = !(actualValue instanceof JSONArray)&&!(actualValue instanceof JSONObject);
return isLeafExpectedValue&&isLeafActualValue;
}
}

  SoapUI 里面进行调用:

package direct
import org.json.* //Get test step name
def currentStepIndex = context.currentStepIndex
def previousStep = testRunner.testCase.getTestStepAt(currentStepIndex-1)
def prePreStep = testRunner.testCase.getTestStepAt(currentStepIndex-2) def previousStepName = previousStep.name
def prePreStepName = prePreStep.name //Get extra information, get case number in loop
String caseNum = context.expand('${DataSource#caseNumber}')
String extraInfo = caseNum+ ", " //Get more extra information, get request ID
try{
def requestIdTest =previousStep.testRequest.messageExchange.requestHeaders.get("X-API-RequestId")
def requestIdBmk =prePreStep.testRequest.messageExchange.requestHeaders.get("X-API-RequestId")
extraInfo += "requestIdBmk = "+requestIdBmk+", requestIdTest = "+requestIdTest+", "
}
catch(NullPointerException e){
assert false,extraInfo+"HTTP Request is null"
} //Get json response and compare them
try{
String expectedJsonResponse = new JSONObject(context.expand( '${'+prePreStepName+'#Response}' ))
String actualJsonResponse = new JSONObject(context.expand( '${'+previousStepName+'#Response}' ))
LooseyJSONComparator.assertEquals(expectedJsonResponse, actualJsonResponse,5,extraInfo,log)
}
catch(JSONException e){
assert false,extraInfo+"HTTP Response is not JSON"
}

  

【SoapUI】比较Json response的更多相关文章

  1. 使用Groovy处理SoapUI中Json response

    最近工作中,处理最多的就是xml和json类型response,在SoapUI中request里面直接添加assertion处理json response的话,可以采用以下方式: import gro ...

  2. [SoapUI] Compare JSON Response(比较jsonobject)

    http://jsonassert.skyscreamer.org/ 从这个网站下载jsonassert-1.5.0.jar ,也可以下载到源代码 JSONObject data = getRESTD ...

  3. [SoapUI] 比较JSON Response

    比较两个JSON, ID是数字时,处理成统一的格式:只保留小数点后5位 package direct; import org.json.JSONArray; import org.json.JSONE ...

  4. [SoapUI] 重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息

    重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息 package d ...

  5. datatable fix error–Invalid JSON response

    This error is pretty common. Meaning:When loading data by Ajax(ajax|option).DataTables by default, e ...

  6. [SoapUI] 通过JSONAssert比较两个环境的JSON Response,定制化错误信息到Excel

    package ScriptLibrary; import org.json.JSONArray; import org.json.JSONException; import org.json.JSO ...

  7. SoapUI对于Json数据进行属性值获取与传递

    SoapUI的Property Transfer功能可以很好地对接口请求返回的数据进行参数属性获取与传递,但对于Json数据,SoapUI会把数据格式先转换成XML格式,但实际情况却是,转换后的XML ...

  8. How parse REST service JSON response

    1. get JSON responses and go to : http://json2csharp.com/ 2. write data contracts using C# All class ...

  9. [JSON] Validating/Asserting JSON response with Jsonlurper

    import groovy.json.JsonSlurper def response = messageExchange.response.responseContent log.info &quo ...

随机推荐

  1. MATLAB 提取头发(最大连通域)

    I= imread('2.jpg'); figure(), imshow(I) R=I(:,:,); G=I(:,:,); B=I(:,:,); [m,n]=size(r); mask=zeros(m ...

  2. MySql权威指南

    [MySql权威指南] 1.索引(index):原始数据纪录的排序情况. 2.存储过程(store procedure),就是函数. 3.触发器是一组SQL命令,当数据库执行特定操作时触发,如UPDA ...

  3. Bootstrap Popover

    [Bootstrap Popover] 1.设置一个popover需要添加以下设置: 1)data-toggle="popover" 2)title="Example p ...

  4. 查询结果null替换为0

    xxx表示字段名 mysql数据库 : ifnull( xxx , 0 ) oracle数据库:  NVL(xxx , 0 )

  5. native和webview切换

    native和webview 标签(空格分隔): native和webview 现在目前大部分的app都是native和webview混合,对应的native上的元素可以通过uiautomatorvi ...

  6. asp.net MVC 异常处理

    http://www.cnblogs.com/think8848/archive/2011/03/18/1987849.html http://www.cnblogs.com/snowdream/ar ...

  7. as3.0加载swf并控制

    私人QQ 280841609 var myload:Loader=new Loader(); var url:URLRequest=new URLRequest("1.swf"); ...

  8. Jenkins安装部署(一)

    环境准备 CentOS Linux release 7.4 1.IP:192.168.43.129 2.路径:/mnt 3.jdk版本:jdk1.8.0 4.tomcat版本:tomcat-8.5 5 ...

  9. C/C++ typedef用法详解(真的很详细)

    第一.四个用途 用途一: 定义一种类型的别名,而不只是简单的宏替换.可以用作同时声明指针型的多个对象.比如:char* pa, pb; // 这多数不符合我们的意图,它只声明了一个指向字符变量的指针, ...

  10. Asp.net中GridView使用详解(很全,很经典 转来的)

    Asp.net中GridView使用详解 效果图参考:http://hi.baidu.com/hello%5Fworld%5Fws/album/asp%2Enet中以gv开头的图片 l         ...