Thursday, September 13, 2012

Running Selenium tests in parallel using Perl

Some are of the opinion that you should not try to start to experiment with parallelization of Selenium tests until you have a need for it. I do not share that opinion. I think you should dive into parallelization of your tests as soon as you have enough tests to run in parallel (e.g. TWO! :))

So what does it take to run tests in parallel? Well all you need is a parallel test runner. Fortunately for us, Perl is the Swiss Army knife of the internet (and automation as well). For our implementation we'll be using one module and perl's fork().

The first module is available here: File::Find::Rule
The second comes with your Perl distribution

We'll be using File::Find::Rule to parse directories and create lists (arrays) of files in the process; and for managing our multiple tests running in parallel fork().

1:  #!C:/Perl64/bin/perl  
2:  use strict;  
3:  use warnings;  
4:  use File::Find::Rule;  
5:    
6:  my $start_dir = shift || 'C:\Tests\';  
7:  my $count = 0;  
8:    
9:  my @subdirs = File::Find::Rule->directory->in($start_dir);  
10:    
11:  my @files = File::Find::Rule->file()  
12:                ->name( '*.pl' ) # Get only perl files  
13:                ->in( $subdirs[0] );  
14:    
15:  foreach my $test (@files) {  
16:    my $pid = fork;  
17:    die "fork failed" unless defined $pid;  
18:      
19:    if ($pid == 0) { # We Got a Child  
20:      print "Executing Test: " . $test . " Sequence #: " . $count . "\n";  
21:      my $exit_code = system($test);  
22:      print "Done Executing Test: " . $test . " Sequence #: " . $count . "\n";  
23:      print "Exit Code: " . ($exit_code >> 8) . "\n";  
24:      exit ($exit_code >> 8);  
25:    }  
26:    $count++;    
27:  }  
28:  exit(0);  

If you run the above script with two .pl files in the C:\Temp\ directory you get the following output:

 Executing Test: C:\Temp\test1.pl Sequence #: 0  
 Executing Test: C:\Temp\test2.pl Sequence #: 1  
 Done Executing Test: C:\Temp\test2.pl Sequence #: 1  
 Exit Code: 2  
 Done Executing Test: C:\Temp\test1.pl Sequence #: 0  
 Exit Code: 1  

This is what the above script is doing:
1. You pass in a directory or it uses C:\Tests\ as the default
2. Create a list of subdirectories
3. Go into each directory and get a list of files
4. Fork each one of those files (making sure they exit)

NOTE: Number 4 above is important! Unless you like zombies, that is!

No comments:

Post a Comment

Creative Commons License
VGP-Miami Web and Mobile Automation Blog by Alfred Vega is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.