0

I am writing perl test cases for checking C code . Here I am calling C file multiple times with different values and checking whether it returns 1. My perl file looks something like this:

my $variableCheck1,$variableCheck2,$variableCheck3.....
.
.
.
.
if(($variableCheck1 == 1) && ($variableCheck2 == 1) && ($variableCheck3 == 1).....)
{
   print "Test cases are passed";
}

The problem is there are many check variables. Is there a way so that I can run all the check variables in a loop while appending number to the check variable something like this

for($i=1 ; $i < 12 ; $i++)
{
      if($variableCheck_$i   == 1)  
    {
    print "Test cases are passed";

    }
}

Append such that for each loop variable name changes depending on value $i :variableCheck1,variableCheck2.

1

2 Answers 2

5

It would be better to use an actual testing library, such as Test::More which will let you know if all of the tests passed, as well as providing many useful testing functions . Then it is very simple to just iterate over your various parameter values and run tests. Here is an example which passes various parameters to the echo command and then pipes the result to calculator program bc to see that addition works correctly:

test_add.t

#!/usr/bin/env perl

use warnings;
use strict;
use Test::More;
for my $aa ( 1..3 ) {
    for my $bb ( 1..3 ) {
        my $expected = $aa + $bb;
        my $prog = "echo $aa + $bb | bc";
        my $output = `$prog`;
        ok( $expected == $output, "$aa + $bb = $expected" );
    }
}
done_testing();

Run the test file:

prove -v test_add.t
ok 1 - 1 + 1 = 2
ok 2 - 1 + 2 = 3
ok 3 - 1 + 3 = 4
ok 4 - 2 + 1 = 3
ok 5 - 2 + 2 = 4
ok 6 - 2 + 3 = 5
ok 7 - 3 + 1 = 4
ok 8 - 3 + 2 = 5
ok 9 - 3 + 3 = 6
1..9
ok
ll tests successful.
Files=1, Tests=9,  0 wallclock secs ( 0.05 usr  0.01 sys +  0.04 cusr  0.00 csys =  0.10 CPU)
Result: PASS
3

Any time you are using a long list of numbered variables, then the tool for the job is not to dynamically work out variable names - that's called symbolic referencing, and it's nasty.

What you should be doing is using a list of variables.

my @variablecheck = ( 1, 2, 1, 3, ); 

foreach my $value ( @variablecheck ) { 
    print "Test passed\n" if $value == 1;
}

If you are really set on symbolic naming - read this before proceeding - it's from 1998, but it's still a bad idea. You can use hashes for a similar purpose - they're good if you've got arbitrary names - but for sequential numeric values, an array is the tool for the job.

And so is using a testing library, like TAP::Harness or Test::More

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.