summaryrefslogtreecommitdiff
path: root/t/CP_Testing.pm
blob: a0bc04e2882d7f0e27aed9475cef9181342e54da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package CP_Testing;

## Common methods used by the other tests for check_postgres.pl

use strict;
use warnings;
use Data::Dumper;
use Time::HiRes qw/sleep/;
use DBI;
use Cwd;

our $DEBUG = 0;

use vars qw/$com $info $count/;

my $fakeschema = 'cptest';

sub new {
	my $class = shift;
	my $arg = shift || {};
	my $self = {
		started  => time(),
		dbdir    => $arg->{dbdir}    || 'test_database_check_postgres',
		testuser => $arg->{testuser} || 'check_postgres_testing',
	};
	if (exists $arg->{default_action}) {
		$self->{action} = $arg->{default_action};
	}
	return bless $self => $class;
}

sub cleanup {

	my $self = shift;
	my $dbdir = $self->{dbdir} or die;
	my $pidfile = "$dbdir/data/postmaster.pid";
	return if ! -e $pidfile;
	open my $fh, '<', $pidfile or die qq{Could not open "$pidfile": $!\n};
	<$fh> =~ /^(\d+)/ or die qq{File "$pidfile" did not start with a number!\n};
	my $pid = $1;
	close $fh or die qq{Could not close "$pidfile": $!\n};
	kill 15 => $pid;
	sleep 1;
	if (kill 0 => $pid) {
		kill 9 => $pid;
	}
	return;
}

sub test_database_handle {

	## Request for a database handle: create and startup DB as needed

	my $self = shift;
	my $arg = shift || {};
	$arg->{dbname} ||= $self->{dbname} || 'postgres';

	ref $arg eq 'HASH' or die qq{Must pass a hashref (or nothing) to test_database_handle\n};

	## Create the test database directory if it does not exist
	my $dbdir = $self->{dbdir};
	if (! -d $dbdir) {

		-e $dbdir and die qq{Oops: I cannot create "$dbdir", there is already a file there!\n};

		Test::More::diag qq{Creating database in directory "$dbdir"\n};

		mkdir $dbdir;

		my $initdb = $ENV{PGINITDB} || 'initdb';

		$com = qq{LC_ALL=en LANG=C $initdb --locale=C -E UTF8 -D $dbdir/data 2>&1};
		eval {
			$info = qx{$com};
		};
		if ($@) {
			die qq{Failed to run "$com": error was $@\n};
		}

		## Modify the postgresql.conf
		my $cfile = "$dbdir/data/postgresql.conf";
		open my $cfh, '>>', $cfile or die qq{Could not open "$cfile": $!\n};
		print $cfh qq{\n\n## check_postgres.pl testing parameters\n};
		print $cfh qq{listen_addresses = ''\n};
		print $cfh qq{max_connections = 10\n};
		print $cfh qq{max_prepared_transactions = 5\n};
		print $cfh qq{autovacuum = off\n};
		print $cfh "\n";
		close $cfh or die qq{Could not close "$cfile": $!\n};

		mkdir "$dbdir/data/socket";

	}

	## See if the database is already running.
	my $needs_startup = 0;

	my $pidfile = "$dbdir/data/postmaster.pid";
	if (! -e $pidfile) {
		$needs_startup = 1;
	}
	else {
		open my $fh, '<', $pidfile or die qq{Could not open "$pidfile": $!\n};
		<$fh> =~ /^(\d+)/ or die qq{Invalid information in file "$pidfile", expected a PID\n};
		my $pid = $1;
		close $fh or die qq{Could not open "$pidfile": $!\n};
		## Send a signal to see if this PID is alive
		$count = kill 0 => $pid;
		if ($count == 0) {
			Test::More::diag qq{Found a PID file, but no postmaster. Removing file "$pidfile"\n};
			unlink $pidfile;
			$needs_startup = 1;
		}
	}

	if ($needs_startup) {

		my $logfile = "$dbdir/pg.log";

		unlink $logfile;

		$com = qq{LC_ALL=en LANG=C pg_ctl -o '-k socket' -l $logfile -D "$dbdir/data" start};
		eval {
			$info = qx{$com};
		};
		if ($@) {
			die qq{Failed to run "$com": got $!\n};
		}

		my $bail_out = 100;
		my $found = 0;
		open my $logfh, '<', $logfile or die qq{Could not open "$logfile": $!\n};
	  SCAN: {
			seek $logfh, 0, 0;
			while (<$logfh>) {
				if (/ready to accept connections/) {
					last SCAN;
				}
			}
			if (!$bail_out--) {
				die qq{Gave up waiting for $logfile to say it was ready\n};
			}
			sleep 0.1;
			redo;
		}
		close $logfh or die qq{Could not close "$logfile": $!\n};

	} ## end of needs startup

	my $here = cwd();
	my $dbhost = $self->{dbhost} = "$here/$dbdir/data/socket";
	$dbhost =~ s/^ /\\ /;
	$dbhost =~ s/([^\\]) /$1\\ /g;
	$self->{dbname} ||= 'postgres';
	my $dsn = qq{dbi:Pg:host=$dbhost;dbname=$self->{dbname}};
	my $dbuser = $self->{testuser};
	my @superdsn = ($dsn, $dbuser, '', {AutoCommit=>0,RaiseError=>1,PrintError=>0});
	my $dbh = DBI->connect(@superdsn);
	$dbh->ping() or die qq{Failed to ping!\n};

	$dbh->{AutoCommit} = 1;
	$dbh->{RaiseError} = 0;
	$dbh->do("CREATE USER $dbuser SUPERUSER");
	$dbh->do("CREATE USER sixpack NOSUPERUSER CREATEDB");
	$dbh->do("CREATE USER readonly NOSUPERUSER NOCREATEDB");
	$dbh->do("ALTER USER readonly SET default_transaction_read_only = 1");
	$dbh->do("CREATE DATABASE beedeebeedee");
	$dbh->do("CREATE DATABASE ardala");
	$dbh->{AutoCommit} = 0;
	$dbh->{RaiseError} = 1;

	if (! exists $self->{keep_old_schema}) {
		local $dbh->{Warn};
		$dbh->do("DROP SCHEMA IF EXISTS $fakeschema CASCADE");
	}

	if ($arg->{dbname} ne $self->{dbname}) {
		my $tmp_dsn = $dsn;
		$tmp_dsn =~ s/dbname=\w+/dbname=$arg->{dbname}/;
		my $tmp_dbh;
		eval { $tmp_dbh = DBI->connect($tmp_dsn, @superdsn[1..$#superdsn]) };
		if ($@) {
			local($dbh->{AutoCommit}) = 1;
			$dbh->do("CREATE DATABASE " . $arg->{dbname});
			eval { $tmp_dbh = DBI->connect($tmp_dsn, @superdsn[1..$#superdsn]) };
			die $@ if $@;
		}
		$dbh->disconnect;
		$dbh = $tmp_dbh;
		$self->{dbname} = $arg->{dbname};
	}

	$self->{dbh} = $dbh;
	$self->{dsn} = $dsn;
	$self->{superdsn} = \@superdsn;

	## Sanity check
	$dbh->do("ALTER USER $dbuser SET search_path = public");
	$dbh->do("SET search_path = public");
	$dbh->do("COMMIT");

	return $dbh;

} ## end of test_database_handle

sub get_command {
  return run('get_command', @_);
}

sub run {

	my $self = shift;
	my $get;
	if ($self eq 'get_command') {
		$get = $self;
		$self = shift;
	}
	my @arg = @_;
	my $extra = pop @arg || '';
	my $action = @arg ? $arg[0] : $self->{action} || die "First arg must be the command\n";

	my $double = $action =~ s/DB2// ? 1 : 0;

	my $dbhost = $self->{dbhost}   || die "No dbhost?";
	my $dbuser = $self->{testuser} || die "No testuser?";
	my $dbname = $self->{dbname}   || die "No dbname?";
	my $com = qq{perl check_postgres.pl --action=$action --dbhost="$dbhost" --dbuser=$dbuser};
	if ($extra !~ /dbname=/) {
		$com .= " --dbname=$dbname";
	}

	if ($double) {
		$com .= qq{ --dbhost2="$dbhost" --dbname2=ardala --dbuser2=$dbuser};
	}

	$extra and $com .= " $extra";

	$DEBUG and warn "DEBUG RUN: $com\n";

	return $com if $get;
	my $result;
	eval {
		$result = qx{$com 2>&1};
	};
	if ($@) {
		return "TESTERROR: $@";
	}

	return $result;

} ## end of run

sub get_user {
	my $self = shift;
	return $self->{testuser};
}

sub get_host {
	my $self = shift;
	return $self->{dbhost};
}

sub get_dbname {
	my $self = shift;
	return $self->{dbname};
}

sub get_dbh {
	my $self = shift;
	return $self->{dbh} || die;
}

sub get_fresh_dbh {

	my $self = shift;
	my $opt = shift || {};

	my $superdsn = $self->{superdsn} || die;

	if ($opt->{dbname}) {
		$superdsn->[0] =~ s/dbname=\w+/dbname=$opt->{dbname}/;
	}

	my $dbh = DBI->connect(@$superdsn);

	return $dbh;
}

sub create_fake_pg_table {

	## Dangerous: do not try this at home!

	my $self = shift;
	my $name = shift || die;
	my $args = shift || '';
	my $dbh = $self->{dbh} || die;
	my $dbuser = $self->{testuser} || die;
	if ($self->schema_exists($dbh,$fakeschema)) {
		local $dbh->{Warn};
		$dbh->do("DROP TABLE IF EXISTS $fakeschema.$name");
	}
	else {
		$dbh->do("CREATE SCHEMA $fakeschema");
	}

	my $funcargs = '';
	if ($args) {
		($funcargs = $args) =~ s/\w+/NULL/g;
		$funcargs = qq{($funcargs)};
	}

	$dbh->do("CREATE TABLE $fakeschema.$name AS SELECT * FROM $name$funcargs LIMIT 0");

	if ($args) {
		local $dbh->{Warn};
		$dbh->do("DROP FUNCTION IF EXISTS $fakeschema.$name($args)");
		$dbh->do("CREATE FUNCTION $fakeschema.$name($args) RETURNS SETOF TEXT LANGUAGE SQL AS 'SELECT * FROM $fakeschema.$name; '");
	}

	$dbh->do("ALTER USER $dbuser SET search_path = $fakeschema, public, pg_catalog");
	$dbh->commit();

} ## end of create_fake_pg_table


sub get_fake_schema {
	return $fakeschema;
}


sub set_fake_schema {

	my $self = shift;
	my $dbh = $self->{dbh} || die;
	my $dbuser = $self->{testuser} || die;
	if (!$self->schema_exists($dbh,$fakeschema)) {
		$dbh->do("CREATE SCHEMA $fakeschema");
	}

	$dbh->do("ALTER USER $dbuser SET search_path = $fakeschema, public, pg_catalog");
	$dbh->commit();

} ## end of set_fake_schema


sub remove_fake_pg_table {

	my $self = shift;
	my $name = shift || die;
	(my $name2 = $name) =~ s/\(.+//;
	my $dbh = $self->{dbh} || die;
	my $dbuser = $self->{testuser} || die;
	{
		local $dbh->{Warn};
		$dbh->do("DROP TABLE IF EXISTS public.$name2");
	}
	$dbh->do("ALTER USER $dbuser SET search_path = public");
	$dbh->commit();

} ## end of remove_fake_pg_table


sub table_exists {

	my ($self,$dbh,$table) = @_;

	my $SQL = 'SELECT count(1) FROM pg_class WHERE relname = ?';
	my $sth = $dbh->prepare($SQL);
	$sth->execute($table);
	my $count = $sth->fetchall_arrayref()->[0][0];
	return $count;

} ## end of table_exists


sub schema_exists {

	my ($self,$dbh,$schema) = @_;

	my $SQL = 'SELECT count(1) FROM pg_namespace WHERE nspname = ?';
	my $sth = $dbh->prepare($SQL);
	$sth->execute($schema);
	my $count = $sth->fetchall_arrayref()->[0][0];
	return $count;

} ## end of schema_exists


sub fake_version {

	my $self = shift;
	my $version = shift || '9.9';
	my $dbh = $self->{dbh} || die;
	my $dbuser = $self->{testuser} || die;

	if (! $self->schema_exists($dbh, $fakeschema)) {
		$dbh->do("CREATE SCHEMA $fakeschema");
	}

	$dbh->do(qq{
CREATE OR REPLACE FUNCTION $fakeschema.version()
RETURNS TEXT
LANGUAGE SQL
AS \$\$
SELECT 'PostgreSQL $version on fakefunction for check_postgres.pl testing'::text;
\$\$
});
	$dbh->do("ALTER USER $dbuser SET search_path = $fakeschema, public, pg_catalog");
	$dbh->commit();

} ## end of fake version


sub bad_fake_version {

	my $self = shift;
	my $version = shift || '9.9';
	my $dbh = $self->{dbh} || die;
	my $dbuser = $self->{testuser} || die;

	$dbh->do(qq{
CREATE OR REPLACE FUNCTION public.version()
RETURNS TEXT
LANGUAGE SQL
AS \$\$
SELECT 'Postgres $version on fakefunction for check_postgres.pl testing'::text;
\$\$
});
	$dbh->do("ALTER USER $dbuser SET search_path = public, pg_catalog");
	$dbh->commit();

} ## end of bad fake version

sub fake_self_version {

	## Look out...

	my $self = shift;
	my $version = shift || '9.9';
	my $file = 'check_postgres.pl';
	open my $fh, '+<', $file or die qq{Could not open "$file": $!\n};
	my $slurp;
	{ local $/; $slurp = <$fh> }
	$slurp =~ s/(our \$VERSION = '\d+\.\d+\.\d+';)/$1\n\$VERSION = '$version'; ## TESTING ONLY/;
	seek $fh, 0, 0;
	print $fh $slurp;
	truncate $fh, tell($fh);
	close $fh or die qq{Could not close "$file": $!\n};

} ## end of fake_self_version

sub restore_self_version {

	my $self = shift;
	my $file = 'check_postgres.pl';
	open my $fh, '+<', $file or die qq{Could not open "$file": $!\n};
	my $slurp;
	{ local $/; $slurp = <$fh> }
	$slurp =~ s/^\$VERSION = '\d+\.\d+\.\d+'.+?\n//gm;
	seek $fh, 0, 0;
	print $fh $slurp;
	truncate $fh, tell($fh);
	close $fh or die qq{Could not close "$file": $!\n};

} ## end of restore_self_version

sub reset_path {

	my $self = shift;
	my $dbh = $self->{dbh} || die;
	my $dbuser = $self->{testuser} || die;
	$dbh->do("ALTER USER $dbuser SET search_path = public");
	$dbh->commit();

} ## end of reset_path

1;