1 package org.apache.qetest.xsl; 2 3 import org.apache.tools.ant.BuildException; 4 import org.apache.tools.ant.Task; 5 6 import java.io.File; 7 8 import javax.xml.parsers.DocumentBuilder; 9 import javax.xml.parsers.DocumentBuilderFactory; 10 import javax.xml.xpath.XPath; 11 import javax.xml.xpath.XPathConstants; 12 import javax.xml.xpath.XPathFactory; 13 14 import org.w3c.dom.Document; 15 16 /* 17 This ant task checks, whether ant target "api"'s result 18 is pass or fail, by inspecting content within test results 19 XML documents. 20 21 @author <a href="mailto:mukulg@apache.org">Mukul Gandhi</a> 22 */ 23 public class XSLApiTestsResultTask extends Task { 24 25 private String resultDir; 26 27 private String fileNamePrefix; 28 29 private static final String PASS = "Pass"; 30 31 // method to run this, ant build task execute()32 public void execute() throws BuildException { 33 File dirObj = new File(this.resultDir); 34 File[] fileList = dirObj.listFiles(); 35 for (int idx = 0; idx < fileList.length; idx++) { 36 String fileName = fileList[idx].getName(); 37 if (fileName.startsWith(this.fileNamePrefix)) { 38 String testResultFilePassStatus = getTestResultFilePassStatus( 39 fileList[idx].getAbsolutePath()); 40 if (!PASS.equals(testResultFilePassStatus)) { 41 String[] dirNameParts = (this.resultDir).split("/"); 42 String errorContextFileName = dirNameParts[dirNameParts.length - 1] + "/" + fileName; 43 throw new BuildException("One or more tests in an 'api' target failed. Test failure was found, " + 44 "while inspecting the file " + errorContextFileName + ". Please fix any api tests " + 45 "problems before checking in!", location); 46 } 47 } 48 } 49 } 50 setResultDir(String resultDir)51 public void setResultDir(String resultDir) { 52 this.resultDir = resultDir; 53 } 54 setFileNamePrefix(String fileNamePrefix)55 public void setFileNamePrefix(String fileNamePrefix) { 56 this.fileNamePrefix = fileNamePrefix; 57 } 58 59 /* 60 Read the test pass status value, within test result's XML document. 61 */ getTestResultFilePassStatus(String testResultFilePath)62 private String getTestResultFilePassStatus(String testResultFilePath) { 63 String resultStr = ""; 64 65 try { 66 DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); 67 DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); 68 Document xmlDocument = docBuilder.parse(testResultFilePath); 69 XPath xPath = XPathFactory.newInstance().newXPath(); 70 String xpathExprStr = "/teststatus"; 71 String xpathNodeValue = (String)((xPath.compile(xpathExprStr)). 72 evaluate(xmlDocument, 73 XPathConstants.STRING)); 74 resultStr = xpathNodeValue.trim(); 75 } 76 catch (Exception ex) { 77 String[] filePathParts = testResultFilePath.split("/"); 78 throw new BuildException("Exception occured, processing api test result XML document " + filePathParts[filePathParts.length - 1], location); 79 } 80 81 return resultStr; 82 } 83 84 } 85