]> git.donarmstrong.com Git - debbugs.git/blob - t/lib/DebbugsTest.pm
Merge branch 'database'
[debbugs.git] / t / lib / DebbugsTest.pm
1
2 package DebbugsTest;
3
4 =head1 NAME
5
6 DebbugsTest
7
8 =head1 SYNOPSIS
9
10 use DebbugsTest
11
12
13 =head1 DESCRIPTION
14
15 This module contains various testing routines used to test debbugs in
16 a "pseudo install"
17
18 =head1 FUNCTIONS
19
20 =cut
21
22 use warnings;
23 use strict;
24 use vars qw($VERSION $DEBUG %EXPORT_TAGS @EXPORT_OK @EXPORT);
25 use base qw(Exporter);
26
27 use IO::File;
28 use File::Temp qw(tempdir);
29 use Cwd qw(getcwd);
30 use Debbugs::MIME qw(create_mime_message);
31 use File::Basename qw(dirname basename);
32 use IPC::Open3;
33 use IO::Handle;
34 use Test::More;
35 use Test::PostgreSQL;
36
37 use Params::Validate qw(validate_with :types);
38
39 BEGIN{
40      $VERSION = 1.00;
41      $DEBUG = 0 unless defined $DEBUG;
42
43      @EXPORT = ();
44      %EXPORT_TAGS = (configuration => [qw(dirsize create_debbugs_configuration send_message)],
45                      mail          => [qw(num_messages_sent)],
46                      control       => [qw(test_control_commands)],
47                      database => [qw(create_postgresql_database update_postgresql_database)]
48                     );
49      @EXPORT_OK = ();
50      Exporter::export_ok_tags(keys %EXPORT_TAGS);
51      $EXPORT_TAGS{all} = [@EXPORT_OK];
52 }
53
54 # First, we're going to send mesages to receive.
55 # To do so, we'll first send a message to submit,
56 # then send messages to the newly created bugnumber.
57
58
59
60 sub create_debbugs_configuration {
61      my %param = validate_with(params => \@_,
62                                spec   => {debug => {type => BOOLEAN,
63                                                     default => exists $ENV{DEBUG}?
64                                                     $ENV{DEBUG}:0,
65                                                    },
66                                           cleanup => {type => BOOLEAN,
67                                                       optional => 1,
68                                                      },
69                                          },
70                               );
71      $param{cleanup} = $param{debug}?0:1 if not exists $param{cleanup};
72      my $sendmail_dir = tempdir(CLEANUP => $param{cleanup});
73      my $spool_dir = tempdir(CLEANUP => $param{cleanup});
74      my $config_dir = tempdir(CLEANUP => $param{cleanup});
75
76
77      $ENV{DEBBUGS_CONFIG_FILE}  ="$config_dir/debbugs_config";
78      $ENV{PERL5LIB} = getcwd();
79      $ENV{SENDMAIL_TESTDIR} = $sendmail_dir;
80      eval {
81      my $sendmail_tester = getcwd().'/t/sendmail_tester';
82      unless (-x $sendmail_tester) {
83           die q(t/sendmail_tester doesn't exist or isn't executable. You may be in the wrong directory.);
84      }
85      my %files_to_create = ("$config_dir/debbugs_config" => <<END,
86 \$gSendmail='$sendmail_tester';
87 \$gSpoolDir='$spool_dir';
88 \$gLibPath='@{[getcwd()]}/scripts';
89 \$gTemplateDir='@{[getcwd()]}/templates';
90 \$gWebDir='@{[getcwd()]}/html';
91 \$gWebHost='localhost';
92 1;
93 END
94                             "$spool_dir/nextnumber" => qq(1\n),
95                             "$config_dir/Maintainers" => qq(foo Blah Bleargh <foo\@baz.com>\nbar Bar Bleargh <bar\@baz.com>\n),
96                             "$config_dir/Maintainers.override" => qq(),
97                             "$config_dir/Source_maintainers" => qq(foo Blah Bleargh <foo\@baz.com>\nbar Bar Bleargh <bar\@baz.com>\n),
98                             "$config_dir/indices/sources" => <<END,
99 foo main foo
100 END
101                             "$config_dir/pseudo-packages.description" => '',
102                             "$config_dir/pseudo-packages.maintainers" => '',
103                            );
104      while (my ($file,$contents) = each %files_to_create) {
105           system('mkdir','-p',dirname($file));
106           my $fh = IO::File->new($file,'w') or
107                die "Unable to create $file: $!";
108           print {$fh} $contents or die "Unable to write $contents to $file: $!";
109           close $fh or die "Unable to close $file: $!";
110      }
111
112      system('touch',"$spool_dir/index.db.realtime");
113      system('ln','-s','index.db.realtime',
114             "$spool_dir/index.db");
115      system('touch',"$spool_dir/index.archive.realtime");
116      system('ln','-s','index.archive.realtime',
117             "$spool_dir/index.archive");
118
119      # create the spool files and sub directories
120      for my $dir (0..99) {
121          for my $archive (qw(db-h archive)) {
122              system('mkdir','-p',"$spool_dir/$archive/".sprintf('%02d',$dir));
123          }
124      }
125      system('mkdir','-p',"$spool_dir/incoming");
126      system('mkdir','-p',"$spool_dir/lock");
127      eval '
128 END{
129      if ($ENV{DEBUG}) {
130           diag("spool_dir:   $spool_dir\n");
131           diag("config_dir:   $config_dir\n",);
132           diag("sendmail_dir: $sendmail_dir\n");
133      }
134 }';
135
136      };
137      BAIL_OUT ($@) if ($@);
138      return (spool_dir => $spool_dir,
139              sendmail_dir => $sendmail_dir,
140              config_dir => $config_dir,
141             );
142 }
143
144 sub dirsize{
145      my ($dir) = @_;
146      opendir(DIR,$dir);
147      my @content = grep {!/^\.\.?$/} readdir(DIR);
148      closedir(DIR);
149      return scalar @content;
150 }
151
152
153 # We're going to use create mime message to create these messages, and
154 # then just send them to receive.
155 # First, check that submit@ works
156
157 sub send_message{
158      my %param = validate_with(params => \@_,
159                                spec   => {to => {type => SCALAR,
160                                                  default => 'submit@bugs.something',
161                                                 },
162                                           headers => {type => ARRAYREF,
163                                                      },
164                                           body    => {type => SCALAR,
165                                                      },
166                                           attachments => {type => ARRAYREF,
167                                                           default => [],
168                                                          },
169                                           run_processall =>{type => BOOLEAN,
170                                                             default => 1,
171                                                            },
172                                          }
173                               );
174      $ENV{LOCAL_PART} = $param{to};
175      my ($rfd,$wfd);
176      my $output='';
177      my $pipe_handler = $SIG{PIPE};
178      $SIG{PIPE} = 'IGNORE';
179      $SIG{CHLD} = 'DEFAULT';
180      my $pid = open3($wfd,$rfd,$rfd,'scripts/receive')
181           or die "Unable to start receive: $!";
182      print {$wfd} create_mime_message($param{headers},
183                                       $param{body},
184                                       $param{attachments}) or
185                                           die "Unable to to print to receive";
186      close($wfd) or die "Unable to close receive";
187      $SIG{PIPE} = $pipe_handler;
188      my $err = $? >> 8;
189      my $childpid = waitpid($pid,0);
190      if ($childpid != -1) {
191           $err = $? >> 8;
192           print STDERR "receive pid: $pid doesn't match childpid: $childpid\n" if $childpid != $pid;
193      }
194      if ($err != 0 ) {
195           my $rfh =  IO::Handle->new_from_fd($rfd,'r') or die "Unable to create filehandle: $!";
196           $rfh->blocking(0);
197           my $rv;
198           while ($rv = $rfh->sysread($output,1000,length($output))) {}
199           if (not defined $rv) {
200                print STDERR "Reading from STDOUT/STDERR would have blocked.";
201           }
202           print STDERR $output,qq(\n);
203           die "receive failed with exit status $err";
204      }
205      # now we should run processall to see if the message gets processed
206      if ($param{run_processall}) {
207           system('scripts/processall') == 0 or die "processall failed";
208      }
209 }
210
211 =item test_control_commands
212
213  test_control_commands(\%config,
214                        forcemerge => {command => 'forcemerge',
215                                       value   => '1 2',
216                                       status_key => 'mergedwith',
217                                       status_value => '2',
218                                       expect_error => 0,
219                                      });
220
221 Test a set of control commands to see if they will fail or not. Takes
222 SCALAR/HASHREF pairs, where the scalar should be unique, and the HASHREF
223 contains the following keys:
224
225 =over
226
227 =item command -- control command to issue
228
229 =item value -- value to pass to control command
230
231 =item status_key -- bug status key to check
232
233 =item status_value -- value of status key
234
235 =item expect_error -- whether to expect the control command to error or not
236
237 =back
238
239 =cut
240
241 sub test_control_commands {
242     my ($config,@commands) = @_;
243
244     # now we need to check to make sure that the control message actually did anything
245     # This is an eval because $ENV{DEBBUGS_CONFIG_FILE} isn't set at BEGIN{} time
246     eval "use Debbugs::Status qw(read_bug writebug);";
247     while (my ($command,$control_command) = splice(@commands,0,2)) {
248         # just check to see that control doesn't explode
249         $control_command->{value} = " $control_command->{value}" if length $control_command->{value}
250             and $control_command->{value} !~ /^\s/;
251         send_message(to => 'control@bugs.something',
252                      headers => [To   => 'control@bugs.something',
253                                  From => 'foo@bugs.something',
254                                  Subject => "Munging a bug with $command",
255                                 ],
256                      body => <<EOF) or fail 'message to control@bugs.something failed';
257 debug 10
258 $control_command->{command} $control_command->{value}
259 thanks
260 EOF
261         ;
262         # now we need to check to make sure the control message was processed without errors
263         if (not ($control_command->{expect_error} // 0)) {
264             ok(system('sh','-c','find '.$config->{sendmail_dir}.
265                       q( -type f | xargs grep -q "Subject: Processed: Munging a bug with $command")
266                      ) == 0,
267                'control@bugs.something'. "$command message was parsed without errors");
268         }
269         # now we need to check to make sure that the control message actually did anything
270         my $status;
271         $status = read_bug(exists $control_command->{bug}?(bug => $control_command->{bug}):(bug=>1),
272                            exists $control_command->{location}?(location => $control_command->{location}):(),
273                           );
274         is_deeply($status->{$control_command->{status_key}},
275                   $control_command->{status_value},
276                   "bug " .
277                   (exists $control_command->{bug}?$control_command->{bug}:1).
278                   " $command"
279                  )
280             or fail(Data::Dumper->Dump([$status],[qw(status)]));
281     }
282 }
283
284
285 {
286      package DebbugsTest::HTTPServer;
287      use base qw(HTTP::Server::Simple::CGI HTTP::Server::Simple::CGI::Environment);
288
289      our $child_pid = undef;
290      our $webserver = undef;
291      our $server_handler = undef;
292
293      END {
294           if (defined $child_pid) {
295                # stop the child
296                my $temp_exit = $?;
297                kill(15,$child_pid);
298                waitpid(-1,0);
299                $? = $temp_exit;
300           }
301      }
302
303      sub fork_and_create_webserver {
304           my ($handler,$port) = @_;
305           $port ||= 8080;
306           if (defined $child_pid) {
307                die "We appear to have already forked once";
308           }
309           $server_handler = $handler;
310           my $pid = fork;
311           return 0 if not defined $pid;
312           if ($pid) {
313                $child_pid = $pid;
314                # Wait here for a second to let the child start up
315                sleep 1;
316                return $pid;
317           }
318           else {
319                $webserver = DebbugsTest::HTTPServer->new($port);
320                $webserver->run;
321           }
322
323      }
324
325      sub handle_request {
326           if (defined $server_handler) {
327                $server_handler->(@_);
328           }
329           else {
330                warn "No handler defined\n";
331                print "No handler defined\n";
332           }
333      }
334 }
335
336 =head2 num_messages_sent
337
338      $SD_SIZE = num_messages_sent($SD_SIZE,2,$sendmail_dir,'2 messages have been sent properly');
339
340 Tests to make sure that at least a certain number of messages have
341 been sent since the last time this command was run. Usefull to test to
342 make sure that mail has been sent.
343
344 =cut
345
346 sub num_messages_sent {
347     my ($prev_size,$num_messages,$sendmail_dir,$test_name) = @_;
348     my $cur_size = dirsize($sendmail_dir);
349     ## print STDERR "sendmail: $sendmail_dir, want: $num_messages,
350     ## size: $cur_size, prev_size: $prev_size\n";
351     ok($cur_size-$prev_size >= $num_messages, $test_name);
352     return $cur_size;
353 }
354
355 =head2 create_postgresql_database
356
357 C<my $pgsql = create_postgresql_database();>
358
359 Create a postgresql database for testing; when the L<Test::PostgreSQL> object it
360 returns is destroyed (or goes out of scope) the database will be removed.
361
362 =cut
363
364 sub create_postgresql_database {
365     my $pgsql = Test::PostgreSQL->new(use_socket => 1) or
366         return undef;
367     my $installsql =
368         File::Spec->rel2abs(dirname(__FILE__).'/../..').
369             '/bin/debbugs-installsql';
370     # create the debversion extension
371     my $dbh = DBI->connect($pgsql->dsn);
372     $dbh->do(<<END) or die "Unable to create extension";
373 CREATE EXTENSION IF NOT EXISTS debversion;
374 END
375     # create the schema for the bug tracking system
376     my $dep_dir = File::Temp::tempdir(CLEANUP=>1);
377     system($installsql,
378            '--dsn',$pgsql->dsn,
379            '--install',
380            '--deployment-dir',$dep_dir);
381
382     initialize_postgresql_database($pgsql,@_);
383     return $pgsql;
384 }
385
386 =item iniitalize_postgresql_database
387
388 C<initialize_postgresql_database();>
389
390 Initialize postgresql database by calling debbugs-loadsql appropriately.
391
392 =cut
393
394 sub initialize_postgresql_database {
395     my ($pgsql,@options) = @_;
396     my $loadsql =
397         File::Spec->rel2abs(dirname(__FILE__).'/../..').
398             '/bin/debbugs-loadsql';
399
400     my $ftpdists =
401         File::Spec->rel2abs(dirname(__FILE__).'/../debian/dist');
402     my $debinfo_dir =
403         File::Spec->rel2abs(dirname(__FILE__).'/../debian/debinfo');
404     my %loadsql_commands =
405         (configuration => [],
406          suites => ['--ftpdists',$ftpdists],
407          debinfo => ['--debinfo-dir',$debinfo_dir],
408          packages => ['--ftpdists',$ftpdists],
409          maintainers => [],
410         );
411     for my $command (keys %loadsql_commands) {
412         system($loadsql,$command,
413                '--dsn',$pgsql->dsn,
414                @options,
415                @{$loadsql_commands{$command}}) == 0 or
416                    die "Unable to load $command";
417     }
418 }
419
420
421 =item update_postgresql_database
422
423 C<update_postgresql_database();>
424
425 Update the postgresql database by calling debbugs-loadsql appropriately.
426
427 =cut
428 sub update_postgresql_database {
429     my ($pgsql,@options) = @_;
430     my $loadsql =
431         File::Spec->rel2abs(dirname(__FILE__).'/../..').
432             '/bin/debbugs-loadsql';
433
434     my %loadsql_commands =
435         (bugs_and_logs => [],
436         );
437     for my $command (keys %loadsql_commands) {
438         system($loadsql,$command,
439                '--dsn',$pgsql->dsn,
440                @options,
441                @{$loadsql_commands{$command}}) == 0 or
442                    die "Unable to load $command";
443     }
444 }
445
446
447
448 1;
449
450 __END__
451
452
453