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

import static  java.lang.Math.*
import java.text.NumberFormat

import com.eviware.soapui.support.GroovyUtils
import com.eviware.soapui.support.XmlHolder

import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.Row
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
import org.apache.poi.ss.usermodel.RichTextString

import java.awt.Color

//  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 dataIdMappingFile = 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" )
def nodesArrayTP =xmlHolderTP.getDomNodes("//B/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

// Failed records
int failedRecordsNumber=0

// Get Map of Data ID and Data Name
getMapOfDataIdAndNameFromExternelFile(dataIdMappingFile)
HashMap dataIDAndNameMap = new HashMap()
dataIDAndNameMap = getMapOfDataIdAndNameFromExternelFile(dataIdMappingFile)
def attributesNumber = nodesListLive.get(0).attributes.getLength()

// 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,recordMapLive)
recordMapTP = getRecordMap(nodesListTP,recordsNumberTP,attributesNumber,dataIDAndNameMap,recordMapTP)

// Fail message
ArrayList failMessageList = new ArrayList()
ArrayList failMessage

// Compare data value on TP and Live based on ticker
Iterator iter = recordMapLive.entrySet().iterator()
while (iter.hasNext()) {
	Map.Entry entry = (Map.Entry) iter.next()
	def ticker = entry.getKey()
	HashMap dataMapLive = entry.getValue()
	HashMap dataMapTP =recordMapTP.get(ticker)
	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)

		if(dataValueTP==null){
			failMessage=[ticker,dataNameLive,"Not Exist",dataValueLive]
  			failMessageList.add(failMessage)
		}

		if(dataValueLive != dataValueTP){
			 if(((dataValueTP=="")&&(dataValueTP!=""))||((dataValueTP!="")&&(dataValueTP==""))){
	        		failMessage = [ticker,dataNameLive,dataValueTP,dataValueLive]
       			failMessageList.add(failMessage)
	    		}

			if(dataValueLive.isFloat()&&dataValueTP.isFloat()){
				allowableDeviation = dataDeviationMap.get(dataNameLive)
				if(allowableDeviation==null){
					allowableDeviation=0
				}
				addFailMessageAboutFloatDiff(failMessageList,ticker,dataNameLive,dataValueTP,dataValueLive, allowableDeviation)
			}

			else{
				failMessage =[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
def failedPercentage = failedDataPointsNumber/totalDataPointsNumber
NumberFormat format = NumberFormat.getPercentInstance()
format.setMinimumFractionDigits(2)
log.error "Failed Data Points Percentage = "+format.format(failedPercentage)

// Print out all failed data points
if(failedDataPointsNumber>0){
	def testResultFile = new File(testResultPath+ currentStepName+".xlsx")
     if (testResultFile.exists()) {
		 testResultFile.delete()
     }
     String sheetName = "Failed Data Points"
     HashMap data = new HashMap()
     data.put("1", ["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)
	def theFirstFailMessage = failMessageList.get(0)
	assert false,"Ticker = "+theFirstFailMessage.get(0)+" , Data Point = "+theFirstFailMessage.get(1)+" , TP = "+theFirstFailMessage.get(2)+" , Live = "+theFirstFailMessage.get(3)
}

//**********************************************************************Methods**************************************************************************
// Get map of ticker and other data points list
def getRecordMap(List nodesList,int recordsNumber,int attributesNumber,HashMap dataIDAndNameMap,HashMap recordMap){
	HashMap map = new HashMap()
	for(int i=0;i<recordsNumber;i++){
		attributes = nodesList.get(i).getAttributes()
		ticker = attributes.item(3).value
		if(ticker!=""){
			HashMap dataMap = new HashMap()
			for(int j=4;j<attributesNumber;j++){
				dataID = attributes.item(j).name
				dataName = dataIDAndNameMap.get(dataID)
				dataValue = attributes.item(j).value
				dataMap.put(dataName,dataValue)
			}
			map.put(ticker,dataMap)
		}
	}
	return map
}

// Get map of Data ID and Data Name from externel file
def getMapOfDataIdAndNameFromExternelFile(String dataIdMappingFile){
	HashMap map = new HashMap()
    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)
     }
     return map
}

// Add fail message when two float data is different
def addFailMessageAboutFloatDiff(ArrayList failMessageList,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 =[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,10 *256)
        sheet.setColumnWidth(1,30 *256)
        sheet.setColumnWidth(2,20 *256)
        sheet.setColumnWidth(3,20 *256)
        sheet.setColumnWidth(4,20 *256)
        sheet.setColumnWidth(5,20 *256)

        sheet.createFreezePane( 0, 1, 0, 1 )

         XSSFCellStyle cellStyleTitle = workbook.createCellStyle()
  	   cellStyleTitle.setFillPattern( XSSFCellStyle.SOLID_FOREGROUND)
  	   cellStyleTitle.setFillForegroundColor( new XSSFColor( new Color(111, 187, 195)))

  	   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((item.contains("%"))&&(cellnum==6)&&(new Float(item.substring(0,item.indexOf("%")))/100>0.1)){
                	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)
            }
        }
        try {
            FileOutputStream out = new FileOutputStream(createFile)
            workbook.write(out)
            out.close()
        } catch (FileNotFoundException e) {
            e.printStackTrace()
        } catch (IOException e) {
            e.printStackTrace()
        }
}

  

时间: 2024-10-23 10:06:39

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

[SoapUI] 比较API在两个测试环境下的XML response文件,找出不同的DataID和DataValue,并从另外一个保存着API DataID与UI DataName 映射关系的XML文件中读取DataName

import org.custommonkey.xmlunit.* import javax.xml.xpath.* import javax.xml.parsers.DocumentBuilderFactory import javax.xml.parsers.*; String UIDataName = "" def responseTP= new FileReader( new File('D:\\Study\\MA\\xml_TP.xml')) def responseLive

[SoapUI] 比较TP和Live环境下的XML Response,将代码按照功能进行拆分,根据代码所在目录自动获取Mapping文件所在路径,自动获取测试步骤名称

import org.custommonkey.xmlunit.* import org.custommonkey.xmlunit.examples.* import javax.xml.xpath.* import javax.xml.parsers.* import static java.lang.Math.* import com.eviware.soapui.support.GroovyUtils // The parameter allowableDeviation means th

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

import org.custommonkey.xmlunit.* def responseTP=context.expand( '${Intraday Table_TP#Response}' ) def responseLive=context.expand( '${Intraday Table_Live#Response}' ) if (responseTP == responseLive) { log.info "Test case pass" assert true } els

在Linux环境下使用OpenSSL对消息和文件进行加密(转载)

转自:http://netsecurity.51cto.com/art/201301/378513.htm 1.简介 OpenSSL是一款功能强大的加密工具包.我们当中许多人已经在使用OpenSSL,用于创建RSA私匙或证书签名请求(CSR).不过,你可曾 知道可以使用OpenSSL来测试计算机速度?或者还可以用它来对文件或消息进行加密?本文将介绍几个简单易学的技巧,教你如何使用OpenSSL对消息 和文件进行加密. [相关推荐]:网络安全工具百宝箱 2.对消息进行加密和解密 首先,我们不妨对简

两个JDK环境下,Tomcat启动时遇到java.lang.UnsatisfiedLinkError

由于最近自己安装了两个jdk环境,然后在启动Tomcat时遇到了启动失败的错误 具体错误: 解决方法: 删除C:\Windows\System32目录下的tcnative-1.dll,这个文件是Tomcat Native Java Library.

Web环境下applicationContext.xml文件配置

在web环境下(web.xml)如何配置applicationContext.xml文件 <listener>  <listener-class>   org.springframework.web.context.ContextLoaderListener  </listener-class> </listener> 或: <servlet>  <servlet-name>context</servlet-name>  

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

需求如题. 解决方案1 - 挂载目录(适用于创建新的容器) 格式-v 容器目录 或 -v 本地目录:容器目录 范例Linux宿主环境下:使用镜像 nginx:latest,以后台模式启动一个容器,将容器的 80 端口映射到主机的 80 端口,主机的目录 /data 映射到容器的 /data. docker run -p 80:80 -v /data:/data -d nginx:latest Windows宿主环境下: docker run -it -v /d/WindowsFolder:/de

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

正常情况下,我们在用tinyxml读取xml文件的的时候,会像下面这样写. 1 std::string filePath = FileUtils::getInstance()->getWritablePath() + fileName;//获取文件路径. 2 XMLDocument *pDoc = new XMLDocument();//创建一个空的XMLDocument 3 XMLError errorId = pDoc->LoadFile(filePath.c_str());//用XMLD

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

在VC6.0中使用键盘快捷键或者是文件菜单打开现有文件以及添加文件出现编辑器停止响应,弹出内容为Microsoft(R) Developer Studio已停止工作 Windows正在检查解决该问题的解决方案, 在我的机器上是这样解决的, 添加插件 1.使用附件中的FileTool.exe filetool.rar 2.双击运行,选择unzip,解压至自定义的目录下面 3.启动VC6.0,打开解压后的工程文件,build编译后,会在目录下生成 FileTool.dll文件. 4.重新启动VC6.