[SoapUI] 比较两个不同环境下的XML Response, 从外部文件读取允许的偏差值,输出结果到Excel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import static  java.lang.Math.*
import java.text.NumberFormat
import java.awt.Color
 
import com.eviware.soapui.support.GroovyUtils
import com.eviware.soapui.support.XmlHolder
 
import org.apache.poi.ss.usermodel.RichTextString
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.ss.util.*
 
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook
import org.apache.poi.xssf.usermodel.XSSFCellStyle
import org.apache.poi.xssf.usermodel.XSSFColor
 
//  Get test steps
def currentStepIndex = context.currentStepIndex
String currentStepName = testRunner.testCase.getTestStepAt(currentStepIndex).name
String previousStepName = testRunner.testCase.getTestStepAt(currentStepIndex-1).name
String prePreStepName = testRunner.testCase.getTestStepAt(currentStepIndex-2).name
 
//  File path
String testDataPath = testRunner.testCase.testSuite.project.getPropertyValue( "testDataPath" )
String dataIdMappingPAFile = testDataPath+"\\DataIdMappingPA.xml"
String dataIdMappingDirectFile = testDataPath+"\\DataIdMappingPA.xml"
String dataDeviationFile = testDataPath+"\\RTQDataAllowableDeviation.xlsx"
String testResultPath = testRunner.testCase.testSuite.project.getPropertyValue( "testResultPath" )
 
//  Get allowable deviation
def allowableDeviation
HashMap dataDeviationMap = getAllowableDeviation(dataDeviationFile)
 
// Get response
def groovyUtils = new GroovyUtils( context )
def xmlHolderLive = groovyUtils.getXmlHolder( prePreStepName+"#ResponseAsXml" )
def xmlHolderTP = groovyUtils.getXmlHolder( previousStepName+"#ResponseAsXml" )
 
// Get records
def nodesArrayLive = xmlHolderLive.getDomNodes("//B/I/I" )
def nodesArrayTP =xmlHolderTP.getDomNodes("//B/I/I")
List nodesListLive = nodesArrayLive.toList()
List nodesListTP = nodesArrayTP.toList()
int recordsNumberLive = nodesListLive.size()
int recordsNumberTP = nodesListTP.size()
log.info "Total Records Number on Live = "+recordsNumberLive
log.info "Total Records Number on TP = "+recordsNumberTP
 
def attributesNumber = nodesListLive.get(0).attributes.getLength()
 
// Failed records
int failedRecordsNumber=0
 
// Get Map of Data ID and Data Name
HashMap dataIDAndNameMap = new HashMap()
getMapOfDataIdAndNameFromExternelFile(dataIdMappingPAFile,dataIDAndNameMap)
getMapOfDataIdAndNameFromExternelFile(dataIdMappingDirectFile,dataIDAndNameMap)
 
// Get Map of Data Name and Data Value
HashMap  recordMapLive = new HashMap()
HashMap  recordMapTP = new HashMap()
def dataName
def dataValue
recordMapLive = getRecordMap(nodesListLive,recordsNumberLive,attributesNumber,dataIDAndNameMap)
recordMapTP = getRecordMap(nodesListTP,recordsNumberTP,attributesNumber,dataIDAndNameMap)
 
// Fail message
ArrayList failMessageList = new ArrayList()
ArrayList failMessage
 
// Compare data value on TP and Live based on PortfolioId
Iterator iter = recordMapLive.entrySet().iterator()
while (iter.hasNext()) {
    Map.Entry entry = (Map.Entry) iter.next()
    def portfolioId = entry.getKey()
    HashMap dataMapLive = entry.getValue()
    HashMap dataMapTP =recordMapTP.get(portfolioId)
    Iterator iter2 = dataMapLive.entrySet().iterator()
    while (iter2.hasNext()) {
        Map.Entry entry2 = (Map.Entry) iter2.next()
        def dataNameLive = entry2.getKey()
        def dataValueLive = entry2.getValue()
        def dataValueTP = dataMapTP.get(dataNameLive)
        def ticker
        if(dataValueTP==null){
            ticker = dataMapLive.get("Ticker")
            failMessage=[portfolioId,ticker,dataNameLive,"Not Exist",dataValueLive]
            failMessageList.add(failMessage)
        }
         
        if(dataValueLive != dataValueTP){
             ticker = dataMapLive.get("Ticker")
             
            if(dataValueLive.isFloat()&&dataValueTP.isFloat()){
                allowableDeviation = dataDeviationMap.get(dataNameLive)
                if(allowableDeviation==null){
                    allowableDeviation=0
                }
                addFailMessageAboutFloatDiff(failMessageList,portfolioId,ticker,dataNameLive,dataValueTP,dataValueLive, allowableDeviation)
            }
 
            else{
                failMessage =[portfolioId,ticker,dataNameLive,dataValueTP,dataValueLive]
                failMessageList.add(failMessage)
            }
        }
    }
}  
 
// Get total data points number
int totalDataPointsNumber = recordsNumberLive*attributesNumber
log.info "Total Data Points Number = "+totalDataPointsNumber
 
// Get failed data points number
int failedDataPointsNumber = failMessageList.size()
log.info "Failed Data Points Number = "+failedDataPointsNumber
 
if(failedDataPointsNumber>0){
    // Get failed percentage
    def failedPercentage
    NumberFormat format = NumberFormat.getPercentInstance()
    format.setMinimumFractionDigits(2)
    failedPercentage = failedDataPointsNumber/totalDataPointsNumber
 
    // Get the first failed message
    def theFirstFailMessage = failMessageList.get(0)
    def theFirstErrorMessage = "Failed : "+format.format(failedPercentage)+", eg : Portfolio Id = "+theFirstFailMessage.get(0)+" , Ticker = "+theFirstFailMessage.get(1)+" , Data Point = "+theFirstFailMessage.get(2)+" , TP = "+theFirstFailMessage.get(3)+" , Live = "+theFirstFailMessage.get(4)
    log.error theFirstErrorMessage
 
    // Write failed data points to excel
    def testResultFile = new File(testResultPath+ currentStepName+".xlsx"
     if (testResultFile.exists()) {
         testResultFile.delete()
     }
     String sheetName = "Failed Data Points"
     HashMap data = new HashMap()
     data.put("1", ["Portfolio Id","Ticker","Data Point","TP","Live","Allowable Deviation","Actual Deviation"])
    for(j=0; j<failedDataPointsNumber; j++){
         data.put((j+2).toString(), failMessageList.get(j))
    }
    createExcelFile(testResultFile,sheetName,data)
    assert false,theFirstErrorMessage
}
 
//**********************************************************************Methods**************************************************************************
// Get map of PortfolioId and other data points list
def getRecordMap(List nodesList,int recordsNumber,int attributesNumber,HashMap dataIDAndNameMap){
    HashMap map = new HashMap()
    for(int i=0;i<recordsNumber;i++){
        attributes = nodesList.get(i).getAttributes()
        portfolioId = attributes.item(5).value
        if(portfolioId!=""){
            HashMap dataMap = new HashMap()
            for(int j=3;j<attributesNumber;j++){
                dataID = attributes.item(j).name
                dataName = dataIDAndNameMap.get(dataID)
                dataValue = attributes.item(j).value
                dataMap.put(dataName,dataValue)
            }
            map.put(portfolioId,dataMap)
        }
    }
    return map
}
 
// Get map of Data ID and Data Name from externel file
def getMapOfDataIdAndNameFromExternelFile(String dataIdMappingFile,HashMap map){
    def xmlDataIdMapping= new XmlParser().parse(dataIdMappingFile)
    for(it in xmlDataIdMapping.f){
            String mapDataID =  "${it.attribute("i")}"
            String mapDataName =  "${it.attribute("udlbl")}"
            map.put(mapDataID, mapDataName)
     }
}
 
// Add fail message when two float data is different
def addFailMessageAboutFloatDiff(ArrayList failMessageList,String portfolioId,String ticker,String dataName,String dataValueStringTP,String dataValueStringLive,def allowableDeviation){
    def dataValueTP = dataValueStringTP.toFloat()
     def dataValueLive = dataValueStringLive.toFloat()
      
     if ((dataValueLive ==0)&&(dataValueTP == 0)){
        return
    }
    NumberFormat format = NumberFormat.getPercentInstance()
    format.setMinimumFractionDigits(2)
    Float benchmark = dataValueLive
    if (dataValueLive ==0){
        benchmark = dataValueTP
    }
    def actualDeviation = Math.abs((dataValueLive-dataValueTP )/benchmark)
 
    if(actualDeviation>allowableDeviation){ 
        failMessage =[portfolioId,ticker,dataName,dataValueStringTP,dataValueStringLive,format.format(allowableDeviation),format.format(actualDeviation)]
        failMessageList.add(failMessage)
     }
}
 
// Get allowable deviation from externel file
def getAllowableDeviation(String dataDeviationFile){
    HashMap map = new HashMap()
    File file = new File(dataDeviationFile)
    try{
        XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(dataDeviationFile))
            XSSFSheet sheet = wb.getSheetAt(0)
            Row row
            Cell cellDataName
            Cell cellDataDeviation
            int rows = sheet.physicalNumberOfRows
            def dataName
            def dataDeviation
            (1..<rows).each{ r ->
                row = sheet.getRow(r)
                if (row != null){ 
                    cellDataName = row.getCell(1)
                    cellDataDeviation = row.getCell(2)
                    if (cellDataName != null){
                        dataName = cellDataName.getStringCellValue()
                    }
                    if (cellDataDeviation != null){
                        switch (cellDataDeviation.getCellType()){
                            case cellDataDeviation.CELL_TYPE_NUMERIC:
                                dataDeviation = cellDataDeviation.getNumericCellValue()
                                break
              
                            case cellDataDeviation.CELL_TYPE_STRING:
                                dataDeviation = cellDataDeviation.getStringCellValue()
                                break
              
                            case cellDataDeviation.CELL_TYPE_BLANK:
                                break
              
                            default:
                                break
                    }
                    }
                }
            map.put(dataName,dataDeviation)
            }
            return map
     }
     catch (Exception e){
         log.info "Exception :" + e.getMessage()
     }
}
 
def createExcelFile(File createFile,String sheetName, HashMap data){ 
        XSSFWorkbook workbook = new XSSFWorkbook()
        XSSFSheet sheet = workbook.createSheet(sheetName)
 
       sheet.setColumnWidth(0,15 *256)
       sheet.setColumnWidth(1,10 *256)
        sheet.setColumnWidth(2,30 *256)
        sheet.setColumnWidth(3,20 *256)
        sheet.setColumnWidth(4,20 *256)
        sheet.setColumnWidth(5,20 *256)
        sheet.setColumnWidth(6,20 *256)
 
        sheet.createFreezePane( 0, 1, 0, 1 )
 
         XSSFCellStyle cellStyleTitle = workbook.createCellStyle()
       cellStyleTitle.setFillPattern( XSSFCellStyle.SOLID_FOREGROUND)
       cellStyleTitle.setFillForegroundColor( new XSSFColor( new Color(131, 191, 90)))
 
       XSSFCellStyle cellStyleFailed = workbook.createCellStyle()
       cellStyleFailed.setFillPattern( XSSFCellStyle.SOLID_FOREGROUND)
       cellStyleFailed.setFillForegroundColor( new XSSFColor( new Color(255, 0, 0)))
          
        Set<String> keySet=data.keySet()
        ArrayList keyList=new ArrayList (keySet)
        Collections.sort(keyList)
              
        int rownum = 0
        for (String key : keyList) {
            Row row = sheet.createRow(rownum++)
            ArrayList arrayList =  data.get(key)
            int cellnum = 0
            for (def item : arrayList) {
                Cell cell = row.createCell(cellnum++)
                if(rownum==1){
                    cell.setCellStyle(cellStyleTitle)
                }
                 // If the actual deviation > 10%, change the cell color to red in the excel
                if((item.contains("%"))&&(cellnum==7)){
                    Number number = NumberFormat.getInstance().parse(item)
                    if(number>10){
                        cell.setCellStyle(cellStyleFailed)
                    }
                }
                if(item instanceof Date)
                    cell.setCellValue((RichTextString)item)
                else if(item instanceof Boolean)
                    cell.setCellValue((Boolean)item)
                else if(item instanceof String)
                    cell.setCellValue((String)item)
                else if(item instanceof Double)
                    cell.setCellValue((Double)item)
                else if(item instanceof Float)
                    cell.setCellValue((Float)item)
                else if(item instanceof BigDecimal)
                    cell.setCellValue((BigDecimal)item)
            }
        }
        sheet.setAutoFilter(CellRangeAddress.valueOf("A1:G1"))
        try {
            FileOutputStream out = new FileOutputStream(createFile)
            workbook.write(out)
            out.close()  
        } catch (FileNotFoundException e) {
            e.printStackTrace()
        } catch (IOException e) {
            e.printStackTrace()
        }
}

  

posted on   张缤分  阅读(427)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示