1DBD::Mock(3)          User Contributed Perl Documentation         DBD::Mock(3)
2
3
4

NAME

6       DBD::Mock - Mock database driver for testing
7

SYNOPSIS

9        use DBI;
10
11        # connect to your as normal, using 'Mock' as your driver name
12        my $dbh = DBI->connect( 'DBI:Mock:', '', '' )
13                      || die "Cannot create handle: $DBI::errstr\n";
14
15        # create a statement handle as normal and execute with parameters
16        my $sth = $dbh->prepare( 'SELECT this, that FROM foo WHERE id = ?' );
17        $sth->execute( 15 );
18
19        # Now query the statement handle as to what has been done with it
20        my $mock_params = $sth->{mock_params};
21        print "Used statement: ", $sth->{mock_statement}, "\n",
22              "Bound parameters: ", join( ', ', @{ $params } ), "\n";
23

DESCRIPTION

25       Testing with databases can be tricky. If you are developing a system
26       married to a single database then you can make some assumptions about
27       your environment and ask the user to provide relevant connection
28       information. But if you need to test a framework that uses DBI,
29       particularly a framework that uses different types of persistence
30       schemes, then it may be more useful to simply verify what the framework
31       is trying to do -- ensure the right SQL is generated and that the
32       correct parameters are bound. "DBD::Mock" makes it easy to just modify
33       your configuration (presumably held outside your code) and just use it
34       instead of "DBD::Foo" (like DBD::Pg or DBD::mysql) in your framework.
35
36       There is no distinct area where using this module makes sense. (Some
37       people may successfully argue that this is a solution looking for a
38       problem...) Indeed, if you can assume your users have something like
39       DBD::AnyData or DBD::SQLite or if you do not mind creating a dependency
40       on them then it makes far more sense to use these legitimate driver
41       implementations and test your application in the real world -- at least
42       as much of the real world as you can create in your tests...
43
44       And if your database handle exists as a package variable or something
45       else easily replaced at test-time then it may make more sense to use
46       Test::MockObject to create a fully dynamic handle. There is an
47       excellent article by chromatic about using Test::MockObject in this and
48       other ways, strongly recommended. (See "SEE ALSO" for a link)
49
50   How does it work?
51       "DBD::Mock" comprises a set of classes used by DBI to implement a
52       database driver. But instead of connecting to a datasource and
53       manipulating data found there it tracks all the calls made to the
54       database handle and any created statement handles. You can then inspect
55       them to ensure what you wanted to happen actually happened. For
56       instance, say you have a configuration file with your database
57       connection information:
58
59         [DBI]
60         dsn      = DBI:Pg:dbname=myapp
61         user     = foo
62         password = bar
63
64       And this file is read in at process startup and the handle stored for
65       other procedures to use:
66
67         package ObjectDirectory;
68
69         my ( $DBH );
70
71         sub run_at_startup {
72            my ( $class, $config ) = @_;
73            $config ||= read_configuration( ... );
74            my $dsn  = $config->{DBI}{dsn};
75            my $user = $config->{DBI}{user};
76            my $pass = $config->{DBI}{password};
77            $DBH = DBI->connect( $dsn, $user, $pass ) || die ...;
78         }
79
80         sub get_database_handle {
81            return $DBH;
82         }
83
84       A procedure might use it like this (ignoring any error handling for the
85       moment):
86
87         package My::UserActions;
88
89         sub fetch_user {
90            my ( $class, $login ) = @_;
91            my $dbh = ObjectDirectory->get_database_handle;
92            my $sql = q{
93                SELECT login_name, first_name, last_name, creation_date, num_logins
94                  FROM users
95                 WHERE login_name = ?
96            };
97            my $sth = $dbh->prepare( $sql );
98            $sth->execute( $login );
99            my $row = $sth->fetchrow_arrayref;
100            return ( $row ) ? User->new( $row ) : undef;
101         }
102
103       So for the purposes of our tests we just want to ensure that:
104
105       1. The right SQL is being executed
106       2. The right parameters are bound
107
108       Assume whether the SQL actually works or not is irrelevant for this
109       test :-)
110
111       To do that our test might look like:
112
113         my $config = ObjectDirectory->read_configuration( ... );
114         $config->{DBI}{dsn} = 'DBI:Mock:';
115         ObjectDirectory->run_at_startup( $config );
116
117         my $login_name = 'foobar';
118         my $user = My::UserActions->fetch_user( $login_name );
119
120         # Get the handle from ObjectDirectory;
121         # this is the same handle used in the
122         # 'fetch_user()' procedure above
123         my $dbh = ObjectDirectory->get_database_handle();
124
125         # Ask the database handle for the history
126         # of all statements executed against it
127         my $history = $dbh->{mock_all_history};
128
129         # Now query that history record to
130         # see if our expectations match reality
131         is(scalar(@{$history}), 1, 'Correct number of statements executed' ;
132
133         my $login_st = $history->[0];
134         like($login_st->statement,
135             qr/SELECT login_name.*FROM users WHERE login_name = ?/sm,
136             'Correct statement generated' );
137
138         my $params = $login_st->bound_params;
139         is(scalar(@{$params}), 1, 'Correct number of parameters bound');
140         is($params->[0], $login_name, 'Correct value for parameter 1' );
141
142         # Reset the handle for future operations
143         $dbh->{mock_clear_history} = 1;
144
145       The list of properties and what they return is listed below. But in an
146       overall view:
147
148       ·   A database handle contains the history of all statements created
149           against it. Other properties set for the handle (e.g.,
150           'PrintError', 'RaiseError') are left alone and can be queried as
151           normal, but they do not affect anything. (A future feature may
152           track the sequence/history of these assignments but if there is no
153           demand it probably will not get implemented.)
154
155       ·   A statement handle contains the statement it was prepared with plus
156           all bound parameters or parameters passed via "execute()". It can
157           also contain predefined results for the statement handle to
158           'fetch', track how many fetches were called and what its current
159           record is.
160
161   A Word of Warning
162       This may be an incredibly naive implementation of a DBD. But it works
163       for me ...
164

DBD::Mock

166       Since this is a normal DBI statement handle we need to expose our
167       tracking information as properties (accessed like a hash) rather than
168       methods.
169
170   Database Driver Properties
171       mock_connect_fail
172           This is a boolean property which when set to true (1) will not
173           allow DBI to connect. This can be used to simulate a DSN error or
174           authentication failure. This can then be set back to false (0) to
175           resume normal DBI operations. Here is an example of how this works:
176
177             # install the DBD::Mock driver
178             my $drh = DBI->install_driver('Mock');
179
180             $drh->{mock_connect_fail} = 1;
181
182             # this connection will fail
183             my $dbh = DBI->connect('dbi:Mock:', '', '') || die "Cannot connect";
184
185             # this connection will throw an exception
186             my $dbh = DBI->connect('dbi:Mock:', '', '', { RaiseError => 1 });
187
188             $drh->{mock_connect_fail} = 0;
189
190             # this will work now ...
191             my $dbh = DBI->connect(...);
192
193           This feature is conceptually different from the 'mock_can_connect'
194           attribute of the $dbh in that it has a driver-wide scope, where
195           'mock_can_connect' is handle-wide scope. It also only prevents the
196           initial connection, any $dbh handles created prior to setting
197           'mock_connect_fail' to true (1) will still go on working just fine.
198
199       mock_data_sources
200           This is an ARRAY reference which holds fake data sources which are
201           returned by the Driver and Database Handle's "data_source()"
202           method.
203
204       mock_add_data_sources
205           This takes a string and adds it to the 'mock_data_sources'
206           attribute.
207
208   Database Handle Properties
209       mock_all_history
210           Returns an array reference with all history (a.k.a.
211           "DBD::Mock::StatementTrack") objects created against the database
212           handle in the order they were created. Each history object can then
213           report information about the SQL statement used to create it, the
214           bound parameters, etc..
215
216       mock_all_history_iterator
217           Returns a "DBD::Mock::StatementTrack::Iterator" object which will
218           iterate through the current set of "DBD::Mock::StatementTrack"
219           object in the  history. See the DBD::Mock::StatementTrack::Iterator
220           documentation below for more information.
221
222       mock_clear_history
223           If set to a true value all previous statement history operations
224           will be erased. This includes the history of currently open
225           handles, so if you do something like:
226
227             my $dbh = get_handle( ... );
228             my $sth = $dbh->prepare( ... );
229             $dbh->{mock_clear_history} = 1;
230             $sth->execute( 'Foo' );
231
232           You will have no way to learn from the database handle that the
233           statement parameter 'Foo' was bound.
234
235           This is useful mainly to ensure you can isolate the statement
236           histories from each other. A typical sequence will look like:
237
238               set handle to framework
239               perform operations
240               analyze mock database handle
241               reset mock database handle history
242               perform more operations
243               analyze mock database handle
244               reset mock database handle history
245               ...
246
247       mock_can_connect
248           This statement allows you to simulate a downed database connection.
249           This is useful in testing how your application/tests will perform
250           in the face of some kind of catastrophic event such as a network
251           outage or database server failure. It is a simple boolean value
252           which defaults to on, and can be set like this:
253
254             # turn the database off
255             $dbh->{mock_can_connect} = 0;
256
257             # turn it back on again
258             $dbh->{mock_can_connect} = 1;
259
260           The statement handle checks this value as well, so something like
261           this will fail in the expected way:
262
263             $dbh = DBI->connect( 'DBI:Mock:', '', '' );
264             $dbh->{mock_can_connect} = 0;
265
266             # blows up!
267             my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) });
268             if ( $@ ) {
269                # Here, $DBI::errstr = 'No connection present'
270             }
271
272           Turning off the database after a statement prepare will fail on the
273           statement "execute()", which is hopefully what you would expect:
274
275             $dbh = DBI->connect( 'DBI:Mock:', '', '' );
276
277             # ok!
278             my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) });
279             $dbh->{mock_can_connect} = 0;
280
281             # blows up!
282             $sth->execute;
283
284           Similarly:
285
286             $dbh = DBI->connect( 'DBI:Mock:', '', '' );
287
288             # ok!
289             my $sth = eval { $dbh->prepare( 'SELECT foo FROM bar' ) });
290
291             # ok!
292             $sth->execute;
293
294             $dbh->{mock_can_connect} = 0;
295
296             # blows up!
297             my $row = $sth->fetchrow_arrayref;
298
299           Note: The handle attribute "Active" and the handle method "ping"
300           will behave according to the value of "mock_can_connect". So if
301           "mock_can_connect" were to be set to 0 (or off), then both "Active"
302           and "ping" would return false values (or 0).
303
304       mock_add_resultset( \@resultset | \%sql_and_resultset )
305           This stocks the database handle with a record set, allowing you to
306           seed data for your application to see if it works properly.. Each
307           recordset is a simple arrayref of arrays with the first arrayref
308           being the fieldnames used. Every time a statement handle is created
309           it asks the database handle if it has any resultsets available and
310           if so uses it.
311
312           Here is a sample usage, partially from the test suite:
313
314             my @user_results = (
315               [ 'login', 'first_name', 'last_name' ],
316               [ 'cwinters', 'Chris', 'Winters' ],
317               [ 'bflay', 'Bobby', 'Flay' ],
318               [ 'alincoln', 'Abe', 'Lincoln' ],
319             );
320             my @generic_results = (
321               [ 'foo', 'bar' ],
322               [ 'this_one', 'that_one' ],
323               [ 'this_two', 'that_two' ],
324             );
325
326             my $dbh = DBI->connect( 'DBI:Mock:', '', '' );
327             $dbh->{mock_add_resultset} = \@user_results;    # add first resultset
328             $dbh->{mock_add_resultset} = \@generic_results; # add second resultset
329             my ( $sth );
330             eval {
331                $sth = $dbh->prepare( 'SELECT login, first_name, last_name FROM foo' );
332                $sth->execute();
333             };
334
335             # this will fetch rows from the first resultset...
336             my $row1 = $sth->fetchrow_arrayref;
337             my $user1 = User->new( login => $row->[0],
338                                   first => $row->[1],
339                                   last  => $row->[2] );
340             is( $user1->full_name, 'Chris Winters' );
341
342             my $row2 = $sth->fetchrow_arrayref;
343             my $user2 = User->new( login => $row->[0],
344                                   first => $row->[1],
345                                   last  => $row->[2] );
346             is( $user2->full_name, 'Bobby Flay' );
347             ...
348
349             my $sth_generic = $dbh->prepare( 'SELECT foo, bar FROM baz' );
350             $sth_generic->execute;
351
352             # this will fetch rows from the second resultset...
353             my $row = $sth->fetchrow_arrayref;
354
355           You can also associate a resultset with a particular SQL statement
356           instead of adding them in the order they will be fetched:
357
358             $dbh->{mock_add_resultset} = {
359                sql     => 'SELECT foo, bar FROM baz',
360                results => [
361                    [ 'foo', 'bar' ],
362                    [ 'this_one', 'that_one' ],
363                    [ 'this_two', 'that_two' ],
364                ],
365             };
366
367           This will return the given results when the statement 'SELECT foo,
368           bar FROM baz' is prepared. Note that they will be returned every
369           time the statement is prepared, not just the first. It should also
370           be noted that if you want, for some reason, to change the result
371           set bound to a particular SQL statement, all you need to do is add
372           the result set again with the same SQL statement and DBD::Mock will
373           overwrite it.
374
375           It should also be noted that the "rows" method will return the
376           number of records stocked in the result set. So if your
377           code/application makes use of the "$sth->rows" method for things
378           like UPDATE and DELETE calls you should stock the result set like
379           so:
380
381             $dbh->{mock_add_resultset} = {
382                sql     => 'UPDATE foo SET baz = 1, bar = 2',
383                # this will appear to have updated 3 rows
384                results => [[ 'rows' ], [], [], []],
385             };
386
387             # or ...
388
389             $dbh->{mock_add_resultset} = {
390                sql     => 'DELETE FROM foo WHERE bar = 2',
391                # this will appear to have deleted 1 row
392                results => [[ 'rows' ], []],
393             };
394
395           Now I admit this is not the most elegant way to go about this, but
396           it works for me for now, and until I can come up with a better
397           method, or someone sends me a patch ;) it will do for now.
398
399           If you want a given statement to fail, you will have to use the
400           hashref method and add a 'failure' key. That key can be handed an
401           arrayref with the error number and error string, in that order. It
402           can also be handed a hashref with two keys - errornum and
403           errorstring. If the 'failure' key has no useful value associated
404           with it, the errornum will be '1' and the errorstring will be
405           'Unknown error'.
406
407       mock_get_info
408           This attribute can be used to set up values for get_info(). It
409           takes a hashref of attribute_name/value pairs. See DBI for more
410           information on the information types and their meaning.
411
412       mock_session
413           This attribute can be used to set a current DBD::Mock::Session
414           object. For more information on this, see the DBD::Mock::Session
415           docs below. This attribute can also be used to remove the current
416           session from the $dbh simply by setting it to "undef".
417
418       mock_last_insert_id
419           This attribute is incremented each time an INSERT statement is
420           passed to "prepare" on a per-handle basis. It's starting value can
421           be set with  the 'mock_start_insert_id' attribute (see below).
422
423             $dbh->{mock_start_insert_id} = 10;
424
425             my $sth = $dbh->prepare('INSERT INTO Foo (foo, bar) VALUES(?, ?)');
426
427             $sth->execute(1, 2);
428             # $dbh->{mock_last_insert_id} == 10
429
430             $sth->execute(3, 4);
431             # $dbh->{mock_last_insert_id} == 11
432
433           For more examples, please refer to the test file
434           t/025_mock_last_insert_id.t.
435
436       mock_start_insert_id
437           This attribute can be used to set a start value for the
438           'mock_last_insert_id' attribute. It can also be used to effectively
439           reset the 'mock_last_insert_id' attribute as well.
440
441           This attribute also can be used with an ARRAY ref parameter, it's
442           behavior is slightly different in that instead of incrementing the
443           value for every "prepare" it will only increment for each
444           "execute". This allows it to be used over multiple "execute" calls
445           in a single $sth. It's usage looks like this:
446
447             $dbh->{mock_start_insert_id} = [ 'Foo', 10 ];
448             $dbh->{mock_start_insert_id} = [ 'Baz', 20 ];
449
450             my $sth1 = $dbh->prepare('INSERT INTO Foo (foo, bar) VALUES(?, ?)');
451
452             my $sth2 = $dbh->prepare('INSERT INTO Baz (baz, buz) VALUES(?, ?)');
453
454             $sth1->execute(1, 2);
455             # $dbh->{mock_last_insert_id} == 10
456
457             $sth2->execute(3, 4);
458             # $dbh->{mock_last_insert_id} == 20
459
460           Note that DBD::Mock's matching of table names in 'INSERT'
461           statements is fairly simple, so if your table names are quoted in
462           the insert statement ("INSERT INTO "Foo"") then you need to quote
463           the name for "mock_start_insert_id":
464
465             $dbh->{mock_start_insert_id} = [ q{"Foo"}, 10 ];
466
467       mock_add_parser
468           DBI provides some simple parsing capabilities for 'SELECT'
469           statements to ensure that placeholders are bound properly. And
470           typically you may simply want to check after the fact that a
471           statement is syntactically correct, or at least what you expect.
472
473           But other times you may want to parse the statement as it is
474           prepared rather than after the fact. There is a hook in this mock
475           database driver for you to provide your own parsing routine or
476           object.
477
478           The syntax is simple:
479
480             $dbh->{mock_add_parser} = sub {
481                my ( $sql ) = @_;
482                unless ( $sql =~ /some regex/ ) {
483                    die "does not contain secret fieldname";
484                }
485             };
486
487           You can also add more than one for a handle. They will be called in
488           order, and the first one to fail will halt the parsing process:
489
490             $dbh->{mock_add_parser} = \&parse_update_sql;
491             $dbh->{mock_add-parser} = \&parse_insert_sql;
492
493           Depending on the 'PrintError' and 'RaiseError' settings in the
494           database handle any parsing errors encountered will issue a "warn"
495           or "die". No matter what the statement handle will be "undef".
496
497           Instead of providing a subroutine reference you can use an object.
498           The only requirement is that it implements the method "parse()" and
499           takes a SQL statement as the only argument. So you should be able
500           to do something like the following (untested):
501
502             my $parser = SQL::Parser->new( 'mysql', { RaiseError => 1 } );
503             $dbh->{mock_add_parser} = $parser;
504
505       mock_data_sources & mock_add_data_sources
506           These properties will dispatch to the Driver's properties of the
507           same name.
508
509   Database Driver Methods
510       last_insert_id
511           This returns the value of "mock_last_insert_id".
512
513       In order to capture begin_work(), commit(), and rollback(), DBD::Mock
514       will create statements for them, as if you had issued them in the
515       appropriate SQL command line program. They will go through the standard
516       prepare()-execute() cycle, meaning that any custom SQL parsers will be
517       triggered and DBD::Mock::Session will need to know about these
518       statements.
519
520       begin_work
521           This will create a statement with SQL of "BEGIN WORK" and no
522           parameters.
523
524       commit
525           This will create a statement with SQL of "COMMIT" and no
526           parameters.
527
528       rollback
529           This will create a statement with SQL of "ROLLBACK" and no
530           parameters.
531
532   Statement Handle Properties
533       Active
534           Returns true if the handle is a 'SELECT' and has more records to
535           fetch, false otherwise. (From the DBI.)
536
537       mock_statement
538           The SQL statement this statement handle was "prepare"d with. So if
539           the handle were created with:
540
541             my $sth = $dbh->prepare( 'SELECT * FROM foo' );
542
543           This would return:
544
545             SELECT * FROM foo
546
547           The original statement is unmodified so if you are checking against
548           it in tests you may want to use a regex rather than a straight
549           equality check. (However if you use a phrasebook to store your SQL
550           externally you are a step ahead...)
551
552       mock_fields
553           Fields used by the statement. As said elsewhere we do no analysis
554           or parsing to find these, you need to define them beforehand. That
555           said, you do not actually need this very often.
556
557           Note that this returns the same thing as the normal statement
558           property 'FIELD'.
559
560       mock_params
561           Returns an arrayref of parameters bound to this statement in the
562           order specified by the bind type. For instance, if you created and
563           stocked a handle with:
564
565             my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' );
566             $sth->bind_param( 2, 'yes' );
567             $sth->bind_param( 1, 7783 );
568
569           This would return:
570
571             [ 7738, 'yes' ]
572
573           The same result will occur if you pass the parameters via
574           "execute()" instead:
575
576             my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = ? AND is_active = ?' );
577             $sth->execute( 7783, 'yes' );
578
579       mock_records
580           An arrayref of arrayrefs representing the records the mock
581           statement was stocked with.
582
583       mock_num_records
584           Number of records the mock statement was stocked with; if never
585           stocked it is still 0. (Some weirdos might expect undef...)
586
587       mock_num_rows
588           This returns the same value as mock_num_records. And is what is
589           returned by the "rows" method of the statement handle.
590
591       mock_current_record_num
592           Current record the statement is on; returns 0 in the instances when
593           you have not yet called "execute()" and if you have not yet called
594           a "fetch" method after the execute.
595
596       mock_is_executed
597           Whether "execute()" has been called against the statement handle.
598           Returns 'yes' if so, 'no' if not.
599
600       mock_is_finished
601           Whether "finish()" has been called against the statement handle.
602           Returns 'yes' if so, 'no' if not.
603
604       mock_is_depleted
605           Returns 'yes' if all the records in the recordset have been
606           returned. If no "fetch()" was executed against the statement, or If
607           no return data was set this will return 'no'.
608
609       mock_my_history
610           Returns a "DBD::Mock::StatementTrack" object which tracks the
611           actions performed by this statement handle. Most of the actions are
612           separately available from the properties listed above, so you
613           should never need this.
614

DBD::Mock::Pool

616       This module can be used to emulate Apache::DBI style DBI connection
617       pooling. Just as with Apache::DBI, you must enable DBD::Mock::Pool
618       before loading DBI.
619
620         use DBD::Mock qw(Pool);
621         # followed by ...
622         use DBI;
623
624       While this may not seem to make a lot of sense in a single-process
625       testing scenario, it can be useful when testing code which assumes a
626       multi-process Apache::DBI pooled environment.
627

DBD::Mock::StatementTrack

629       Under the hood this module does most of the work with a
630       "DBD::Mock::StatementTrack" object. This is most useful when you are
631       reviewing multiple statements at a time, otherwise you might want to
632       use the "mock_*" statement handle attributes instead.
633
634       new( %params )
635           Takes the following parameters:
636
637           ·   return_data: Arrayref of return data records
638
639           ·   fields: Arrayref of field names
640
641           ·   bound_params: Arrayref of bound parameters
642
643       statement (Statement attribute 'mock_statement')
644           Gets/sets the SQL statement used.
645
646       fields  (Statement attribute 'mock_fields')
647           Gets/sets the fields to use for this statement.
648
649       bound_params  (Statement attribute 'mock_params')
650           Gets/set the bound parameters to use for this statement.
651
652       return_data  (Statement attribute 'mock_records')
653           Gets/sets the data to return when asked (that is, when someone
654           calls 'fetch' on the statement handle).
655
656       current_record_num (Statement attribute 'mock_current_record_num')
657           Gets/sets the current record number.
658
659       is_active() (Statement attribute 'Active')
660           Returns true if the statement is a SELECT and has more records to
661           fetch, false otherwise. (This is from the DBI, see the 'Active'
662           docs under 'ATTRIBUTES COMMON TO ALL HANDLES'.)
663
664       is_executed( $yes_or_no ) (Statement attribute 'mock_is_executed')
665           Sets the state of the tracker 'executed' flag.
666
667       is_finished( $yes_or_no ) (Statement attribute 'mock_is_finished')
668           If set to 'yes' tells the tracker that the statement is finished.
669           This resets the current record number to '0' and clears out the
670           array ref of returned records.
671
672       is_depleted() (Statement attribute 'mock_is_depleted')
673           Returns true if the current record number is greater than the
674           number of records set to return.
675
676       num_fields
677           Returns the number of fields set in the 'fields' parameter.
678
679       num_rows
680           Returns the number of records in the current result set.
681
682       num_params
683           Returns the number of parameters set in the 'bound_params'
684           parameter.
685
686       bound_param( $param_num, $value )
687           Sets bound parameter $param_num to $value. Returns the arrayref of
688           currently-set bound parameters. This corresponds to the
689           'bind_param' statement handle call.
690
691       bound_param_trailing( @params )
692           Pushes @params onto the list of already-set bound parameters.
693
694       mark_executed()
695           Tells the tracker that the statement has been executed and resets
696           the current record number to '0'.
697
698       next_record()
699           If the statement has been depleted (all records returned) returns
700           undef; otherwise it gets the current recordfor returning,
701           increments the current record number and returns the current
702           record.
703
704       to_string()
705           Tries to give an decent depiction of the object state for use in
706           debugging.
707

DBD::Mock::StatementTrack::Iterator

709       This object can be used to iterate through the current set of
710       "DBD::Mock::StatementTrack" objects in the history by fetching the
711       'mock_all_history_iterator' attribute from a database handle. This
712       object is very simple and is meant to be a convience to make writing
713       long test script easier. Aside from the constructor ("new") this object
714       has only one method.
715
716           next
717
718           Calling "next" will return the next "DBD::Mock::StatementTrack"
719           object in the history. If there are no more
720           "DBD::Mock::StatementTrack" objects available, then this method
721           will return false.
722
723           reset
724
725           This will reset the internal pointer to the begining of the
726           statement history.
727

DBD::Mock::Session

729       The DBD::Mock::Session object is an alternate means of specifying the
730       SQL statements and result sets for DBD::Mock. The idea is that you can
731       specify a complete 'session' of usage, which will be verified through
732       DBD::Mock. Here is an example:
733
734         my $session = DBD::Mock::Session->new('my_session' => (
735               {
736                   statement => "SELECT foo FROM bar", # as a string
737                   results   => [[ 'foo' ], [ 'baz' ]]
738               },
739               {
740                   statement => qr/UPDATE bar SET foo \= \'bar\'/, # as a reg-exp
741                   results   => [[]]
742               },
743               {
744                   statement => sub {  # as a CODE ref
745                           my ($SQL, $state) = @_;
746                           return $SQL eq "SELECT foo FROM bar";
747                           },
748                   results   => [[ 'foo' ], [ 'bar' ]]
749               },
750               {
751                   # with bound parameters
752                   statement    => "SELECT foo FROM bar WHERE baz = ? AND borg = ?",
753                   # check exact bound param value,
754                   # then check it against regexp
755                   bound_params => [ 10, qr/\d+/ ],
756                   results      => [[ 'foo' ], [ 'baz' ]]
757               }
758         ));
759
760       As you can see, a session is essentially made up a list of HASH
761       references we call 'states'. Each state has a 'statement' and a set of
762       'results'. If DBD::Mock finds a session in the 'mock_session'
763       attribute, then it will pass the current $dbh and SQL statement to that
764       DBD::Mock::Session. The SQL statement will be checked against the
765       'statement'  field in the current state. If it passes, then the
766       'results' of the current state will get feed to DBD::Mock through the
767       'mock_add_resultset' attribute. We then advance to the next state in
768       the session, and wait for the next call through DBD::Mock. If at any
769       time the SQL statement does not match the current state's 'statement',
770       or the session runs out of available states, an error will be raised
771       (and propagated through the normal DBI error handling based on your
772       values for RaiseError and PrintError).
773
774       Also, as can be seen in the the session element, bound parameters can
775       also be supplied and tested. In this statement, the SQL is compared,
776       then when the statement is executed, the bound parameters are also
777       checked. The bound parameters much match in both number of parameters
778       and the parameters themselves, or an error will be raised.
779
780       As can also be seen in the example above, 'statement' fields can come
781       in many forms. The simplest is a string, which will be compared using
782       "eq" against the currently running statement. The next is a reg-exp
783       reference, this too will get compared against the currently running
784       statement. The last option is a CODE ref, this is sort of a catch-all
785       to allow for a wide range of SQL comparison approaches (including using
786       modules like SQL::Statement or SQL::Parser for detailed functional
787       comparisons). The first argument to the CODE ref will be the currently
788       active SQL statement to compare against, the second argument is a
789       reference to the current state HASH (in case you need to alter the
790       results, or store extra information). The CODE is evaluated in boolean
791       context and throws and exception if it is false.
792
793           new ($session_name, @session_states)
794
795           A $session_name can be optionally be specified, along with at least
796           one @session_states. If you don't specify a $session_name, then a
797           default one will be created for you. The @session_states must all
798           be HASH references as well, if this conditions fail, an exception
799           will be thrown.
800
801           verify_statement ($dbh, $SQL)
802
803           This will check the $SQL against the current state's 'statement'
804           value, and if it passes will add the current state's 'results' to
805           the $dbh. If for some reason the 'statement' value is bad, not of
806           the prescribed type, an exception is thrown. See above for more
807           details.
808
809           verify_bound_params ($dbh, $params)
810
811           If the 'bound_params' slot is available in the current state, this
812           will check the $params against the current state's 'bound_params'
813           value. Both number of parameters and the parameters themselves must
814           match, or an error will be raised.
815
816           reset
817
818           Calling this method will reset the state of the session object so
819           that it can be reused.
820

EXPERIMENTAL FUNCTIONALITY

822       All functionality listed here is highly experimental and should be used
823       with great caution (if at all).
824
825       Error handling in mock_add_resultset
826           We have added experimental erro handling in mock_add_resultset the
827           best example is the test file t/023_statement_failure.t, but it
828           looks something like this:
829
830             $dbh->{mock_add_resultset} = {
831                 sql => 'SELECT foo FROM bar',
832                 results => DBD::Mock->NULL_RESULTSET,
833                 failure => [ 5, 'Ooops!' ],
834             };
835
836           The 5 is the DBI error number, and 'Ooops!' is the error string
837           passed to DBI. This basically allows you to force an error
838           condition to occur when a given SQL statement is execute. We are
839           currently working on allowing more control on the 'when' and
840           'where' the error happens, look for it in future releases.
841
842       Attribute Aliasing
843           Basically this feature allows you to alias attributes to other
844           attributes. So for instance, you can alias a commonly expected
845           attribute like 'mysql_insertid' to something DBD::Mock already has
846           like 'mock_last_insert_id'. While you can also just set
847           'mysql_insertid' yourself, this functionality allows it to take
848           advantage of things like the autoincrementing of the
849           'mock_last_insert_id' attribute.
850
851           Right now this feature is highly experimental, and has been added
852           as a first attempt to automatically handle some of the DBD specific
853           attributes which are commonly used/accessed in DBI programming. The
854           functionality is off by default so as to not cause any issues with
855           backwards compatability, but can easily be turned on and off like
856           this:
857
858             # turn it on
859             $DBD::Mock::AttributeAliasing++;
860
861             # turn it off
862             $DBD::Mock::AttributeAliasing = 0;
863
864           Once this is turned on, you will need to choose a database specific
865           attribute aliasing table like so:
866
867             DBI->connect('dbi:Mock:MySQL', '', '');
868
869           The 'MySQL' in the DSN will be picked up and the MySQL specific
870           attribute aliasing will be used.
871
872           Right now only MySQL is supported by this feature, and even that
873           support is very minimal. Currently the MySQL $dbh and $sth
874           attributes 'mysql_insertid' are aliased to the $dbh attribute
875           'mock_last_insert_id'. It is possible to add more aliases though,
876           using the "DBD::Mock:_set_mock_attribute_aliases" function (see the
877           source code for details).
878

BUGS

880       Odd $dbh attribute behavior
881           When writing the test suite I encountered some odd behavior with
882           some $dbh attributes. I still need to get deeper into how DBD's
883           work to understand what it is that is actually doing wrong.
884

TO DO

886       Make DBD specific handlers
887           Each DBD has its own quirks and issues, it would be nice to be able
888           to handle those issues with DBD::Mock in some way. I have an number
889           of ideas already, but little time to sit down and really flesh them
890           out. If you have any suggestions or thoughts, feel free to email me
891           with them.
892
893       Enhance the DBD::Mock::StatementTrack object
894           I would like to have the DBD::Mock::StatementTrack object handle
895           more of the mock_* attributes. This would encapsulate much of the
896           mock_* behavior in one place, which would be a good thing.
897
898           I would also like to add the ability to bind a subroutine (or
899           possibly an object) to the result set, so that the results can be
900           somewhat more dynamic and allow for a more realistic interaction.
901

CODE COVERAGE

903       We use Devel::Cover to test the code coverage of my tests, below is the
904       Devel::Cover report on this module test suite.
905
906         ---------------------------- ------ ------ ------ ------ ------ ------ ------
907         File                           stmt   bran   cond    sub    pod   time  total
908         ---------------------------- ------ ------ ------ ------ ------ ------ ------
909         blib/lib/DBD/Mock.pm           92.0   86.6   77.9   95.3    0.0  100.0   89.5
910         Total                          92.0   86.6   77.9   95.3    0.0  100.0   89.5
911         ---------------------------- ------ ------ ------ ------ ------ ------ ------
912

SEE ALSO

914       DBI
915
916       DBD::NullP, which provided a good starting point
917
918       Test::MockObject, which provided the approach
919
920       Test::MockObject article -
921       <http://www.perl.com/pub/a/2002/07/10/tmo.html>
922
923       Perl Code Kata: Testing Databases -
924       <http://www.perl.com/pub/a/2005/02/10/database_kata.html>
925

DISCUSSION GROUP

927       We have created a DBD::Mock google group for discussion/questions about
928       this module.
929
930       http://groups-beta.google.com/group/DBDMock <http://groups-
931       beta.google.com/group/DBDMock>
932

ACKNOWLEDGEMENTS

934       Thanks to Ryan Gerry for his patch in RT #26604
935       Thanks to Marc Beyer for his patch in RT #16951
936       Thanks to Justin DeVuyst for the mock_connect_fail idea
937       Thanks to Thilo Planz for the code for "bind_param_inout"
938       Thanks to Shlomi Fish for help tracking down RT Bug #11515
939       Thanks to Collin Winter for the patch to fix the "begin_work()",
940       "commit()" and "rollback()" methods.
941       Thanks to Andrew McHarg <amcharg@acm.org> for "fetchall_hashref()",
942       "fetchrow_hashref()" and "selectcol_arrayref()" methods and tests.
943       Thanks to Andrew W. Gibbs for the "mock_last_insert_ids" patch and test
944       Thanks to Chas Owens for patch and test for the "mock_can_prepare",
945       "mock_can_execute", and "mock_can_fetch" features.
946
948       Copyright (C) 2004 Chris Winters <chris@cwinters.com>
949
950       Copyright (C) 2004-2007 Stevan Little <stevan@iinteractive.com>
951
952       Copyright (C) 2007 Rob Kinyon <rob.kinyon@gmail.com>
953
954       This library is free software; you can redistribute it and/or modify it
955       under the same terms as Perl itself.
956

AUTHORS

958       Chris Winters <chris@cwinters.com>
959
960       Stevan Little <stevan@iinteractive.com>
961
962       Rob Kinyon <rob.kinyon@gmail.com>
963
964
965
966perl v5.12.0                      2010-05-12                      DBD::Mock(3)
Impressum