]> git.sur5r.net Git - i3/i3/blob - testcases/lib/i3test.pm
testcases: always start i3 through i3test::launch_with_config
[i3/i3] / testcases / lib / i3test.pm
1 package i3test;
2 # vim:ts=4:sw=4:expandtab
3 use strict; use warnings;
4
5 use File::Temp qw(tmpnam tempfile tempdir);
6 use Test::Builder;
7 use X11::XCB::Rect;
8 use X11::XCB::Window;
9 use X11::XCB qw(:all);
10 use AnyEvent::I3;
11 use List::Util qw(first);
12 use Time::HiRes qw(sleep);
13 use Cwd qw(abs_path);
14 use Scalar::Util qw(blessed);
15 use SocketActivation;
16
17 use v5.10;
18
19 use Exporter ();
20 our @EXPORT = qw(
21     get_workspace_names
22     get_unused_workspace
23     fresh_workspace
24     get_ws_content
25     get_ws
26     get_focused
27     open_empty_con
28     open_window
29     open_floating_window
30     get_dock_clients
31     cmd
32     sync_with_i3
33     does_i3_live
34     exit_gracefully
35     workspace_exists
36     focused_ws
37     get_socket_path
38     launch_with_config
39     wait_for_event
40     wait_for_map
41     wait_for_unmap
42     $x
43 );
44
45 my $tester = Test::Builder->new();
46 my $_cached_socket_path = undef;
47 my $_sync_window = undef;
48 my $tmp_socket_path = undef;
49
50 our $x;
51
52 BEGIN {
53     my $window_count = 0;
54     sub counter_window {
55         return $window_count++;
56     }
57 }
58
59 my $i3_pid;
60 my $i3_autostart;
61
62 END {
63
64     # testcases which start i3 manually should always call exit_gracefully
65     # on their own. Let’s see, whether they really did.
66     if (! $i3_autostart) {
67         return unless $i3_pid;
68
69         $tester->ok(undef, 'testcase called exit_gracefully()');
70     }
71
72     # don't trigger SIGCHLD handler
73     local $SIG{CHLD};
74
75     # From perldoc -v '$?':
76     # Inside an "END" subroutine $? contains the value
77     # that is going to be given to "exit()".
78     #
79     # Since waitpid sets $?, we need to localize it,
80     # otherwise TAP would be misinterpreted our return status
81     local $?;
82
83     # When measuring code coverage, try to exit i3 cleanly (otherwise, .gcda
84     # files are not written)
85     if ($ENV{COVERAGE} || $ENV{VALGRIND}) {
86         exit_gracefully($i3_pid, "/tmp/nested-$ENV{DISPLAY}");
87
88     } else {
89         kill(9, $i3_pid)
90             or $tester->BAIL_OUT("could not kill i3");
91
92         waitpid $i3_pid, 0;
93     }
94 }
95
96 sub import {
97     my ($class, %args) = @_;
98     my $pkg = caller;
99
100     $i3_autostart = delete($args{i3_autostart}) // 1;
101
102     my $cv = launch_with_config('-default', dont_block => 1)
103         if $i3_autostart;
104
105     my $test_more_args = '';
106     $test_more_args = join(' ', 'qw(', %args, ')') if keys %args;
107     local $@;
108     eval << "__";
109 package $pkg;
110 use Test::More $test_more_args;
111 use Data::Dumper;
112 use AnyEvent::I3;
113 use Time::HiRes qw(sleep);
114 __
115     $tester->BAIL_OUT("$@") if $@;
116     feature->import(":5.10");
117     strict->import;
118     warnings->import;
119
120     $x ||= i3test::X11->new;
121     $cv->recv if $i3_autostart;
122
123     @_ = ($class);
124     goto \&Exporter::import;
125 }
126
127 #
128 # Waits for the next event and calls the given callback for every event to
129 # determine if this is the event we are waiting for.
130 #
131 # Can be used to wait until a window is mapped, until a ClientMessage is
132 # received, etc.
133 #
134 # wait_for_event $x, 0.25, sub { $_[0]->{response_type} == MAP_NOTIFY };
135 #
136 sub wait_for_event {
137     my ($timeout, $cb) = @_;
138
139     my $cv = AE::cv;
140
141     $x->flush;
142
143     # unfortunately, there is no constant for this
144     my $ae_read = 0;
145
146     my $guard = AE::io $x->get_file_descriptor, $ae_read, sub {
147         while (defined(my $event = $x->poll_for_event)) {
148             if ($cb->($event)) {
149                 $cv->send(1);
150                 last;
151             }
152         }
153     };
154
155     # Trigger timeout after $timeout seconds (can be fractional)
156     my $t = AE::timer $timeout, 0, sub { warn "timeout ($timeout secs)"; $cv->send(0) };
157
158     my $result = $cv->recv;
159     undef $t;
160     undef $guard;
161     return $result;
162 }
163
164 # thin wrapper around wait_for_event which waits for MAP_NOTIFY
165 # make sure to include 'structure_notify' in the window’s event_mask attribute
166 sub wait_for_map {
167     my ($win) = @_;
168     my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
169     wait_for_event 2, sub {
170         $_[0]->{response_type} == MAP_NOTIFY and $_[0]->{window} == $id
171     };
172 }
173
174 # Wrapper around wait_for_event which waits for UNMAP_NOTIFY. Also calls
175 # sync_with_i3 to make sure i3 also picked up and processed the UnmapNotify
176 # event.
177 sub wait_for_unmap {
178     my ($win) = @_;
179     # my $id = (blessed($win) && $win->isa('X11::XCB::Window')) ? $win->id : $win;
180     wait_for_event 2, sub {
181         $_[0]->{response_type} == UNMAP_NOTIFY # and $_[0]->{window} == $id
182     };
183     sync_with_i3();
184 }
185
186 #
187 # Opens a new window (see X11::XCB::Window), maps it, waits until it got mapped
188 # and synchronizes with i3.
189 #
190 # set dont_map to a true value to avoid mapping
191 #
192 # if you want to change aspects of your window before it would be mapped,
193 # set before_map to a coderef. $window gets passed as $_ and as first argument.
194 #
195 # if you set both dont_map and before_map, the coderef will be called nevertheless
196 #
197 #
198 # default values:
199 #     class => WINDOW_CLASS_INPUT_OUTPUT
200 #     rect => [ 0, 0, 30, 30 ]
201 #     background_color => '#c0c0c0'
202 #     event_mask => [ 'structure_notify' ]
203 #     name => 'Window <n>'
204 #
205 sub open_window {
206     my %args = @_ == 1 ? %{$_[0]} : @_;
207
208     my $dont_map = delete $args{dont_map};
209     my $before_map = delete $args{before_map};
210
211     $args{class} //= WINDOW_CLASS_INPUT_OUTPUT;
212     $args{rect} //= [ 0, 0, 30, 30 ];
213     $args{background_color} //= '#c0c0c0';
214     $args{event_mask} //= [ 'structure_notify' ];
215     $args{name} //= 'Window ' . counter_window();
216
217     my $window = $x->root->create_child(%args);
218
219     if ($before_map) {
220         # TODO: investigate why _create is not needed
221         $window->_create;
222         $before_map->($window) for $window;
223     }
224
225     return $window if $dont_map;
226
227     $window->map;
228     wait_for_map($window);
229     return $window;
230 }
231
232 # Thin wrapper around open_window which sets window_type to
233 # _NET_WM_WINDOW_TYPE_UTILITY to make the window floating.
234 sub open_floating_window {
235     my %args = @_ == 1 ? %{$_[0]} : @_;
236
237     $args{window_type} = $x->atom(name => '_NET_WM_WINDOW_TYPE_UTILITY');
238
239     return open_window(\%args);
240 }
241
242 sub open_empty_con {
243     my ($i3) = @_;
244
245     my $reply = $i3->command('open')->recv;
246     return $reply->{id};
247 }
248
249 sub get_workspace_names {
250     my $i3 = i3(get_socket_path());
251     my $tree = $i3->get_tree->recv;
252     my @outputs = @{$tree->{nodes}};
253     my @cons;
254     for my $output (@outputs) {
255         # get the first CT_CON of each output
256         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
257         @cons = (@cons, @{$content->{nodes}});
258     }
259     [ map { $_->{name} } @cons ]
260 }
261
262 sub get_unused_workspace {
263     my @names = get_workspace_names();
264     my $tmp;
265     do { $tmp = tmpnam() } while ($tmp ~~ @names);
266     $tmp
267 }
268
269 sub fresh_workspace {
270     my $unused = get_unused_workspace;
271     cmd("workspace $unused");
272     $unused
273 }
274
275 sub get_ws {
276     my ($name) = @_;
277     my $i3 = i3(get_socket_path());
278     my $tree = $i3->get_tree->recv;
279
280     my @outputs = @{$tree->{nodes}};
281     my @workspaces;
282     for my $output (@outputs) {
283         # get the first CT_CON of each output
284         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
285         @workspaces = (@workspaces, @{$content->{nodes}});
286     }
287
288     # as there can only be one workspace with this name, we can safely
289     # return the first entry
290     return first { $_->{name} eq $name } @workspaces;
291 }
292
293 #
294 # returns the content (== tree, starting from the node of a workspace)
295 # of a workspace. If called in array context, also includes the focus
296 # stack of the workspace
297 #
298 sub get_ws_content {
299     my ($name) = @_;
300     my $con = get_ws($name);
301     return wantarray ? ($con->{nodes}, $con->{focus}) : $con->{nodes};
302 }
303
304 sub get_focused {
305     my ($ws) = @_;
306     my $con = get_ws($ws);
307
308     my @focused = @{$con->{focus}};
309     my $lf;
310     while (@focused > 0) {
311         $lf = $focused[0];
312         last unless defined($con->{focus});
313         @focused = @{$con->{focus}};
314         my @cons = grep { $_->{id} == $lf } (@{$con->{nodes}}, @{$con->{'floating_nodes'}});
315         $con = $cons[0];
316     }
317
318     return $lf;
319 }
320
321 sub get_dock_clients {
322     my $which = shift;
323
324     my $tree = i3(get_socket_path())->get_tree->recv;
325     my @outputs = @{$tree->{nodes}};
326     # Children of all dockareas
327     my @docked;
328     for my $output (@outputs) {
329         if (!defined($which)) {
330             @docked = (@docked, map { @{$_->{nodes}} }
331                                 grep { $_->{type} == 5 }
332                                 @{$output->{nodes}});
333         } elsif ($which eq 'top') {
334             my $first = first { $_->{type} == 5 } @{$output->{nodes}};
335             @docked = (@docked, @{$first->{nodes}});
336         } elsif ($which eq 'bottom') {
337             my @matching = grep { $_->{type} == 5 } @{$output->{nodes}};
338             my $last = $matching[-1];
339             @docked = (@docked, @{$last->{nodes}});
340         }
341     }
342     return @docked;
343 }
344
345 sub cmd {
346     i3(get_socket_path())->command(@_)->recv
347 }
348
349 sub workspace_exists {
350     my ($name) = @_;
351     ($name ~~ @{get_workspace_names()})
352 }
353
354 sub focused_ws {
355     my $i3 = i3(get_socket_path());
356     my $tree = $i3->get_tree->recv;
357     my @outputs = @{$tree->{nodes}};
358     my @cons;
359     for my $output (@outputs) {
360         # get the first CT_CON of each output
361         my $content = first { $_->{type} == 2 } @{$output->{nodes}};
362         my $first = first { $_->{fullscreen_mode} == 1 } @{$content->{nodes}};
363         return $first->{name}
364     }
365 }
366
367 #
368 # Sends an I3_SYNC ClientMessage with a random value to the root window.
369 # i3 will reply with the same value, but, due to the order of events it
370 # processes, only after all other events are done.
371 #
372 # This can be used to ensure the results of a cmd 'focus left' are pushed to
373 # X11 and that $x->input_focus returns the correct value afterwards.
374 #
375 # See also docs/testsuite for a long explanation
376 #
377 sub sync_with_i3 {
378     # Since we need a (mapped) window for receiving a ClientMessage, we create
379     # one on the first call of sync_with_i3. It will be re-used in all
380     # subsequent calls.
381     if (!defined($_sync_window)) {
382         $_sync_window = open_window(
383             rect => [ -15, -15, 10, 10 ],
384             override_redirect => 1,
385         );
386     }
387
388     my $root = $x->get_root_window();
389     # Generate a random number to identify this particular ClientMessage.
390     my $myrnd = int(rand(255)) + 1;
391
392     # Generate a ClientMessage, see xcb_client_message_t
393     my $msg = pack "CCSLLLLLLL",
394          CLIENT_MESSAGE, # response_type
395          32,     # format
396          0,      # sequence
397          $root,  # destination window
398          $x->atom(name => 'I3_SYNC')->id,
399
400          $_sync_window->id,    # data[0]: our own window id
401          $myrnd, # data[1]: a random value to identify the request
402          0,
403          0,
404          0;
405
406     # Send it to the root window -- since i3 uses the SubstructureRedirect
407     # event mask, it will get the ClientMessage.
408     $x->send_event(0, $root, EVENT_MASK_SUBSTRUCTURE_REDIRECT, $msg);
409
410     # now wait until the reply is here
411     return wait_for_event 2, sub {
412         my ($event) = @_;
413         # TODO: const
414         return 0 unless $event->{response_type} == 161;
415
416         my ($win, $rnd) = unpack "LL", $event->{data};
417         return ($rnd == $myrnd);
418     };
419 }
420
421 sub does_i3_live {
422     my $tree = i3(get_socket_path())->get_tree->recv;
423     my @nodes = @{$tree->{nodes}};
424     my $ok = (@nodes > 0);
425     $tester->ok($ok, 'i3 still lives');
426     return $ok;
427 }
428
429 # Tries to exit i3 gracefully (with the 'exit' cmd) or kills the PID if that fails
430 sub exit_gracefully {
431     my ($pid, $socketpath) = @_;
432     $socketpath ||= get_socket_path();
433
434     my $exited = 0;
435     eval {
436         say "Exiting i3 cleanly...";
437         i3($socketpath)->command('exit')->recv;
438         $exited = 1;
439     };
440
441     if (!$exited) {
442         kill(9, $pid)
443             or $tester->BAIL_OUT("could not kill i3");
444     }
445
446     if ($socketpath =~ m,^/tmp/i3-test-socket-,) {
447         unlink($socketpath);
448     }
449
450     waitpid $pid, 0;
451     undef $i3_pid;
452 }
453
454 # Gets the socket path from the I3_SOCKET_PATH atom stored on the X11 root window
455 sub get_socket_path {
456     my ($cache) = @_;
457     $cache ||= 1;
458
459     if ($cache && defined($_cached_socket_path)) {
460         return $_cached_socket_path;
461     }
462
463     my $atom = $x->atom(name => 'I3_SOCKET_PATH');
464     my $cookie = $x->get_property(0, $x->get_root_window(), $atom->id, GET_PROPERTY_TYPE_ANY, 0, 256);
465     my $reply = $x->get_property_reply($cookie->{sequence});
466     my $socketpath = $reply->{value};
467     $_cached_socket_path = $socketpath;
468     return $socketpath;
469 }
470
471 #
472 # launches a new i3 process with the given string as configuration file.
473 # useful for tests which test specific config file directives.
474 #
475 # be sure to use !NO_I3_INSTANCE! somewhere in the file to signal
476 # complete-run.pl that it should not create an instance of i3
477 #
478 sub launch_with_config {
479     my ($config, %args) = @_;
480
481     $tmp_socket_path = "/tmp/nested-$ENV{DISPLAY}";
482
483     my ($fh, $tmpfile) = tempfile("i3-cfg-for-$ENV{TESTNAME}-XXXXX", UNLINK => 1);
484
485     if ($config ne '-default') {
486         say $fh $config;
487     } else {
488         open(my $conf_fh, '<', './i3-test.config')
489             or $tester->BAIL_OUT("could not open default config: $!");
490         local $/;
491         say $fh scalar <$conf_fh>;
492     }
493
494     say $fh "ipc-socket $tmp_socket_path"
495         unless $args{dont_add_socket_path};
496
497     close($fh);
498
499     my $cv = AnyEvent->condvar;
500     $i3_pid = activate_i3(
501         unix_socket_path => "$tmp_socket_path-activation",
502         display => $ENV{DISPLAY},
503         configfile => $tmpfile,
504         outdir => $ENV{OUTDIR},
505         testname => $ENV{TESTNAME},
506         valgrind => $ENV{VALGRIND},
507         strace => $ENV{STRACE},
508         cv => $cv,
509     );
510
511     # force update of the cached socket path in lib/i3test
512     # as soon as i3 has started
513     $cv->cb(sub { get_socket_path(0) });
514
515     return $cv if $args{dont_block};
516
517     # blockingly wait until i3 is ready
518     $cv->recv;
519
520     return $i3_pid;
521 }
522
523 package i3test::X11;
524 use parent 'X11::XCB::Connection';
525
526 sub input_focus {
527     my $self = shift;
528     i3test::sync_with_i3();
529
530     return $self->SUPER::input_focus(@_);
531 }
532
533 1