【问题标题】:Perl tests - common parent for testsPerl 测试 - 测试的共同父级
【发布时间】:2018-11-10 03:20:48
【问题描述】:

我有一组测试,总是命名为Module.t,每一个都是这样开始的:

use 5.026;
use strict;
use warnings;

use Test::Perl::Critic (-severity => 3);
use Module::Path 'module_path';
use Test::More tests => 8;
use Test::Log4perl;
Test::Log4perl->suppress_logging;

BEGIN { use_ok("My::Module") }
critic_ok(module_path("My::Module"));

... actual tests for this module ...

之所以这样做,是因为一堆模块的编码不是很好,并且为了在我们进行时重构东西,我正在尝试随着时间的推移为单个模块编写测试。例如。我不能只为所有来源启用 Perl::Critic,因为它会在我的脸上爆炸。

理想情况下,我希望为所有这些进行“父”测试,这样当我或其他开发人员想要编写新测试时,他们将始终拥有所有必需的东西。比如:

use 5.026;
use strict;
use warnings;

# 6 tests because 2 (use_ok and critic_ok) are already in the parent
use parent ParentTest("My::Module", tests => 6);

... actual tests for this module ...

perl 有办法做到这一点吗?

免责声明:我是 perl 菜鸟,所以也许这有更好的解决方案 :-)

【问题讨论】:

    标签: perl unit-testing testing


    【解决方案1】:

    听起来您只需要一个帮助模块来加载一些其他模块并为您运行一些初始测试。

    类似:

    # ParentTest.pm
    package ParentTest;
    use strict;
    use warnings;
    
    use Test::Perl::Critic (-severity => 3);
    use Module::Path 'module_path';
    use Test::More;
    use Test::Log4perl;
    
    sub import {
        my (undef, $module, %args) = @_;
    
        $args{tests} += 2;
    
        plan %args;
        Test::Log4perl->suppress_logging;
        use_ok $module;
        critic_ok module_path $module;
    
        @_ = 'Test::More';
        goto +Test::More->can('import');
    }
    
    1
    

    用法如下:

    use ParentTest "My::Module", tests => 6;
    

    这一切都未经测试,但想法是:

    • 我们想要运行一些代码来设置初始测试计划并运行一些测试。
    • 我们还希望导出 Test::More 导出的所有内容,因此我们的调用者不必自己 use Test::More
    • use Some::Module @args 等价于BEGIN { require "Some/Module.pm"; Some::Module->import(@args); },所以我们可以把自定义逻辑放在import 方法中。
    • 我们首先忽略第一个参数(这是一个类名,因为 import 被称为类方法)并将其余参数分配给 $module%args
    • 我们将 $args{tests} 增加 2 以说明我们自动执行的两个额外测试(如果 tests 未传入,则在此处隐式创建)。
    • 我们将%args 传递给plan from Test::More,这非常适合在初始use 行之外设置测试计划。
    • 我们执行初始测试。
    • 我们尾调用Test::More::import,擦除我们自己的堆栈帧。这使得我们的调用者看起来像 Test::More->import(),它将所有 Test::More 实用程序函数导出给它们。
    • goto +Test::More->... 中的一元 + 没有实际作用,但它有助于区分 goto LABELgoto EXPRESSION 句法形式。我们想要后一种解释。

    【讨论】:

    • 这很完美,我提交了一个编辑来为 goto 添加 &{}。我还添加了代码来设置/创建测试 2 因为 use_ok 和critic_ok 已经是 2 个测试。我还没有弄清楚如何让它变得更好,似乎无法找到一种方法将数组转换为没有变量的内联哈希。随意美化那部分:-))谢谢!
    • @lukash 我简化了tests + 2 逻辑。为什么要添加&{ }
    • &{ } 被添加,因为没有它我得到Bareword found where operator expected at ... line .., near "goto Test::More" (Do you need to predeclare goto?)
    • @melpomene,我同意卢卡什的观点。我用 5.10 到 5.28 测试了你的代码,但没有一个工作。您需要 goto &{ Test::More->can('import') }goto(Test::More->can('import')) 才能编译代码。
    • @lukash 现在应该修复。我花了一些时间来安装先决条件以实际测试此代码。
    猜你喜欢
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2015-01-17
    • 1970-01-01
    相关资源
    最近更新 更多