]> git.sur5r.net Git - i3/i3/blob - testcases/complete-run.pl.in
Merge pull request #3410 from orestisf1993/min_width
[i3/i3] / testcases / complete-run.pl.in
1 #!/usr/bin/env perl
2 # vim:ts=4:sw=4:expandtab
3 # © 2010 Michael Stapelberg and contributors
4 package complete_run;
5 use strict;
6 use warnings;
7 use v5.10;
8 use utf8;
9 # the following are modules which ship with Perl (>= 5.10):
10 use Pod::Usage;
11 use File::Temp qw(tempfile tempdir);
12 use Getopt::Long;
13 use POSIX ();
14 use TAP::Harness;
15 use TAP::Parser;
16 use TAP::Parser::Aggregator;
17 use Time::HiRes qw(time);
18 use IO::Handle;
19
20 # these are shipped with the testsuite
21 use lib qw(@abs_top_builddir@/testcases/lib @abs_top_srcdir@/testcases/lib @abs_top_srcdir@/AnyEvent-I3/blib/lib);
22 use i3test::Util qw(slurp);
23 use StartXServer;
24 use StatusLine;
25 use TestWorker;
26 # the following modules are not shipped with Perl
27 use AnyEvent;
28 use AnyEvent::Util;
29 use AnyEvent::Handle;
30 use AnyEvent::I3 qw(:all);
31 use X11::XCB::Connection;
32 use JSON::XS; # AnyEvent::I3 depends on it, too.
33
34 binmode STDOUT, ':utf8';
35 binmode STDERR, ':utf8';
36
37 # Close superfluous file descriptors which were passed by running in a VIM
38 # subshell or situations like that.
39 AnyEvent::Util::close_all_fds_except(0, 1, 2);
40
41 our @CLEANUP;
42
43 # convenience wrapper to write to the log file
44 my $log;
45 sub Log { say $log "@_" }
46
47 my %timings;
48 my $help = 0;
49 # Number of tests to run in parallel. Important to know how many Xephyr
50 # instances we need to start (unless @displays are given). Defaults to
51 # num_cores * 2.
52 my $parallel = undef;
53 my @displays = ();
54 my %options = (
55     valgrind => 0,
56     strace => 0,
57     xtrace => 0,
58     coverage => 0,
59     restart => 0,
60     xvfb => 1,
61 );
62 my $keep_xserver_output = 0;
63
64 my $result = GetOptions(
65     "coverage-testing" => \$options{coverage},
66     "keep-xserver-output" => \$keep_xserver_output,
67     "valgrind" => \$options{valgrind},
68     "strace" => \$options{strace},
69     "xtrace" => \$options{xtrace},
70     "xvfb!" => \$options{xvfb},
71     "display=s" => \@displays,
72     "parallel=i" => \$parallel,
73     "help|?" => \$help,
74 );
75
76 pod2usage(-verbose => 2, -exitcode => 0) if $help;
77
78 # Check for missing executables
79 my @binaries = qw(
80                    @abs_top_builddir@/i3
81                    @abs_top_builddir@/i3bar/i3bar
82                    @abs_top_builddir@/i3-config-wizard/i3-config-wizard
83                    @abs_top_builddir@/i3-dump-log/i3-dump-log
84                    @abs_top_builddir@/i3-input/i3-input
85                    @abs_top_builddir@/i3-msg/i3-msg
86                    @abs_top_builddir@/i3-nagbar/i3-nagbar
87                );
88
89 foreach my $binary (@binaries) {
90     die "$binary executable not found, did you run “make”?" unless -e $binary;
91     die "$binary is not an executable" unless -x $binary;
92 }
93
94 my @test_binaries = qw(
95                         @abs_top_builddir@/test.commands_parser
96                         @abs_top_builddir@/test.config_parser
97                         @abs_top_builddir@/test.inject_randr15
98                     );
99
100 foreach my $binary (@test_binaries) {
101     die "$binary executable not found, did you run “make check”?" unless -e $binary;
102     die "$binary is not an executable" unless -x $binary;
103 }
104
105 $ENV{PATH} = join(':',
106     '@abs_top_builddir@/i3-nagbar',
107     '@abs_top_builddir@/i3-msg',
108     '@abs_top_builddir@/i3-input',
109     '@abs_top_builddir@/i3-dump-log',
110     '@abs_top_builddir@/i3-config-wizard',
111     '@abs_top_builddir@/i3bar',
112     '@abs_top_builddir@',
113     '@abs_top_srcdir@',
114     $ENV{PATH});
115
116 qx(Xephyr -help 2>&1);
117 die "Xephyr was not found in your path. Please install Xephyr (xserver-xephyr on Debian)." if $?;
118
119 qx(xvfb-run --help 2>&1);
120 if ($? && $options{xvfb}) {
121     say "xvfb-run not found, not running tests under xvfb. Install the xvfb package to speed up tests";
122     $options{xvfb} = 0;
123 }
124
125 if ($options{xvfb}) {
126     for (my $n = 99; $n < 120; $n++) {
127         my $path = File::Temp::tmpnam($ENV{TMPDIR} // "/tmp", "i3-testsXXXXXX");
128         if (!defined(POSIX::mkfifo($path, 0600))) {
129             die "mkfifo: $!";
130         }
131         my $pid = fork // die "fork: $!";
132         if ($pid == 0) {
133             # Child
134
135             # Xvfb checks whether the parent ignores USR1 and sends USR1 to the
136             # parent when ready, so that the wait call will be interrupted.  We
137             # can’t implement this in Perl, as Perl’s waitpid transparently
138             # handles -EINTR.
139             exec('/bin/sh', '-c', qq|trap "exit" INT; trap : USR1; (trap '' USR1; exec Xvfb :$n -screen 0 640x480x8 -nolisten tcp) & PID=\$!; wait; if ! kill -0 \$PID 2>/dev/null; then echo 1:\$PID > $path; else echo 0:\$PID > $path; wait \$PID; fi|);
140             die "exec: $!";
141         }
142         chomp(my $kill = slurp($path));
143         unlink($path);
144         my ($code, $xvfbpid) = ($kill =~ m,^([0-1]):(.*)$,);
145         next unless $code eq '0';
146
147         $ENV{DISPLAY} = ":$n";
148         say "Running tests under Xvfb display $ENV{DISPLAY}";
149
150         push(@CLEANUP, sub {
151             kill(15, $xvfbpid);
152         });
153         last;
154     }
155 }
156
157 @displays = split(/,/, join(',', @displays));
158 @displays = map { s/ //g; $_ } @displays;
159
160 # 2: get a list of all testcases
161 my @testfiles = @ARGV;
162
163 # if no files were passed on command line, run all tests from t/
164 if (scalar @testfiles == 0) {
165     @testfiles = <@abs_top_srcdir@/testcases/t/*.t> if @testfiles == 0;
166 } else {
167     @testfiles = map {
168         # Fully qualify each specified file if necessary
169         if (! -e $_) {
170             $_ = "@abs_top_srcdir@/testcases/$_";
171         }
172         $_
173     } @testfiles;
174 }
175
176 my $numtests = scalar @testfiles;
177
178 # No displays specified, let’s start some Xephyr instances.
179 if (@displays == 0) {
180     @displays = start_xserver($parallel, $numtests, $keep_xserver_output);
181 }
182
183 # 1: create an output directory for this test-run
184 my $outdir = "testsuite-";
185 $outdir .= POSIX::strftime("%Y-%m-%d-%H-%M-%S-", localtime());
186 $outdir .= `git describe --tags`;
187 chomp($outdir);
188 mkdir($outdir) or die "Could not create $outdir";
189 unlink("latest") if -l "latest";
190 symlink("$outdir", "latest") or die "Could not symlink latest to $outdir";
191
192
193 # connect to all displays for two reasons:
194 # 1: check if the display actually works
195 # 2: keep the connection open so that i3 is not the only client. this prevents
196 #    the X server from exiting
197 my @single_worker;
198 for my $display (@displays) {
199     my $screen;
200     my $x = X11::XCB::Connection->new(display => $display);
201     if ($x->has_error) {
202         die "Could not connect to display $display\n";
203     } else {
204         # start a TestWorker for each display
205         push @single_worker, worker($display, $x, $outdir, \%options);
206     }
207 }
208
209 # Read previous timing information, if available. We will be able to roughly
210 # predict the test duration and schedule a good order for the tests.
211 my $timingsjson = slurp('.last_run_timings.json') if -e '.last_run_timings.json';
212 %timings = %{decode_json($timingsjson)} if length($timingsjson) > 0;
213
214 # Re-order the files so that those which took the longest time in the previous
215 # run will be started at the beginning to not delay the whole run longer than
216 # necessary.
217 @testfiles = map  { $_->[0] }
218              sort { $b->[1] <=> $a->[1] }
219              map  { [$_, $timings{$_} // 999] } @testfiles;
220
221 # Run 000-load-deps.t first to bail out early when dependencies are missing.
222 my ($loadtest) = grep { $_ =~ m,t/000-load-deps.t$, } @testfiles;
223 if (defined($loadtest)) {
224     @testfiles = ($loadtest, grep { $_ ne $loadtest } @testfiles);
225 }
226
227 # Run 533-randr15.t last because it destructively modifies the RandR
228 # configuration of the X session, interfering with any test started afterwards.
229 my ($randrtest) = grep { $_ =~ m,t/533-randr15.t$, } @testfiles;
230 if (defined($randrtest)) {
231     @testfiles = ((grep { $_ ne $randrtest } @testfiles), $randrtest);
232 }
233
234 printf("\nRough time estimate for this run: %.2f seconds\n\n", $timings{GLOBAL})
235     if exists($timings{GLOBAL});
236
237 # Forget the old timings, we don’t necessarily run the same set of tests as
238 # before. Otherwise we would end up with left-overs.
239 %timings = (GLOBAL => time());
240
241 my $logfile = "$outdir/complete-run.log";
242 open $log, '>', $logfile or die "Could not create '$logfile': $!";
243 $log->autoflush(1);
244 say "Writing logfile to '$logfile'...";
245
246 # 3: run all tests
247 my @done;
248 my $num = @testfiles;
249 my $harness = TAP::Harness->new({ });
250
251 my $aggregator = TAP::Parser::Aggregator->new();
252 $aggregator->start();
253
254 status_init(displays => \@displays, tests => $num);
255
256 my $single_cv = AE::cv;
257
258 # We start tests concurrently: For each display, one test gets started. Every
259 # test starts another test after completing.
260 for (@single_worker) {
261     $single_cv->begin;
262     take_job($_, $single_cv, \@testfiles);
263 }
264
265 $single_cv->recv;
266
267 $aggregator->stop();
268
269 # print empty lines to separate failed tests from statuslines
270 print "\n\n";
271
272 for (@done) {
273     my ($test, $output) = @$_;
274     say "no output for $test" unless $output;
275     Log "output for $test:";
276     Log $output;
277     # print error messages of failed tests
278     say for $output =~ /^not ok.+\n+((?:^#.+\n)+)/mg
279 }
280
281 # 4: print summary
282 $harness->summary($aggregator);
283
284 close $log;
285
286 # 5: Save the timings for better scheduling/prediction next run.
287 $timings{GLOBAL} = time() - $timings{GLOBAL};
288 open(my $fh, '>', '.last_run_timings.json');
289 print $fh encode_json(\%timings);
290 close($fh);
291
292 # 6: Print the slowest test files.
293 my @slowest = map  { $_->[0] }
294               sort { $b->[1] <=> $a->[1] }
295               map  { [$_, $timings{$_}] }
296               grep { !/^GLOBAL$/ } keys %timings;
297 say '';
298 say 'The slowest tests are:';
299 printf("\t%s with %.2f seconds\n", $_, $timings{$_})
300     for @slowest[0..($#slowest > 4 ? 4 : $#slowest)];
301
302 # When we are running precisely one test, print the output. Makes developing
303 # with a single testcase easier.
304 if ($numtests == 1) {
305     say '';
306     say 'Test output:';
307     say slurp($logfile);
308 }
309
310 END { cleanup() }
311
312 # Report logfiles that match “(Leak|Address)Sanitizer:”.
313 my @logs_with_leaks;
314 for my $log (<$outdir/i3-log-for-*>) {
315     if (slurp($log) =~ /(Leak|Address)Sanitizer:/) {
316         push @logs_with_leaks, $log;
317     }
318 }
319 if (scalar @logs_with_leaks > 0) {
320     say "\nThe following test logfiles contain AddressSanitizer or LeakSanitizer reports:";
321     for my $log (sort @logs_with_leaks) {
322         say "\t$log";
323     }
324 }
325
326 exit ($aggregator->failed > 0);
327
328 #
329 # Takes a test from the beginning of @testfiles and runs it.
330 #
331 # The TAP::Parser (which reads the test output) will get called as soon as
332 # there is some activity on the stdout file descriptor of the test process
333 # (using an AnyEvent->io watcher).
334 #
335 # When a test completes and @done contains $num entries, the $cv condvar gets
336 # triggered to finish testing.
337 #
338 sub take_job {
339     my ($worker, $cv, $tests) = @_;
340
341     my $test = shift @$tests
342         or return $cv->end;
343
344     my $display = $worker->{display};
345
346     Log status($display, "$test: starting");
347     $timings{$test} = time();
348     worker_next($worker, $test);
349
350     # create a TAP::Parser with an in-memory fh
351     my $output;
352     my $parser = TAP::Parser->new({
353         source => do { open(my $fh, '<', \$output); $fh },
354     });
355
356     my $ipc = $worker->{ipc};
357
358     my $w;
359     $w = AnyEvent->io(
360         fh => $ipc,
361         poll => 'r',
362         cb => sub {
363             state $tests_completed = 0;
364             state $partial = '';
365
366             sysread($ipc, my $buf, 4096) or die "sysread: $!";
367
368             if ($partial) {
369                 $buf = $partial . $buf;
370                 $partial = '';
371             }
372
373             # make sure we feed TAP::Parser complete lines so it doesn't blow up
374             if (substr($buf, -1, 1) ne "\n") {
375                 my $nl = rindex($buf, "\n");
376                 if ($nl == -1) {
377                     $partial = $buf;
378                     return;
379                 }
380
381                 # strip partial from buffer
382                 $partial = substr($buf, $nl + 1, '');
383             }
384
385             # count lines before stripping eof-marker otherwise we might
386             # end up with for (1 .. 0) { } which would effectivly skip the loop
387             my $lines = $buf =~ tr/\n//;
388             my $t_eof = $buf =~ s/^$TestWorker::EOF$//m;
389
390             $output .= $buf;
391
392             for (1 .. $lines) {
393                 my $result = $parser->next;
394                 next unless defined($result);
395                 if ($result->is_test) {
396                     $tests_completed++;
397                     status($display, "$test: [$tests_completed/??] ");
398                 } elsif ($result->is_bailout) {
399                     Log status($display, "$test: BAILOUT");
400                     status_completed(scalar @done);
401                     say "";
402                     say "test $test bailed out: " . $result->explanation;
403                     exit 1;
404                 }
405             }
406
407             return unless $t_eof;
408
409             Log status($display, "$test: finished");
410             $timings{$test} = time() - $timings{$test};
411             status_completed(scalar @done);
412
413             $aggregator->add($test, $parser);
414             push @done, [ $test, $output ];
415
416             undef $w;
417             take_job($worker, $cv, $tests);
418         }
419     );
420 }
421
422 sub cleanup {
423     my $exitcode = $?;
424     $_->() for @CLEANUP;
425     exit $exitcode;
426 }
427
428 # must be in a begin block because we C<exit 0> above
429 BEGIN {
430     $SIG{$_} = sub {
431         require Carp; Carp::cluck("Caught SIG$_[0]\n");
432         cleanup();
433     } for qw(INT TERM QUIT KILL PIPE)
434 }
435
436 __END__
437
438 =head1 NAME
439
440 complete-run.pl - Run the i3 testsuite
441
442 =head1 SYNOPSIS
443
444 complete-run.pl [files...]
445
446 =head1 EXAMPLE
447
448 To run the whole testsuite on a reasonable number of Xephyr instances (your
449 running X11 will not be touched), run:
450   ./complete-run.pl
451
452 To run only a specific test (useful when developing a new feature), run:
453   ./complete-run t/100-fullscreen.t
454
455 =head1 OPTIONS
456
457 =over 8
458
459 =item B<--display>
460
461 Specifies which X11 display should be used. Can be specified multiple times and
462 will parallelize the tests:
463
464   # Run tests on the second X server
465   ./complete-run.pl -d :1
466
467   # Run four tests in parallel on some Xephyr servers
468   ./complete-run.pl -d :1,:2,:3,:4
469
470 Note that it is not necessary to specify this anymore. If omitted,
471 complete-run.pl will start (num_cores * 2) Xephyr instances.
472
473 =item B<--valgrind>
474
475 Runs i3 under valgrind to find memory problems. The output will be available in
476 C<latest/valgrind-for-$test.log>.
477
478 =item B<--strace>
479
480 Runs i3 under strace to trace system calls. The output will be available in
481 C<latest/strace-for-$test.log>.
482
483 =item B<--xtrace>
484
485 Runs i3 under xtrace to trace X11 requests/replies. The output will be
486 available in C<latest/xtrace-for-$test.log>.
487
488 =item B<--xvfb>
489
490 =item B<--no-xvfb>
491
492 Enable or disable running tests under Xvfb. Enabled by default.
493
494 =item B<--coverage-testing>
495
496 Generates a test coverage report at C<latest/i3-coverage>. Exits i3 cleanly
497 during tests (instead of kill -9) to make coverage testing work properly.
498
499 =item B<--parallel>
500
501 Number of Xephyr instances to start (if you don't want to start num_cores * 2
502 instances for some reason).
503
504   # Run all tests on a single Xephyr instance
505   ./complete-run.pl -p 1
506
507 =back