4

I have a .pm module that have five functions every function return 0 or 1 and I want to add another functions that reutrn 0 or 1 on the future (those function are test functions 1 means ok 0 means failure).

I want to call those functions which founded on the .pm module from a script .

I want my script to call every function on the .pm module if it return 0 then to continue to the next function. If it returns 1 then it should print somthing to LOG and stop proccessing the record .

Supposing I will update the .pm module and add new functions to it, is it possible to keep the script code without any change? I don't want to add the if condition every time I added tests to the .pm module ?

Dynamic
  • 921
  • 1
  • 12
  • 31
sam
  • 291
  • 1
  • 2
  • 5
  • 1
    This sounds like a simple testing framework/harness, have you looked at [Test::Simple](http://search.cpan.org/~mschwern/Test-Simple-0.98/lib/Test/Simple.pm) instead? That module seems to do exactly what you are trying to, but by using it instead later on you can move to Test::More and get additional features. – Panky Aug 15 '11 at 22:33
  • 1
    see this thread http://stackoverflow.com/questions/607282/whats-the-best-way-to-discover-all-subroutines-a-perl-module-has – bpgergo Aug 15 '11 at 22:36
  • Do you want to get names of all subroutines in module? – Alexandr Ciornii Aug 15 '11 at 23:00

1 Answers1

3

The .pm module should provide a way to retrieve the list of functions that you want to test.

I think the best way is for it be a subroutine call, but you could also use a variable (e.g. a list variable) defined in the package.

Examples:

package MyModule;

sub testable_functions { qw(fun1 fun2 fun3) }
sub fun1 { ... }
sub fun2 { ... }
sub fun3 { ... }
sub not_going_to_be_tested { ... }

or:

package MyModule;
our @testable_functions = qw(fun1 fun2 fun3);

In your test code:

my @funs_to_be_tested = MyModule->testable_functions;
# or = @MyModule::testable_functions if you're using a list

for my $fun (@funs_to_be_tested) {
  my $full_name = "MyModule::" . $fun;
  $full_name->() or die "function $full_name failed\n";
}

Now you can add functions to be tested without changing your test code.

If you want to get fancy, you can rummage through the package's symbol table:

package MyModule;

sub testable_functions {
  my @funs;
  for my $name ( keys %MyModule:: ) {
    next if $name eq "testable_functions"; # can add more conditions here
    my $full_name = "MyModule::".$name;
    next unless *{$full_name}{CODE};       # avoid non-subs
    push(@funs, $name);
  }
  return @funs;
}

Still, the contract is the same: MyModule provides a way for the test code to get a list of the functions which should be tested.

ErikR
  • 51,541
  • 9
  • 73
  • 124