【SoapUI】比较Json response
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的更多相关文章
- 使用Groovy处理SoapUI中Json response
最近工作中,处理最多的就是xml和json类型response,在SoapUI中request里面直接添加assertion处理json response的话,可以采用以下方式: import gro ...
- [SoapUI] Compare JSON Response(比较jsonobject)
http://jsonassert.skyscreamer.org/ 从这个网站下载jsonassert-1.5.0.jar ,也可以下载到源代码 JSONObject data = getRESTD ...
- [SoapUI] 比较JSON Response
比较两个JSON, ID是数字时,处理成统一的格式:只保留小数点后5位 package direct; import org.json.JSONArray; import org.json.JSONE ...
- [SoapUI] 重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息
重载JSONComparator比对JSON Response,忽略小数点后几位,将科学计数法转换为普通数字进行比对,在错误信息中打印当前循环的case number及其他附加信息 package d ...
- datatable fix error–Invalid JSON response
This error is pretty common. Meaning:When loading data by Ajax(ajax|option).DataTables by default, e ...
- [SoapUI] 通过JSONAssert比较两个环境的JSON Response,定制化错误信息到Excel
package ScriptLibrary; import org.json.JSONArray; import org.json.JSONException; import org.json.JSO ...
- SoapUI对于Json数据进行属性值获取与传递
SoapUI的Property Transfer功能可以很好地对接口请求返回的数据进行参数属性获取与传递,但对于Json数据,SoapUI会把数据格式先转换成XML格式,但实际情况却是,转换后的XML ...
- How parse REST service JSON response
1. get JSON responses and go to : http://json2csharp.com/ 2. write data contracts using C# All class ...
- [JSON] Validating/Asserting JSON response with Jsonlurper
import groovy.json.JsonSlurper def response = messageExchange.response.responseContent log.info &quo ...
随机推荐
- 如何用 Postman 处理 json请求格式
下边是其他博友写的 http://blog.163.com/huan12_8/blog/static/130519090201611711213719/
- 【C++】正则表达式引擎学习心得
最近参照一些资料实现了一个非常简易的正则表达式引擎,支持基本的正则语法 | + * ()等. 实现思路是最基本的:正则式->AST->NFA->DFA. 以下是具体步骤: 一. 正则 ...
- Python程序打包—pyinstaller
简介:PyInstaller是一个十分有用的第三方库,通过对源文件打包,Python程序可以在没有安装 Python的环境中运行,也可以作为一个独立文件方便传递和管理. PyInstaller的官方网 ...
- oracle 11g SQL语句补充学习
添加列: alter table tablename add columnName datatype (not null); -------需要注意一点的是在添加一列为非空的时候, 表必 ...
- 利用MATLAB截取一张复杂图片中想要的区域
A = imread('1.jpg'); imshow(A); [x,y] = ginput(2); %确定图像上的两点利用ginput函数,返回值是两点的坐标 pic_1 = imcrop(A ...
- 【资料整理】ADO.NET
ADO.NET: 1.SYSTEM.DATA 命名空间下类的集合的统称,用于操作 连接数据库的 它提供了统一的编程接口,可以操作不同的数据库 数据库实例:默认实例(MSSQLSEVER)和命名实例(M ...
- synchronized细节问题(一)
synchronized锁重入: 关键字synchronized拥有锁重入的功能,也就是在使用synchronized时,当一个线程得到一个对象的锁后,再次请求此对象时是可以再次得到该对象的锁. 下面 ...
- 100-days: Seven
Title: Can baiju, China's sorghum firewater, go global? sorghum n. 高粱 firewater n. 烈酒 Baijiu——a broa ...
- [leetcode]161. One Edit Distance编辑步数为一
Given two strings s and t, determine if they are both one edit distance apart. Note: There are 3 pos ...
- Java IO如何读写文件
Java把这些不同来源和目标的数据都统一抽象为数据流:Java语言的输入输出功能是十分强大而灵活的:在Java类库中,IO部分的内容是很庞大的,因为它涉及的领域很广泛:标准输入输出,文件的操作,网络上 ...