加载,修改,然后保存 testng-results.xml

Load, modify, then save testng-results.xml

<?xml version="1.0" encoding="UTF-8"?>
<testng-results skipped="0" failed="0" ignored="0" total="1" passed="1">
  <reporter-output>
  </reporter-output>
  <suite name="Gradle suite">
    <groups>
      <group name="smoke-ui-forms">
        <method name="fp17CompleteForm" class="ui.forms.fp17CompleteFormXX1011"/>
      </group> <!-- smoke-ui-forms -->
    </groups>
    <test name="Gradle test">
      <class name="ui.forms.fp17CompleteFormXX1011">
        <test-method status="PASS" name="beforeClassSpec" ">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- beforeClassSpec -->
        <test-method status="PASS" name="fp17CompleteForm">
          <reporter-output>
          </reporter-output>
          <attributes>
            <attribute name="test">
              <![CDATA[XX-1011]]>
            </attribute> <!-- test -->
          </attributes>
        </test-method> <!-- fp17CompleteForm -->
        <test-method status="PASS" name="cleanupSpec">
          <reporter-output>
          </reporter-output>
        </test-method> <!-- cleanupSpec -->
      </class> <!-- ui.forms.fp17CompleteFormXX1011 -->
    </test> <!-- Gradle test -->
  </suite> <!-- Gradle suite -->
</testng-results>

鉴于上述 XML,我正在尝试加载文件,修改它以删除名称等于 beforeClassSpec 的所有测试方法。

Groovy 脚本

def xmlFile = new File("../../../build/reports/tests/test/testng-results.xml")
def xml = new XmlParser().parse(xmlFile)
def nodes = xml.suite.test.class.'test-method'
nodes
        .findAll { it.'@name' == 'beforeClassSpec' }
        .each { nodes.remove(it) }

此代码确实成功地从我的 nodes def 中删除了 beforeClassSpec,但它们保留在 xml def 中。

我也试过这个

def xmlFile = new File("../../../build/reports/tests/test/testng-results.xml")
def xml = new XmlParser().parse(xmlFile)
xml.suite.test.class.'test-method'
        .findAll { it.'@name' == 'beforeClassSpec' }
        .each { xml.remove(it) }

我也试过使用 xmlSlurper,它无法正确读取文件,只能 returns CDATA 节点。

使用.each { it.parent().remove(it) }

def nodes = xml.suite.test.class.'test-method'
nodes
        .findAll { it.'@name' == 'beforeClassSpec' }
        .each { it.parent().remove(it) }
        
println groovy.xml.XmlUtil.serialize(xml)