从项目级别拆除脚本创建测试报告

时间:2017-01-17 15:02:44

标签: groovy soapui

我根据测试套件的执行生成报告,在该报告中创建文件夹目录并插入显示报告的文件。这是在<{>>测试套件级别的TearDown Script内编译的。以下是代码:

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context) 
def dataFolder = groovyUtils.projectPath
def failedTestCases = 0
def succeedTestCases = 0
def totalTestCases = 0
def testCaseFailed = ""
def testCaseSucceed = ""
def date = new Date()
def folderTime = date.format("yyyy-MM-dd HH-mm-ss")
def hotelId = context.getProperty('hotelid')
def hotelname = context.getProperty('hotelname')
def hoteltype = context.getProperty('hoteltype')
//def propertyValues = ""
//def correlationid = messageExchange.modelItem.testStep.testCase.testSuite.Project.namegetPropertyValue("correlationid")
//Create a folder directory for the responses
RootResultFolder = dataFolder + "\\Test Reports" + "\\xxx_WebAPI - " + folderTime + "\\"
CreateResultFolder = new File(RootResultFolder)
CreateResultFolder.mkdir()

//context.setProperty("RootResultFolder", RootResultFolder)

def fileName = "WebAPI Test Report.txt"
def rootFolder = RootResultFolder + fileName 
def logFile = new File(rootFolder)



if(logFile.exists())
{

 log.info("Error a file named " + fileName + "already exisits")
}
    else
{
runner.results.each { testCaseResult ->
    def name = testCaseResult.testCase.name
    totalTestCases++
    if(testCaseResult.status.toString() == 'FAILED'){
        failedTestCases ++
        testCaseFailed += "- $name - HAS FAILED \n\n"
       //propertyValues += "hotelid - $hotelid, hotelname - $hotelname, hoteltype - $hoteltype \n\n"
        testCaseResult.results.each{ testStepResults ->
            testStepResults.messages.each() { msg -> log.info msg } 
        }
    }else{
        succeedTestCases ++
        testCaseSucceed += "- $name - SUCCEED \n\n"
        testCaseResult.results.each{ testStepResults ->
        testStepResults.messages.each() { msg -> log.info msg } 
        }
    }
}
}


logFile.write   "TOTAL TEST CASES SUCCEED: $succeedTestCases of $totalTestCases" + "\n\n" +
            testCaseSucceed + "---\n\n" +
            "TOTAL TEST CASES FAILED: $failedTestCases of $totalTestCases" + "\n\n" +
            testCaseFailed + "\n\n"

我真正想要做的是从Test Suite级别移动代码并将其放在Project级别的拆卸脚本中。现在,当我从那里运行代码时,它不会生成文件,我假设我需要放置正确的路径,因为我没有转向测试套件来测试案例,而是从项目到测试套件到testcase到测试步骤。

我的问题是关于语法,我想在整个项目运行时开发一个报告,它会输出以下结果:

  • 项目名称 - 成功还是失败。如果一个套件失败,则项目失败,否则通过
  • 测试套件 - 获取项目中每个测试套件的名称,如果通过,则将“成功”放置在&#39;测试套件名称旁边的地方&#39;失败&#39;在测试套件名称旁边
  • 测试套件中所有测试用例的名称。就像截图中的截图一样,&#39;成功&#39;旁边的测试用例已经过去了&#39;失败&#39;旁边那些没有。
  • 最后是属性值。如果测试用例失败,请捕获该失败测试用例的属性值,以便我们可以跟踪导致测试失败的值。

有人可以帮助我使用相关的语法来执行这些操作,然后我可以将它添加到我的代码中并进行操作吗?

更新:

def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context) 
def dataFolder = groovyUtils.projectPath
def date = new Date()
def folderTime = date.format("yyyy-MM-dd HH-mm-ss")

//Create a folder directory for the responses
RootResultFolder = dataFolder + "\\Test Reports" + "\\xxx - " + folderTime + "\\"
CreateResultFolder = new File(RootResultFolder)
CreateResultFolder.mkdir()*/

//context.setProperty("RootResultFolder", RootResultFolder)

def reportFileName = "WebAPI Test Report.txt"
def rootFolder = RootResultFolder + reportFileName 
def logFile = new File(rootFolder)

1 个答案:

答案 0 :(得分:10)

如果查看项目的TearDown Script,它会显示如下,即已由soapui初始化的变量。

enter image description here

您的脚本问题
所以,如果你看一下,就会有runner变量。同样的变量也可以在测试套件级别的TearDown脚本中获得。但是,这些是不同对象的实例。 OP中使用的脚本是套件级别的,你知道这就是你没有看到结果的原因。

这是项目级别TearDown Script,并在行注释中跟随。

/**
*
* Below is the TearDown script for SoapUI Project level
* Which create a custom report in a  given file
* Modify the variable "reportFileName" below
*
**/
//Modify the file as needed for report file
//def reportFileName = '/tmp/abctestreport.txt'
//Adding the below as user wants specific directory
//Get the project path

def dataFolder =  new com.eviware.soapui.support.GroovyUtils(context).projectPath

//Create today's date for storing response
def today = new Date().format("yyyy-MM-dd")

def filePrefix = "${dataFolder}/TestReports/xxx_WebAPI_${today}" as String

def fileNamePart = new Date().format("yyyy-MM-dd'T'HH.mm.ss")

//creating filename dynamically.
def reportFileName = "${filePrefix}/xxx_WebAPI_TestReport_${fileNamePart}.txt" as String


//NOTE: Not required to edit beyond this point

/**
* This class holds the test case details
**/
class TestCaseResultHolder {
    def log
    Map<String, String> properties = [:]
    boolean status

    def createProperties(testCase) {
        testCase.getPropertyNames().each { key ->
            properties[key] = testCase.getPropertyValue(key)
        }       
    }

    def getCaseResult(caseRunner, caseName) {
        log.info "Checking test case status ${caseName}"
        if ( caseRunner.status.toString() == 'FAILED' ){
            log.error "Test case $caseName has failed"
            for ( stepResult in caseRunner?.results ){
                stepResult.messages.each() { msg -> log.info msg }
            }
            return false
        } else {
            log.info "${caseName} is passed"
        }
        true
    }

    def buildCaseResult(caseRunner, caseName) {
        status = getCaseResult(caseRunner, caseName)
        if (!status) {
            createProperties(caseRunner.testCase)
        }
    }

}

/**
* This class holds the test suite details
**/
class SuiteResultsHolder {

    def log
    Map<String, TestCaseResultHolder> casaeResults = [:]
    int testCaseCount = 0
    int passedCasesCount = 0
    int failedCasesCount = 0

    def buildSuiteResults(suiteRunner, suiteName){      
        log.info "Building results of test suite ${suiteName}"
        for ( caseRunner in suiteRunner?.results ) {
            def caseName = caseRunner.testCase.name
            testCaseCount++
            def tcHolder = new TestCaseResultHolder(log: log)
            tcHolder.buildCaseResult(caseRunner, caseName)          
            casaeResults[caseName] = tcHolder
            if (tcHolder.status) {
                passedCasesCount++
            } else {
                failedCasesCount++
            }
        }
    }

    def getStatus() {
        (0 < failedCasesCount) ? false : true
    }

}

/**
* This class holds the project details
**/
class ProjectResultsHolder {

    def log
    Map<String, SuiteResultsHolder> suiteResults = [:]
    int suiteCount = 0
    int passedSuitecount = 0
    int failedSuiteCount = 0

    def buildProjectResults(projectRunner, projectName) {
        log.info "Building results of test project ${projectName}"          
        for(suiteRunner in projectRunner?.results) {
            def suiteName =  suiteRunner.testSuite.name
            suiteCount++
            def suiteResultsHolder = new SuiteResultsHolder(log: log)
            suiteResultsHolder.buildSuiteResults(suiteRunner, suiteName)
            suiteResults[suiteName] = suiteResultsHolder
            if (suiteResultsHolder.status) {
                passedSuitecount++
            } else {
                failedSuiteCount++
            }
        }
    }

    def getStatus() {
        (0 < failedSuiteCount) ? false : true
    }

}

//Get the status string based on boolean
def getResult(status){ status == true ? 'SUCCEED' : 'FAILED'}

//Draws a line
def drawLine(def letter = '=', def count = 70) { letter.multiply(count)}

//Gets the summary report
def getSummaryReport(project, projectResultHolder) {
    def report = new StringBuffer()
    report.append(drawLine()).append('\n')
    report.append("\t\t\tTest Execution Summary\n")
    report.append(drawLine('-', 60)).append('\n')
    report.append("Project : ${project.name}\n")
    report.append("Result : ${getResult(projectResultHolder.status)}\n")
    report.append("Total test suites executed: ${projectResultHolder.suiteCount}\n")
    report.append("Test suites passed: ${projectResultHolder.passedSuitecount}\n")
    report.append("Test suites failed: ${projectResultHolder.failedSuiteCount}\n")
    report.append(drawLine()).append('\n')
    report
}

//Gets the test case report
def getTestCaseReport(testCaseReport) {
    def report = new StringBuffer()
    report.append(drawLine('-', 60)).append('\n')
    report.append("\t\tTest Case Details:\n")
    report.append(drawLine('-', 60)).append('\n')
    testCaseReport.each { kase, tcReport ->
        report.append("Name : ${kase}\n")
        report.append("Status : ${getResult(tcReport.status)}\n")
        if (!tcReport.status) {
            report.append("Properties : ${tcReport.properties.toString()}\n")
        }
    }
    report
}

//Get the detailed report
def getDetailedReport(projectResultHolder) {
    def report = new StringBuffer()
    report.append(drawLine()).append('\n')
    report.append("\t\t\tTest Execution Detailed Report\n")
    report.append(drawLine()).append('\n')
    projectResultHolder.suiteResults.each { suite, details ->
        report.append("Test Suite : ${suite}\n")
        report.append("Result : ${getResult(details.status)}\n")
        report.append("Total Cases : ${details.testCaseCount}\n")
        report.append("Cases Passed : ${details.passedCasesCount}\n")
        report.append("Cases Failed: ${details.failedCasesCount}\n")
        report.append(getTestCaseReport(details.casaeResults))
        report.append(drawLine()).append('\n')
        report.append(drawLine()).append('\n')
    }
    report
}

//Save the contents to a file
def saveToFile(file, content) {
    if (!file.parentFile.exists()) {
        file.parentFile.mkdirs()
        log.info "Directory did not exist, created"
    }
    file.write(content) 
    assert file.exists(), "${file.name} not created"
}

def holder = new ProjectResultsHolder(log: log)
holder.buildProjectResults(runner, project.name)

def finalReport = new StringBuffer()
finalReport.append(getSummaryReport(project, holder))
finalReport.append(getDetailedReport(holder))

def reportFile = new File(reportFileName)
saveToFile(reportFile, finalReport.toString())

这是生成的输出
enter image description here