如何使用 Perl 将生成的文本文件转换为 Junit 格式 (XML)

How to convert a generated text file to Junit format(XML) using Perl

如何使用 Perl 将生成的文本文件转换为 Junit 格式(XML)

我生成了一个文本文件,格式为:

Tests started on Fri Oct 19 14:11:35 2018

Test File    Comparison Result

========= =================

abc.msg    FAILED

aa.msg     PASSED

bb.msg     TO BE VALIDATED

Tests finished on Fri Oct 19 14:12:01 2018

预期的 JUnit 格式:

请在附件中找到符合预期 xml 格式的片段

我想使用 Perl 脚本将上述文本文件从 Perl 脚本生成后转换为 XML 文件。

如有任何帮助,我们将不胜感激。提前致谢!!

TAP::Formatter::JUnit has tap2junit command that convert TAP format 文本到 JUnit XML。您所要做的就是创建一个可以读取您的测试结果并将其转换为 TAP 格式的过滤器,就像:

custom2tap.pl

#!/usr/bin/perl
use strict;
use warnings;

my @t;
while (my $line = <STDIN>) {
    $line =~ s/\R//;

    if (my ($msg, $result) = $line =~ /^(.*?)\s*(PASSED|FAILED)$/) {
        if ($result eq 'PASSED') {
            push @t, ['ok' => $msg];
        }
        elsif ($result eq 'FAILED') {
            push @t, ['not ok' => $msg];
        }
    }

}

die "No test" if @t == 0;
printf "1..%d\n", scalar @t;

for my $i (0 .. $#t) {
    printf "%s %d - %s\n", $t[$i]->[0], $i + 1, $t[$i]->[1];
}

1;

将你的测试结果保存为customtest.txt然后运行cat customtest.txt | perl custom2tap.pl | tap2junit -,你可以得到如下输出:

<testsuites>
  <testsuite failures="1" errors="0" name="-" tests="3">
    <testcase name="1 - abc.msg">
      <failure message="not ok 1 - abc.msg"
               type="TestFailed"><![CDATA[not ok 1 - abc.msg]]></failure>
    </testcase>
    <testcase name="2 - aa.msg"></testcase>
    <testcase name="3 - bb.msg"></testcase>
    <system-out><![CDATA[1..3
not ok 1 - abc.msg
ok 2 - aa.msg
ok 3 - bb.msg
]]></system-out>
    <system-err></system-err>
  </testsuite>
</testsuites>

Windows

安装Strawberry Perl,以便您可以使用cpan命令。

从命令提示符安装 TAP::Formatter::JUnit

> cpan -i TAP::Formatter::JUnit

运行 type customtest.txt | perl custom2tap.pl | tap2junit -