Wednesday, August 17, 2016

How To Write Codes In Perl For Accomodating To Simple Testings

In order to write scripts in perl which are testable, it is good to follow the following proposed method (assuming this code is inside file a.pl):-


#!/usr/bin/env perl                                                                                   

sub main
{                                                                                                  
    ### Your main code goes here           
    # ... ... ...                          
    1;                                                         
}


sub is_five
{
    my $num = shift(@_);
    if ($num == 5)
    {
        return 1;
    }
    else:
    {
        return 0;
    }
} # is_five


############################
# This loop will only be entered if this script is called explicitly, ie:-
#   $./a.pl
#
# This loop will not be entered If this file is required, ie:-
#   require 'a.pl'
############################
unless (caller)
{
    main();
}
Now, to write a test that tests the is_five() function, we can create a file call test_a.py, and write the test like this:-
#!/usr/bin/env perl

use Test::Simple tests => 2;
require "a.pl";

sub test_is_five___pass
{
    return is_five(5)
}
sub test_is_five___fail
{
    return is_five(3)
}

unless (caller)
{
    ok(test_is_five___pass());
    ok(! test_is_five___fail());
}

No comments:

Post a Comment

How To Bypass Kerberos(kinit) Authentication

Whenever you try to setuid and impersonate as someone else to run something, it is very likely that you will run into kerberos/kinit issues....