是否可以在不执行其语句的情况下使用或需要 Perl 脚本? [英] Is it possible use or require a Perl script without executing its statements?

查看:49
本文介绍了是否可以在不执行其语句的情况下使用或需要 Perl 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要给一些旧的脚本添加单元测试,这些脚本基本上都是以下形式:

I need to add unit testing to some old scripts, the scripts are all basically in the following form:

#!/usr/bin/perl

# Main code
foo();
bar();

# subs
sub foo {

}
sub bar {

}

如果我尝试在单元测试中要求"此代码,则代码的主要部分将运行,因为我希望能够单独测试foo".

If I try to 'require' this code in a unit test, the main section of the code will run, where as I want to be able to just test "foo" in isolation.

有没有办法在不将 foo,bar 移动到单独的 .pm 文件的情况下做到这一点?

Is there any way to do this without moving foo,bar into a seperate .pm file?

推荐答案

单元测试脚本的另一个常见技巧是将它们的代码体包装到一个调用者"块中:

Another common trick for unit testing scripts is to wrap the body of their code into a 'caller' block:

#!/usr/bin/perl

use strict;
use warnings;

unless (caller) {
    # startup code
}

sub foo { ... }

当从命令行、cron、bash 脚本等运行时,它运行正常.但是,如果您从另一个 Perl 程序加载它,除非(调用者){...}"代码不会运行.然后在您的测试程序中,声明一个命名空间(因为脚本可能正在运行包 main:: 中的代码)并执行"脚本.

When run from the command line, cron, a bash script, etc., it runs normally. However, if you load it from another Perl program, the "unless (caller) {...}" code does not run. Then in your test program, declare a namespace (since the script is probably running code in package main::) and 'do' the script.

#!/usr/bin/perl

package Tests::Script;   # avoid the Test:: namespace to avoid conflicts
                         # with testing modules
use strict;
use warnings;

do 'some_script' or die "Cannot (do 'some_script'): $!";

# write your tests

'do' 比 eval 更有效,而且相当干净.

'do' is more efficient than eval and fairly clean for this.

测试脚本的另一个技巧是使用 Expect.这更简洁,但也更难使用,如果您需要模拟任何内容,它不会让您覆盖脚本中的任何内容.

Another trick for testing scripts is to use Expect. This is cleaner, but is also harder to use and it won't let you override anything within the script if you need to mock anything up.

这篇关于是否可以在不执行其语句的情况下使用或需要 Perl 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆