Is it possible use or require a Perl script without executing its statements?

后端 未结 3 1911
半阙折子戏
半阙折子戏 2021-02-05 09:06

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 {         


        
3条回答
  •  -上瘾入骨i
    2021-02-05 09:32

    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 { ... }
    

    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' is more efficient than eval and fairly clean for this.

    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.

提交回复
热议问题