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