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