Perl Testing

Testing Driven Development is a very good development practice, so is it in Perl!

Perl test framework has a similar convention as other test frameworks in other languages, like JUnit for Java.

Perl has a simple way to note which tests pass (OK) and which fail (not OK). E.g,

Let’s see an example,

ok 1 # it means your first test pass

not ok 3 – Hmmm, it fail #it means your third test fail

It provides a set of asserts. E.g,

ok(getname(), ‘luohua’, ‘yes, my name is Luohua’);

is(getname(), ‘luohua’, ‘yes, my name is Luohua’);

like(getname(), qr/luo.*/’, ‘yes, my name is Luohua’);

Well, let me introduce its test moduel, Test::More http://search.cpan.org/~mschwern/Test-Simple-0.98/lib/Test/More.pm

For example, I want to test my camellogger.pm which has getLogLevel(), createLogFile(), getFilename(), and logger() method. I will write the test file as below,

t/camellogger.t

use strict;
use Test::More ;
use camellogger;

#getLogLevel() should return 2,

ok (camellogger::getLogLevel() eq 2, ‘camellogger can retrieve log level properly’);

#createLogFile() should return the new created file name. E.g, camel.20130808155158.log
like (camellogger::createLogFile(), qr/camel\.\d{14}\.log/, ‘camellogger can create a log file properly’);

#getLogFilename() should return the new created file name. E.g, camel.20130808155158.log
like (camellogger::getLogFilename(), qr/camel\.\d{14}\.log/, ‘camellogger can create a log file properly’);
# logger should return 0 otherwise should fail.
is(camellogger::logger(0, ‘$0 – I am Camel’), 0, ‘camellogger can log an event properly’);
done_testing();

Output:

ok 1 – camellogger can retrieve log level properly
ok 2 – camellogger can create a log file properly
ok 3 – camellogger can create a log file properly
ok 4 – camellogger can log an event properly
1..4

Here I will change qr/camel\.\d{14}\.log/ to qr/Alibaba\.\d{14}\.log/. See the result again,

Output 2

ok 1 – camellogger can retrieve log level properly
not ok 2 – camellogger can create a log file properly
# Failed test ‘camellogger can create a log file properly’
# at /home/luhuang/workspace/Camel/t/camellogger.t line 6.
# ‘../logs/camel.20130808223917.log’
# doesn’t match ‘(?^:Alibaba\.\d{14}\.log)’
not ok 3 – camellogger can create a log file properly
# Failed test ‘camellogger can create a log file properly’
# at /home/luhuang/workspace/Camel/t/camellogger.t line 7.
# ‘../logs/camel.20130808223917.log’
# doesn’t match ‘(?^:Alibaba\.\d{14}\.log)’
ok 4 – camellogger can log an event properly
1..4
# Looks like you failed 2 tests of 4.

So it is cool and easy to use, isn’t it? Embrace it NOW, and it will make your Perl life more beautiful!