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