Add Me!Close Menu Navigation

My technical corner about Linux, Perl, programming, computer networks and network security

Add Me!Open Categories Menu

Automate your testing with Perl – a simple example

Testing is one of the most important things during programming. Good testing saves your time and health.

In Perl, there is the Test::More perl module for it, but many begginers programmers don’t know how to use it, because the standard examples is too simple a
here.

 

 

The simplest: is something in a html code?

To demonstrate testing with Perl i will use my modest website which have the simple search form. We also need the irreaplaceable WWW::Mechanize perl mod
for test this form. My test checks that if form exists. For this test, it checks the following html code of the below form:

 

<form id="searchform" action="http://mateusz.szczyrzyca.pl/" method="get">
<input id="searchsubmit" type="submit" value="Enter" />
<input id="searchsubmit" type="submit" /> <input id="s" onfocus="if (this.value == 'Search: type and hit enter!') {this.value = '';}" onblur="if (this.value == ''){this.value = 'Search: type and hit enter!';}" type="text" name="s" />
</form>

 

As you can look, we have the simple form. What we can test here? If you write an application which it displays some form, you might be interested whether your form works correctly. You can see your form testing it in a web browser, but real programmers prefer to see girls, no forms. ;-)

The following code will be checked for existence:

 

<form id="searchform" action="http://mateusz.szczyrzyca.pl/" method="get">
<input id="searchsubmit" type="submit" value="Enter" />

 

This is my test, but your own criteria may be specified.

A simple test program is presented below:

 

#!/usr/bin/perl -w

use strict;
use warnings;
use Test::More 'no_plan';
use WWW::Mechanize;

my $website = "http://mateusz.szczyrzyca.pl";
my $Test = WWW::Mechanize->new;

$Test->get( $website );

### Check if page loads complete.
ok( $Test->success, "The page was loaded correctly." ) ;

### $Test->content contains the html code of the website
### Check if the form in the html code exists
like( $Test->content , qr/\<form id\=\"searchform\" action\=\"http\:\/\/mateusz\.szczyrzyca\.pl\/\" method\=\"get\"\>/, 'Checking form 1...' );
like( $Test->content , qr/\<input id\=\"searchsubmit\" type\=\"submit\" value\=\"Enter\" \/\>/, 'Checking form 2...' );

 

These results are displayed when the program is ended:

 

$ ./test.pl 
ok 1 - Page loaded correctly.
ok 2 - . Checking form 1...
ok 3 - . Checking form 2...
1..3

 

It means that all tests (2 in this case) have been completed correcty.

 

Leave a Reply

You must be logged in to post a comment.