http://qs321.pair.com?node_id=629917

logie17 has asked for the wisdom of the Perl Monks concerning the following question:

Dearest Monks, I am just getting my feet wet with DBD::Mock. I've read through the POD for the module and also have read an excellent article on Perl.com - Perl Code Kata: Testing Databases. However I'm getting tripped up on an aspect of the DBD::Mock::Session object. When you create your statement, result pairs you can can have statement point to a CODE ref. The documentation says this can be used as a sort of catch all but I'm not able to grasp a good example of using this. I found this example:
statement => sub { my $parser1 = SQL::Parser->new('ANSI'); $parser1->parse(shift(@_)); my $parsed_statement1 = $parser1->structure(); delete $parsed_statement1->{original_string}; my $parser2 = SQL::Parser->new('ANSI'); $parser2->parse("UPDATE users SET login_failures = (login_failures + 1) WHERE user_id = 1"); my $parsed_statement2 = $parser2->structure(); delete $parsed_statement2->{original_string}; return Dumper($parsed_statement2) eq Dumper($parsed_statement1); }, results => [[ 'rows' ], []]

However, I'm guessing if it finds parser2 statement and matches the supplied statement returns a true result. What are some other good examples/needs of using a ref to the statement key? (just trying to understand this functionality)
s;;5776?12321=10609$d=9409:12100$xx;;s;(\d*);push @_,$1;eg;map{print chr(sqrt($_))."\n"} @_;

Replies are listed 'Best First'.
Re: This mocks me
by stvn (Monsignor) on Jul 31, 2007 at 22:15 UTC

    The code in that example basically takes both of the supplied SQL statements, parses them (using the SQL::Parser module found in the SQL::Statement distro) and attempts (using Data::Dumper) to compare the AST (Abstract Syntax Tree) they created. The assumption is that even if the actual SQL strings are different (different case identifiers, different formatting or something) the AST created by a good SQL parser will be the same, meaning they are functionally identical.

    -stvn
Re: This mocks me
by CountZero (Bishop) on Aug 01, 2007 at 06:27 UTC
    The SQL statement 1 is something provided by the program you are testing and it is compared to the expected result, which is in the SQL statement 2. The sub compares both and returns a true result if both statements are equivalent (not necessarily exactly the same). This allows you to change the program generated SQL statement without having to change the test. As long as they parse to the same tree (and hence should be functionally equivalent) the program passes the test.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James