How can I test a standalone Perl script?

前端 未结 7 1411
太阳男子
太阳男子 2021-02-01 05:07

I have written a small Perl script and now I would like to create a test suite for it. I thought it would be nice to be able to use the script as a module, import t

7条回答
  •  被撕碎了的回忆
    2021-02-01 05:34

    While making some CGI style perl scripts remotely testable (without looping thru CGI-test modules) I ended up doing something like this:

    bin/myscript.pl:

    use …;
    
    do {
      return 1 if $ENV{INCLUDED_AS_MODULE};
    
      … original script without the subs …
    };
    
    sub some_sub {
     …
    }
    sub …
    sub …
    

    t/mytest.t:

    use Test::More;
    use FindBin qw/$Bin/;
    
    BEGIN {
      $ENV{INCLUDED_AS_MODULE} = 1;
      my $filename = "$Bin/../bin/myscript.pl";
      do $filename or die "Unable to open '$filename': $! ($@)";
    }
    
    ok some_sub(), 'some sub returns true';
    …
    done_testing;
    

    This imports the subs into the main namespace of the test and can be tested easily.

    EDIT: And after some more searching for what I was looking for, I realize modulinos are basically what I did, but avoiding communicating via ENV, putting all your code in a method and just checking wether there is a caller():

    https://www.perlmonks.org/bare/?node_id=537377 (link in a previous answer did not seem to work)

提交回复
热议问题