Cleanup some of the storage tests (no func. changes)
[dbsrgits/DBIx-Class.git] / t / storage / on_connect_do.t
1 use strict;
2 use warnings;
3
4 # !!! do not replace this with done_testing - tests reside in the callbacks
5 # !!! number of calls is important
6 use Test::More tests => 12;
7 # !!!
8 use Test::Exception;
9
10 use lib qw(t/lib);
11 use base 'DBICTest';
12 require DBI;
13
14
15 my $schema = DBICTest->init_schema(
16     no_connect  => 1,
17     no_deploy   => 1,
18 );
19
20 ok $schema->connection(
21   DBICTest->_database,
22   {
23     on_connect_do => 'CREATE TABLE TEST_empty (id INTEGER)',
24   },
25 ), 'connection()';
26
27 is_deeply (
28   $schema->storage->dbh->selectall_arrayref('SELECT * FROM TEST_empty'),
29   [],
30   'string version on_connect_do() worked'
31 );
32
33 $schema->storage->disconnect;
34
35 ok $schema->connection(
36     sub { DBI->connect(DBICTest->_database) },
37     {
38         on_connect_do       => [
39             'CREATE TABLE TEST_empty (id INTEGER)',
40             [ 'INSERT INTO TEST_empty VALUES (?)', {}, 2 ],
41             \&insert_from_subref,
42         ],
43         on_disconnect_do    =>
44             [\&check_exists, 'DROP TABLE TEST_empty', \&check_dropped],
45     },
46 ), 'connection()';
47
48 is_deeply (
49   $schema->storage->dbh->selectall_arrayref('SELECT * FROM TEST_empty'),
50   [ [ 2 ], [ 3 ], [ 7 ] ],
51   'on_connect_do() worked'
52 );
53 dies_ok {
54   $schema->storage->dbh->do('SELECT 1 FROM TEST_nonexistent');
55 } 'Searching for nonexistent table dies';
56
57 $schema->storage->disconnect();
58
59 my($connected, $disconnected, @cb_args);
60 ok $schema->connection(
61     DBICTest->_database,
62     {
63         on_connect_do       => sub { $connected = 1; @cb_args = @_; },
64         on_disconnect_do    => sub { $disconnected = 1 },
65     },
66 ), 'second connection()';
67 $schema->storage->dbh->do('SELECT 1');
68 ok $connected, 'on_connect_do() called after connect()';
69 ok ! $disconnected, 'on_disconnect_do() not called after connect()';
70 $schema->storage->disconnect();
71 ok $disconnected, 'on_disconnect_do() called after disconnect()';
72
73 isa_ok($cb_args[0], 'DBIx::Class::Storage', 'first arg to on_connect_do hook');
74
75 sub check_exists {
76     my $storage = shift;
77     ok $storage->dbh->do('SELECT 1 FROM TEST_empty'), 'Table still exists';
78     return;
79 }
80
81 sub check_dropped {
82     my $storage = shift;
83
84     dies_ok {
85       $storage->dbh->do('SELECT 1 FROM TEST_empty');
86     } 'Reading from dropped table fails';
87     return;
88 }
89
90 sub insert_from_subref {
91     my $storage = shift;
92     return [
93         [ 'INSERT INTO TEST_empty VALUES (?)', {}, 3 ],
94         'INSERT INTO TEST_empty VALUES (7)',
95     ];
96 }