Saturday, January 14, 2006

Adding Assertions in Perl

I've been working on a Perl module that provides a set of assertion methods that will work in Perl 5.6.1 or later. (Note that Perl 5.10 should have some form of builtin support for assertions.)

So far I've implemented:

assert( expr, $optional_message ); # passes if expr is true
assert_is($$this,$that, $opt_msg); # compare with eq
assert_isnt($this,$that, $opt$msg); # Compare with ne

# all values must be == to each other
assert_num_equals($arrayref, $opt_msg);

save_data($key, $ref_to_data); # saves clone of data

# Assert that some data has (or not) the same values as the
# previsouly saved data - does a deep compare.

assert_data_not_different($key,$ref_to_data, $opt_msg);
assert_data_different($key,$ref_to_data, $opt_msg);


I've also implemented methods to set the pass and fail behaviors:

set_pass_behavior('silence');
set_pass_behavior('warn');
set_pass_behavior( \&my_sub ); # CODE ref


set_fail_behavior('silence');
set_fail_behavior('warn');
set_fail_behavior('confess'); #die with stack trace
set_fail_behavior( \&my_sub ); # CODE ref


I'm doing this for a client and am not sure if we'll be allowed to release the code publicly, but I hope so.

No comments: