]> git.sur5r.net Git - i3/i3/blob - testcases/complete-run.pl
Ensure that the "border" command uses logical pixels.
[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 # Report logfiles that match “(Leak|Address)Sanitizer:”.
266 my @logs_with_leaks;
267 for my $log (<$outdir/i3-log-for-*>) {
268     if (slurp($log) =~ /(Leak|Address)Sanitizer:/) {
269         push @logs_with_leaks, $log;
270     }
271 }
272 if (scalar @logs_with_leaks > 0) {
273     say "\nThe following test logfiles contain AddressSanitizer or LeakSanitizer reports:";
274     for my $log (sort @logs_with_leaks) {
275         say "\t$log";
276     }
277 }
278
279 exit ($aggregator->failed > 0);
280
281 #
282 # Takes a test from the beginning of @testfiles and runs it.
283 #
284 # The TAP::Parser (which reads the test output) will get called as soon as
285 # there is some activity on the stdout file descriptor of the test process
286 # (using an AnyEvent->io watcher).
287 #
288 # When a test completes and @done contains $num entries, the $cv condvar gets
289 # triggered to finish testing.
290 #
291 sub take_job {
292     my ($worker, $cv, $tests) = @_;
293
294     my $test = shift @$tests
295         or return $cv->end;
296
297     my $display = $worker->{display};
298
299     Log status($display, "$test: starting");
300     $timings{$test} = time();
301     worker_next($worker, $test);
302
303     # create a TAP::Parser with an in-memory fh
304     my $output;
305     my $parser = TAP::Parser->new({
306         source => do { open(my $fh, '<', \$output); $fh },
307     });
308
309     my $ipc = $worker->{ipc};
310
311     my $w;
312     $w = AnyEvent->io(
313         fh => $ipc,
314         poll => 'r',
315         cb => sub {
316             state $tests_completed = 0;
317             state $partial = '';
318
319             sysread($ipc, my $buf, 4096) or die "sysread: $!";
320
321             if ($partial) {
322                 $buf = $partial . $buf;
323                 $partial = '';
324             }
325
326             # make sure we feed TAP::Parser complete lines so it doesn't blow up
327             if (substr($buf, -1, 1) ne "\n") {
328                 my $nl = rindex($buf, "\n");
329                 if ($nl == -1) {
330                     $partial = $buf;
331                     return;
332                 }
333
334                 # strip partial from buffer
335                 $partial = substr($buf, $nl + 1, '');
336             }
337
338             # count lines before stripping eof-marker otherwise we might
339             # end up with for (1 .. 0) { } which would effectivly skip the loop
340             my $lines = $buf =~ tr/\n//;
341             my $t_eof = $buf =~ s/^$TestWorker::EOF$//m;
342
343             $output .= $buf;
344
345             for (1 .. $lines) {
346                 my $result = $parser->next;
347                 next unless defined($result);
348                 if ($result->is_test) {
349                     $tests_completed++;
350                     status($display, "$test: [$tests_completed/??] ");
351                 } elsif ($result->is_bailout) {
352                     Log status($display, "$test: BAILOUT");
353                     status_completed(scalar @done);
354                     say "";
355                     say "test $test bailed out: " . $result->explanation;
356                     exit 1;
357                 }
358             }
359
360             return unless $t_eof;
361
362             Log status($display, "$test: finished");
363             $timings{$test} = time() - $timings{$test};
364             status_completed(scalar @done);
365
366             $aggregator->add($test, $parser);
367             push @done, [ $test, $output ];
368
369             undef $w;
370             take_job($worker, $cv, $tests);
371         }
372     );
373 }
374
375 sub cleanup {
376     my $exitcode = $?;
377     $_->() for our @CLEANUP;
378     exit $exitcode;
379 }
380
381 # must be in a begin block because we C<exit 0> above
382 BEGIN {
383     $SIG{$_} = sub {
384         require Carp; Carp::cluck("Caught SIG$_[0]\n");
385         cleanup();
386     } for qw(INT TERM QUIT KILL PIPE)
387 }
388
389 __END__
390
391 =head1 NAME
392
393 complete-run.pl - Run the i3 testsuite
394
395 =head1 SYNOPSIS
396
397 complete-run.pl [files...]
398
399 =head1 EXAMPLE
400
401 To run the whole testsuite on a reasonable number of Xephyr instances (your
402 running X11 will not be touched), run:
403   ./complete-run.pl
404
405 To run only a specific test (useful when developing a new feature), run:
406   ./complete-run t/100-fullscreen.t
407
408 =head1 OPTIONS
409
410 =over 8
411
412 =item B<--display>
413
414 Specifies which X11 display should be used. Can be specified multiple times and
415 will parallelize the tests:
416
417   # Run tests on the second X server
418   ./complete-run.pl -d :1
419
420   # Run four tests in parallel on some Xephyr servers
421   ./complete-run.pl -d :1,:2,:3,:4
422
423 Note that it is not necessary to specify this anymore. If omitted,
424 complete-run.pl will start (num_cores * 2) Xephyr instances.
425
426 =item B<--valgrind>
427
428 Runs i3 under valgrind to find memory problems. The output will be available in
429 C<latest/valgrind-for-$test.log>.
430
431 =item B<--strace>
432
433 Runs i3 under strace to trace system calls. The output will be available in
434 C<latest/strace-for-$test.log>.
435
436 =item B<--xtrace>
437
438 Runs i3 under xtrace to trace X11 requests/replies. The output will be
439 available in C<latest/xtrace-for-$test.log>.
440
441 =item B<--coverage-testing>
442
443 Generates a test coverage report at C<latest/i3-coverage>. Exits i3 cleanly
444 during tests (instead of kill -9) to make coverage testing work properly.
445
446 =item B<--parallel>
447
448 Number of Xephyr instances to start (if you don't want to start num_cores * 2
449 instances for some reason).
450
451   # Run all tests on a single Xephyr instance
452   ./complete-run.pl -p 1
453
454 =back