It contains everything in a single .pm file to make it easy to ship with your distribution for testing. I plan to make it available on CPAN as well. The docs so far are below. Comments welcome, even if they're of the "dumbest thing I've ever seen" variety :-)
Chris
--------------------
NAME
DBD::Mock - Mock database driver for testingSYNOPSIS
use DBI; # ...connect as normal, using 'Mock' as your driver name
my $dbh = DBI->connect( 'DBI:Mock:', '', '' )
|| die "Cannot create handle: $DBI::errstr\n";# ...create a statement handle as normal and execute with parameters
my $sth = $dbh->prepare( 'SELECT this, that FROM foo WHERE id = ?' );
$sth->execute( 15 );
# Now query the statement handle as to what has been done with it
my $tracker = $sth->{mock_my_history};
my $params = $tracker->bound_params;
print "Used statement: ", $tracker->statement, "\n",
"Bound parameters: ", join( ', ', @{ $params } ), "\n";DESCRIPTION
Purpose
Testing with databases can be tricky. If you are developing a system
married to a single database then you can make some assumptions about
your environment and ask the user to provide relevant connection
information. But if you need to test a framework that uses DBI,
particularly a framework that uses different types of persistence
schemes, then it may be more useful to simply verify what the framework
is trying to do -- ensure the right SQL is generated and that the
correct parameters are bound. "DBD::Mock" makes it easy to just modify
your configuration (presumably held outside your code) and just use it
instead of "DBD::Foo" (like DBD::Pg or DBD::mysql) in your framework.
There is no distinct area where using this module makes sense. (Some
people may successfully argue that this is a solution looking for a
problem...) Indeed, if you can assume your users have something like
DBD::AnyData or DBD::SQLite or if you do not mind creating a dependency
on them then it makes far more sense to use these legitimate driver
implementations and test your application in the real world -- at least
as much of the real world as you can create in your tests...
And if your database handle exists as a package variable or something
else easily replaced at test-time then it may make more sense to use
Test::MockObject to create a fully dynamic handle. There is an excellent
article by chromatic about using Test::MockObject in this and other
ways, strongly recommended. (See "SEE ALSO" for a link)
How does it work?
"DBD::Mock" comprises a set of classes used by DBI to implement a
database driver. But instead of connecting to a datasource and
manipulating data found there it tracks all the calls made to the
database handle and any created statement handles. You can then inspect
them to ensure what you wanted to happen actually happened. For
instance, say you have a configuration file with your database
connection information:
[DBI]
dsn = DBI:Pg:dbname=myapp
user = foo
password = barAnd this file is read in at process startup and the handle stored for
other procedures to use:
package ObjectDirectory;
my ( $DBH );
sub run_at_startup {
my ( $class, $config ) = @_;
$config ||= read_configuration( ... );
my $dsn = $config->{DBI}{dsn};
my $user = $config->{DBI}{user};
my $pass = $config->{DBI}{password};
$DBH = DBI->connect( $dsn, $user, $pass ) || die ...;
} sub get_database_handle {
return $DBH;
}A procedure might use it like this (ignoring any error handling for the
moment):
package My::UserActions;
sub fetch_user {
my ( $class, $login ) = @_;
my $dbh = ObjectDirectory->get_database_handle;
my $sql = q{
SELECT login_name, first_name, last_name, creation_date, num_logins
FROM users
WHERE login_name = ?
};
my $sth = $dbh->prepare( $sql );
$sth->execute( $login );
my $row = $sth->fetchrow_arrayref;
return ( $row ) ? User->new( $row ) : undef;
}
So for the purposes of our tests we just want to ensure that:
1. The right SQL is being executed
2. The right parameters are bound
Assume whether the SQL actually works or not is irrelevant for this test
:-)
To do that our test might look like:
my $config = ObjectDirectory->read_configuration( ... );
$config->{DBI}{dsn} = 'DBI:Mock:';
ObjectDirectory->run_at_startup( $config );
my $login_name = 'foobar';
my $user = My::UserActions->fetch_user( $login_name ); # Get the handle from ObjectDirectory; this is the same handle used
# in the 'fetch_user()' procedure above
my $dbh = ObjectDirectory->get_database_handle();# Ask the database handle for the history of all statements executed
# against it
my $history = $dbh->{mock_all_history};
# Now query that history record to see if our expectations match
# reality
is( scalar @{ $history }, 1,
'Correct number of statements executed' );
my $login_st = $history->[0];
like( $login_st->statement, qr/SELECT login_name.*FROM users WHERE login_name = ?/sm,
'Correct statement generated' );
my $params = $login_st->bound_params;
is( scalar @{ $params }, 1,
'Correct number of parameters bound' );
is( $params->[0], $login_name,
'Correct value for parameter 1' );
# Reset the handle for future operations
$dbh->{mock_clear_history} = 1;The list of properties and what they return is listed below. But in an
overall view:
* A database handle contains the history of all statements created
against it. Other properties set for the handle (e.g., 'PrintError',
'RaiseError') are left alone and can be queried as normal, but they
do not affect anything. (A future feature may track the
sequence/history of these assignments but if there is no demand it
probably will not get implemented.)
* A statement handle contains the statement it was prepared with plus
all bound parameters or parameters passed via "execute()". It can
also contain predefined results for the statement handle to 'fetch',
track how many fetches were called and what its current record is.
PROPERTIES
Since this is a normal DBI statement handle we need to expose our
tracking information as properties (accessed like a hash) rather than
methods.
Database Handle Properties
mock_all_historyReturns an array reference with all history objects created against the
database handle in the order they were created. Each history object can
then report information about the SQL statement used to create it, the
bound parameters, etc..
mock_clear_history
If set to a true value all previous statement history operations will be
erased. This includes the history of currently open handles, so if you
do something like:
my $dbh = get_handle( ... );
my $sth = $dbh->prepare( ... );
$dbh->{mock_clear_history} = 1;
$sth->execute( 'Foo' ); You will have no way to learn from the database handle that the
statement parameter 'Foo' was bound.This is useful mainly to ensure you can isolate the statement histories
from each other. A typical sequence will look like:
set handle to framework
perform operations
analyze mock database handle
reset mock database handle history
perform more operations
analyze mock database handle
reset mock database handle history
... Statement Handle Properties
mock_statementThe SQL statement this statement handle was "prepare"d with. So if the
handle were created with:
my $sth = $dbh->prepare( 'SELECT * FROM foo' );
This would return:
SELECT * FROM foo
The original statement is unmodified so if you are checking against it
in tests you may want to use a regex rather than a straight equality
check. (However if you use a phrasebook to store your SQL externally you
are a step ahead...)
mock_fields
Fields used by the statement. As said elsewhere we do no analysis or
parsing to find these, you need to define them beforehand. That said,
you do not actually need this very often.
Note that this returns the same thing as the normal statement property
'FIELD'.
mock_params
Returns an arrayref of parameters bound to this statement in the order
specified by the bind type. For instance, if you created and stocked a
handle with:
my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' );
$sth->bind_param( 2, 'yes' );
$sth->bind_param( 1, 7783 );
This would return:
[ 7738, 'yes' ]
The same result will occur if you pass the parameters via "execute()"
instead:
my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' );
$sth->execute( 7783, 'yes' );
mock_records
An arrayref of arrayrefs representing the records the mock statement was
stocked with.
mock_num_records
Number of records the mock statement was stocked with; if never stocked
it is still 0. (Some weirdos might expect undef...)
mock_current_record_num
Current record the statement is on; returns 0 in the instances when you
have not yet called "execute()" and if you have not yet called a "fetch"
method after the execute.
mock_is_executed
Whether "execute()" has been called against the statement handle.
Returns 'yes' if so, 'no' if not.mock_is_finished
Whether "finish()" has been called against the statement handle. Returns
'yes' if so, 'no' if not.
mock_is_depleted
Returns 'yes' if all the records in the recordset have been returned. If
no "fetch()" was executed against the statement, or If no return data
was set this will return 'no'.
mock_my_history
Returns a "DBD::Mock::StatementTracker" object which tracks the actions
performed by this statement handle. Most of the actions are separately
available from the properties listed above, so you may never need this.
SEE ALSO
DBIDBD::NullP, which provided a good starting point
Test::MockObject, which provided the approach
Test::MockObject article -
<http://www.perl.com/pub/a/2002/07/10/tmo.html>COPYRIGHT
Copyright (c) 2004 Chris Winters. All rights reserved.This library is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.
AUTHORS
Chris Winters <[EMAIL PROTECTED]>--------------------
-- Chris Winters Creating enterprise-capable snack systems since 1988
