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()
}
}

  

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

  1. [SoapUI] 比较两个不同环境下XML格式的Response, 结果不同时设置Test Step的执行状态为失败

    import org.custommonkey.xmlunit.* def responseTP=context.expand( '${Intraday Table_TP#Response}' ) d ...

  2. Nginx环境下,PHP下载,中文文件,下载失效(英文可以下载)怎么解决呢?

    参考出处: http://www.imooc.com/qadetail/76393 Nginx环境下,PHP下载,中文文件,下载失效(英文可以下载)怎么解决呢? 背景介绍: 文件名  为英文时可以下载 ...

  3. [Docker] Windows 宿主环境下,共享或上传文件到容器的方法

    需求如题. 解决方案1 - 挂载目录(适用于创建新的容器) 格式-v 容器目录 或 -v 本地目录:容器目录 范例Linux宿主环境下:使用镜像 nginx:latest,以后台模式启动一个容器,将容 ...

  4. stm32f107vc在IAR环境下,引用库函数的工程文件的配置方法

    stm32做开发很方便的一个原因是大家可以稍稍放松对于硬件寄存器等的设置,因为stm32有了非常丰富和实用的库函数,外设文件等等,所以我们在使用的时候可以更加关注程序开发的过程和逻辑关系.但是,在开发 ...

  5. 【NodeJs环境下bower】如何更改bower_components文件夹的位置

    bower在初始化,默认是将bower_components文件夹放到项目的根目录下,若是public/index.html如何配置bower_components下的js或者css类库呢?只需要将b ...

  6. .NET环境下上传和下载Word文件

    一.上传Word文档或者其他文档 1.简单地上传文件的web服务方法如下 [WebMethod] public void UploadFile() { using (TransactionScope ...

  7. VC6在win7环境下无法添加以及打开现有文件的解决办法

       在VC6.0中使用键盘快捷键或者是文件菜单打开现有文件以及添加文件出现编辑器停止响应,弹出内容为Microsoft(R) Developer Studio已停止工作 Windows正在检查解决该 ...

  8. WAMP环境下访问PHP提示下载PHP文件

    原因是服务器没有加载到PHP文件 到http.conf下加载 AddType application/x-httpd-php .php AddType application/x-httpd-php ...

  9. cocos2dx3.0-tinyxml在Android环境下解析xml失败的问题

    本文由@呆代待殆原创,转载请注明出处. 正常情况下,我们在用tinyxml读取xml文件的的时候,会像下面这样写. std::string filePath = FileUtils::getInsta ...

随机推荐

  1. java代码---------再练习ChatAt()的用法

    总结: 没有理解方法的含义.瞎用 package com.mmm; //实现字符串中某个字符出现的次数 public class Mo { public static void main(String ...

  2. HBase之二:Hbase优化

    1.    预先分区 默认情况下,在创建 HBase 表的时候会自动创建一个 Region 分区,当导入数据的时候,所有的 HBase 客户端都向这一个 Region 写数据,直到这个 Region  ...

  3. mysql的约束

    SQL 约束 约束用于限制加入表的数据的类型. 可以在创建表时规定约束(通过 CREATE TABLE 语句),或者在表创建之后也可以(通过 ALTER TABLE 语句). (1)NOT NULL约 ...

  4. 这段时间使用MySQL的一些记录

    自从Fedora19之后,Linux上的MySQL就被MariaDB所取代,这段文字见如下引用: MySQL was replaced by MariaDB since Fedora 19 (http ...

  5. Java GC日志查看

    Java GC类型 Java中的GC有哪几种类型? 参数 描述 UseSerialGC 虚拟机运行在Client模式的默认值,打开此开关参数后, 使用Serial+Serial Old收集器组合进行垃 ...

  6. vmware12中ubuntu16.10的vmware tools失效,导致不能复制粘贴文字以及自动适应窗口分辨率

    问题: 复制命令后,在vmware的ubuntu中粘贴不了,网上说要安装VMWare Tools,但是安装了VMWare Tools 还是不行! 最终找到如下方法: 新安装或异常关机和重新划分分区导致 ...

  7. php redis安装使用

    下载redis-windows-master.解压点击redis-server.exe运行服务端 redis设置访问密码 修改redis.conf文件配置, # requirepass foobare ...

  8. Centos 6.5 下安装 Zabbix server 3.0服务器的安装及 监控主机的加入(2)

    一.Centos 6.5 下的Zabbix Server安装 上篇文章记录的是centos 7 下安装zabbix ,很简单.但是6.5上面没有可用的源直接安装zabbix,所以需要从别处下载.感谢i ...

  9. HTTPS的页面发送不了HTTP请求?——关于混合内容

    我们都知道HTTPS的页面是发送不了HTTP请求的,那么是什么原因导致HTTPS页面不能发送HTTP请求呢?如果有发送的需求,怎么样才能发送?最近刚好遇到了这个问题,而且搜了半天没搜到靠谱的答案,所以 ...

  10. CentOS7|Redhat7挂载NTFS格式磁盘

    //下载安装ntfs-3g_ntfsprogs.tgz软件包进行编译安装 tar -zxf ntfs-3g_ntfsprogs.tgz cd ntfs-3g_ntfsprogs ./configure ...