Debian Codegraph @

lemonldap-ng-common/t/04-Common-DBI-Reconnect.t

raw
1 use strict;
2 use warnings;
3 use Test::More;
4
5 # Test DBI reconnection after connection loss
6 # This verifies that the system recovers gracefully after a database
7 # connection is lost (e.g., after Patroni failover)
8
9 BEGIN {
10 use_ok('Lemonldap::NG::Common::Conf');
11 use_ok( 'Lemonldap::NG::Common::Lib::DBI', 'check_dbh' );
12 }
13
14 my $dbf = 't/cdbiReconnectTest.sql';
15 unlink $dbf;
16
17 SKIP: {
18 eval { require DBI; };
19 skip( "DBI not installed", 22 ) if ($@);
20 eval { require DBD::SQLite };
21 skip( "DBD::SQLite not installed", 22 ) if ($@);
22
23 my $h;
24
25 ok(
26 $h = Lemonldap::NG::Common::Conf->new( {
27 type => 'CDBI',
28 dbiChain => "DBI:SQLite:dbname=$dbf",
29 dbiUser => '',
30 dbiPassword => '',
31 }
32 ),
33 'CDBI object created'
34 );
35
36 $h->_dbh->{sqlite_unicode} = 1;
37 ok(
38 $h->_dbh->do(
39 'CREATE TABLE lmConfig (cfgNum int not null primary key, data text)'
40 ),
41 'Test database created'
42 );
43
44 my $cfg1 = { cfgNum => 1, test => 'initial_value' };
45 ok( $h->store($cfg1) == 1, 'Config 1 stored successfully' );
46 my $loaded;
47
48 subtest 'Automatic reconnection', sub {
49 my $oldDbh = $h->{_dbh} or fail 'No db handle';
50 $oldDbh->disconnect;
51 ok( !eval { $oldDbh->ping }, 'Ping fails on disconnected handle' );
52
53 my $cfg2 = { cfgNum => 2, test => 'after_reconnect' };
54 ok( $h->store($cfg2) == 2, 'Config 2 stored after reconnection' );
55
56 $loaded = $h->load(2);
57 ok( $loaded && $loaded->{test} eq 'after_reconnect',
58 'Config 2 loaded after reconnection' );
59
60 # Verify we got a new handle
61 ok( $h->{_dbh} ne $oldDbh, 'New DBH created after reconnection' );
62 };
63
64 subtest 'Multiple consecutive disconnections', sub {
65 for my $i ( 3 .. 5 ) {
66 $h->{_dbh}->disconnect if $h->{_dbh};
67 my $cfg = { cfgNum => $i, test => "iteration_$i" };
68 ok( $h->store($cfg) == $i,
69 "Config $i stored after reconnection #$i" );
70 }
71
72 # Verify all configs are accessible
73 for my $i ( 1 .. 5 ) {
74 $loaded = $h->load($i);
75 ok( $loaded,
76 "Config $i is accessible after multiple reconnections" );
77 }
78 };
79 }
80
81 # Cleanup
82 unlink $dbf;
83
84 done_testing();