http://www.perlmonks.org?node_id=765225

thiagu_mvt has asked for the wisdom of the Perl Monks concerning the following question:

When we wrote testcase that has forking inside results are printed twice. Can we correct this ?
[host1]$ cat test.pl use Test::More tests => 2; sub for{ my $pid = fork; if($pid == 0 ){ }else{} waitpid($pid,0); } $a = "hi"; ok ("hi" eq $a); ok("1" eq &for());
[host1]$ perl test.pl 1..2 ok 1 not ok 2 # Failed test (test.pl at line 14) not ok 2 # Failed test (test.pl at line 14) # Looks like you failed 1 tests of 2.
Thanks,
Thiagu

Replies are listed 'Best First'.
Re: Results printing multiple times when testcase with fork using Test::more module
by shmem (Chancellor) on May 20, 2009 at 14:12 UTC

    Since you fork, you spawn another process from the current process and thus have two results. Why do you fork if you want just one run of the test?

    If you want the child to terminate before the evaluation of the last ok() test, your sub should look like:

    sub for{ my $pid = fork; if($pid == 0 ){ diag "$$: 0\n"; exit; }else{ diag "$$: 1\n"; waitpid($pid,0); } 1; }
      This is just an example. My actual program calls an API function which is doing the forking through 'open3'. So not my intention or in control.
Re: Results printing multiple times when testcase with fork using Test::more module
by ELISHEVA (Prior) on May 20, 2009 at 18:57 UTC
    Have you considered using Test::Fork? It is supposed to coordinate test counts across multiple threads, but I don't know how well it works.

    Best, beth

      I have not heard of it before. Will surely check it and see whether it can help my need.