代码之家  ›  专栏  ›  技术社区  ›  chris tuxracer

使用groovy脚本在canoo webtest步骤中根据其doctype(dtd)验证网页

  •  1
  • chris tuxracer  · 技术社区  · 15 年前

    如何在使用groovy的canoo webtest步骤中根据doctype(dtd)验证网页?

    1 回复  |  直到 10 年前
        1
  •  1
  •   chris tuxracer    12 年前

    实际上我知道答案。但我花了一段时间才使它工作起来,我想我会分享我的解决方案。这是一个WebTest宏。如果你喜欢的话,你也可以使用顺序…

    <macrodef name="verifySchema" description="Validate the current document against its schema">
    <sequential>
        <groovy description="validate schema" >
            import javax.xml.parsers.ParserConfigurationException
            import javax.xml.parsers.SAXParser
            import javax.xml.parsers.SAXParserFactory
    
            import java.io.InputStreamReader
    
    
            import org.xml.sax.ErrorHandler
            import org.xml.sax.InputSource
            import org.xml.sax.SAXException
            import org.xml.sax.SAXParseException
            import org.xml.sax.XMLReader
    
            class MyHandler implements org.xml.sax.ErrorHandler {
                void warning(SAXParseException e) throws SAXException {
                    println 'WARNING: ' + e.getMessage()
                }
    
                void error(SAXParseException e) throws SAXException {
                    println 'ERROR: ' + e.getMessage()
                    throw e
                }
    
                void fatalError(SAXParseException e) throws SAXException {
                    println 'FATAL: ' + e.getMessage()
                    throw e
                }
            }
    
    
                def factory = SAXParserFactory.newInstance()
                factory.setValidating(true)
                factory.setNamespaceAware(true)
    
                def parser = factory.newSAXParser()
                def reader = parser.getXMLReader()
                reader.setErrorHandler(new MyHandler())
                def response = step.context.currentResponse.webResponse
                reader.parse(new InputSource(new InputStreamReader(response.contentAsStream,"UTF-8")))
        </groovy>
    </sequential>
    

    如果您也希望在出现警告时测试失败,请相应地向处理程序添加一个throw语句。