1 Oct 2000 kbob   » (Master)

Unit Testing in Perl

I read the eXtreme Programming book (Wiki:ExtremeProgrammingExplainedEmbraceChange) a while ago, and the part of XP that interests me most has been the unit testing stuff. But I couldn't get anybody else at work interested.

So now I'm working on a big, ugly Perl script (over 1,000 lines and still writing), and I decided to put unit tests into every class definition. Then I wrote some truly ugly code to find all the methods named "self_test" and execute them when the script starts up.

Well, hey, it works. I've got over 1,000 lines of working code, and I haven't had to debug anything that wasn't trivially easy to find and fix. In previous Perl projects, I've always gotten ensnared in bugs where a variable is supposed to be a ref, but it's actually a ref to a ref, or it's a ref to the wrong thing, or, ...

Perl's lack of encapsulation makes isolating the class under test easy -- if Foo::method requires a Bar as argument, I just pass in bless { }, 'Bar', instead of creating a real Bar.

Each selftest uses die to report errors. The "real" code uses Carp::croak pretty extensively.

Here's an example.

sub CvsDirEntry::self_test {
    my $de0 = CvsDirEntry->new(NAME => 'slug');
    die unless $de0->name eq 'slug';
    die unless $de0->path eq 'slug';

my $de1 = CvsDirEntry->new(NAME => 'grub'); $de1->set_parent(bless $de0, 'CvsDir'); die unless $de1->name eq 'grub'; die unless $de1->path eq 'slug/grub'; }

I'm not consistently writing the tests first (Wiki:CodeUnitTestFirst), but I'll get there...

eXtreme Programming and Windows

It seems like the vast majority of XP practitioners are Windows sharecroppers. Why is the intersection of XP and open source so small?

Netcraft

Apache is down again in this month's Netcraft survey. What gives?

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!