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