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( ', ', @{ $mock_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           The same using named parameters
580
581             my $sth = $dbh->prepare( 'SELECT * FROM foo WHERE id = :id AND is_active = :active' );
582             $sth->bind_param( ':id' => 7783 );
583             $sth->bind_param( ':active' => 'yes' );
584
585       mock_records
586           An arrayref of arrayrefs representing the records the mock
587           statement was stocked with.
588
589       mock_num_records
590           Number of records the mock statement was stocked with; if never
591           stocked it is still 0. (Some weirdos might expect undef...)
592
593       mock_num_rows
594           This returns the same value as mock_num_records. And is what is
595           returned by the "rows" method of the statement handle.
596
597       mock_current_record_num
598           Current record the statement is on; returns 0 in the instances when
599           you have not yet called "execute()" and if you have not yet called
600           a "fetch" method after the execute.
601
602       mock_is_executed
603           Whether "execute()" has been called against the statement handle.
604           Returns 'yes' if so, 'no' if not.
605
606       mock_is_finished
607           Whether "finish()" has been called against the statement handle.
608           Returns 'yes' if so, 'no' if not.
609
610       mock_is_depleted
611           Returns 'yes' if all the records in the recordset have been
612           returned. If no "fetch()" was executed against the statement, or If
613           no return data was set this will return 'no'.
614
615       mock_my_history
616           Returns a "DBD::Mock::StatementTrack" object which tracks the
617           actions performed by this statement handle. Most of the actions are
618           separately available from the properties listed above, so you
619           should never need this.
620

DBD::Mock::Pool

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

DBD::Mock::StatementTrack

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

DBD::Mock::StatementTrack::Iterator

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

DBD::Mock::Session

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

EXPERIMENTAL FUNCTIONALITY

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

BUGS

886       Odd $dbh attribute behavior
887           When writing the test suite I encountered some odd behavior with
888           some $dbh attributes. I still need to get deeper into how DBD's
889           work to understand what it is that is actually doing wrong.
890

TO DO

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

SEE ALSO

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

DISCUSSION GROUP

922       We have created a DBD::Mock google group for discussion/questions about
923       this module.
924
925       <http://groups.google.com/group/DBDMock>
926

ACKNOWLEDGEMENTS

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

AUTHORS

954       Chris Winters <chris@cwinters.com>
955
956       Stevan Little <stevan@iinteractive.com>
957
958       Rob Kinyon <rob.kinyon@gmail.com>
959
960       Mariano Wahlmann <dichoso _at_ gmail.com <gt>
961
962
963
964perl v5.28.0                      2018-07-14                      DBD::Mock(3)
Impressum