使用TAP线束中的函数而不是测试文件

时间:2013-05-16 09:41:25

标签: perl testing tap

以下是我目前使用TAP的测试工具:

use TAP::Harness;
my $harness = TAP::Harness->new();
$harness->runtests(['sequential.t']);

我想避免使用测试文件并直接调用Perl函数。类似的东西:

my %args = (
  exec => run_all_tests(),
);
$harness->runtests();

1 个答案:

答案 0 :(得分:5)

主要问题是所有现代test模块都使用Test::Builder Test::Builder本身假定您只需要在文件中进行一组测试 所以我们需要为每组测试重置单例(Test::More->builder->reset)。

use strict;
use warnings;

use TAP::Harness;
use Test::More;

my %tests = (
  a => sub{
    plan tests => 4;
    ok 5==5, '5 == 5';
    is 5, "5", 'is 5, 5';
    like 5, qr'^\d$', '5 =~ /^\d$/';
    is 5, 4, 'is 5, 4';
  },
  b => sub{
    plan tests => 3;
    ok !0;
    ok !0;
    ok !0;
  },
  c => sub{
    plan 'no_plan';
    ok !0;
    done_testing;
  },
  d => sub{
    ok !0;
    done_testing;
  },
);

sub runner{
  my($harness,$test) = @_;

  my $builder = Test::More->builder;

  # reset the Test::Builder object for every "file"
  $builder->reset;
  $builder->{Indent} = ''; # may not be needed

  # collect the output into $out
  $builder->output(\my($out));     # STDOUT
  $builder->failure_output(\$out); # STDERR
  $builder->todo_output(\$out);    # STDOUT

  # run the test
  $tests{$test}->();

  # the output ( needs at least one newline )
  return $out;
}

my $harness = TAP::Harness->new(
  {
    exec => \&runner,
    verbosity => 1,
  }
);

$harness->runtests(sort keys %tests);
a .. 
1..4
ok 1 - 5 == 5
ok 2 - is 5, 5
ok 3 - 5 =~ /^\d$/
not ok 4 - is 5, 4

#   Failed test 'is 5, 4'
#   at test.pl line 13.
#          got: '5'
#     expected: '4'
Failed 1/4 subtests 
b .. 
1..3
ok 1
ok 2
ok 3
ok
c .. 
ok 1
1..1
ok
d .. 
ok 1
1..1
ok

Test Summary Report
-------------------
a (Wstat: 0 Tests: 4 Failed: 1)
  Failed test:  4
Files=4, Tests=9,  0 wallclock secs ( 0.02 usr +  0.00 sys =  0.02 CPU)
Result: FAIL