Debian Codegraph @

lib/App/Yath/Tester.pm

raw
1 package App::Yath::Tester;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.000179';
6
7 use Test2::API qw/context run_subtest/;
8 use Test2::Tools::Compare qw/is/;
9
10 use Carp qw/croak/;
11 use File::Spec;
12 use File::Temp qw/tempfile tempdir/;
13 use POSIX;
14 use Fcntl qw/SEEK_CUR/;
15 use Time::HiRes qw/sleep/;
16
17 use App::Yath::Util qw/find_yath/;
18 use Test2::Harness::Util qw/clean_path apply_encoding/;
19 use Test2::Harness::Util::IPC qw/run_cmd/;
20 use Test2::Harness::Util::File::JSONL;
21
22 use Importer Importer => 'import';
23 our @EXPORT = qw/yath make_example_dir/;
24
25 my $pdir = tempdir(CLEANUP => 1);
26
27 require App::Yath;
28 my $apppath = App::Yath->app_path;
29
30 sub cover {
31 return unless $ENV{T2_DEVEL_COVER};
32 $ENV{T2_COVER_SELF} = 1;
33 return '-MDevel::Cover=-silent,1,+ignore,^t/,+ignore,^t2/,+ignore,^xt,+ignore,^test.pl';
34 }
35
36 sub yath {
37 my %params = @_;
38
39 local $?;
40
41 my $ctx = context();
42
43 my $cmd = delete $params{cmd} // delete $params{command};
44 my $cli = delete $params{cli} // delete $params{args} // [];
45 my $pre = delete $params{pre} // delete $params{pre_command} // [];
46 my $env = delete $params{env} // {};
47 my $enc = delete $params{encoding};
48 my $prefix = delete $params{prefix};
49
50 my $subtest = delete $params{test} // delete $params{tests} // delete $params{subtest};
51 my $exittest = delete $params{exit};
52
53 my $debug = delete $params{debug} // 0;
54 my $inc = delete $params{inc} // 1;
55 my $capture = delete $params{capture} // 1;
56 my $log = delete $params{log} // 0;
57
58 my $no_app_path = delete $params{no_app_path};
59 my $lib = delete $params{lib} // [];
60
61 if (keys %params) {
62 croak "Unexpected parameters: " . join (', ', sort keys %params);
63 }
64
65 my (@inc, @dev);
66 if ($inc) {
67 my ($pkg, $file) = caller();
68 my $dir = $file;
69 $dir =~ s/\.t2?$//g;
70
71 my $inc = File::Spec->catdir($dir, 'lib');
72 push @dev => "-D$inc" if -d $inc;
73 }
74
75 my ($wh, $cfile);
76 if ($capture) {
77 ($wh, $cfile) = tempfile("yath-$$-XXXXXXXX", TMPDIR => 1, UNLINK => 1, SUFFIX => '.out');
78 $wh->autoflush(1);
79 }
80
81 my (@log, $logfile);
82 if ($log) {
83 my $fh;
84 ($fh, $logfile) = tempfile("yathlog-$$-XXXXXXXX", TMPDIR => 1, UNLINK => 1, SUFFIX => '.jsonl');
85 close($fh);
86 @log = ('-F' => $logfile);
87 print "DEBUG: log file = '$logfile'\n" if $debug;
88 }
89
90 unless ($no_app_path) {
91 push @inc => "-I$apppath" if $cmd =~ m/^(test|start|projects)$/;
92 push @dev => "-D$apppath";
93 }
94
95 my @cover = cover();
96
97 my $yath = find_yath;
98 my @cmd = ($^X, @$lib, @cover, $yath, @$pre, @dev, $cmd ? ($cmd) : (), @inc, @log, @$cli);
99
100 print "DEBUG: Command = " . join(' ' => @cmd) . "\n" if $debug;
101
102 local %ENV = %ENV;
103
104 # App::Yath::Script (2.0) prints a message and sets PERL_HASH_SEED when
105 # it is not already set, which pollutes captured output.
106 $ENV{PERL_HASH_SEED} //= POSIX::strftime('%Y%m%d', localtime);
107
108 $ENV{YATH_PERSISTENCE_DIR} = $pdir;
109 $ENV{YATH_CMD} = $cmd;
110 $ENV{NESTED_YATH} = 1;
111 $ENV{'YATH_SELF_TEST'} = 1;
112 $ENV{$_} = $env->{$_} for keys %$env;
113 my $pid = run_cmd(
114 no_set_pgrp => 1,
115 $capture ? (stderr => $wh, stdout => $wh) : (),
116 command => \@cmd,
117 run_in_parent => [sub { close($wh) }],
118 );
119
120 my (@lines, $exit);
121 if ($capture) {
122 open(my $rh, '<', $cfile) or die "Could not open output file: $!";
123 # Do not apply encoding here — non-blocking reads can split
124 # multi-byte characters, corrupting the :utf8 decode.
125 $rh->blocking(0);
126 my $start = time();
127 my $timeout = $ENV{YATH_TESTER_TIMEOUT} // 120;
128
129 # Everything this run prints is captured, so a test that spends a
130 # couple of minutes in here says nothing at all to whatever harness is
131 # running it, and a harness that sees nothing assumes a hang and kills
132 # the test. Say something now and then instead.
133 my $heartbeat = $ENV{YATH_TESTER_HEARTBEAT} // 10;
134 my $last_beat = $start;
135
136 while (1) {
137 seek($rh, 0, SEEK_CUR); # CLEAR EOF
138 my @new = <$rh>;
139 push @lines => @new;
140 print map { chomp($_); "DEBUG: > $_\n" } @new if $debug > 1;
141
142 waitpid($pid, WNOHANG) or do {
143 if ($timeout && time() - $start > $timeout) {
144 push @lines => "yath tester timeout after ${timeout}s\n";
145 $exit = _reap_stuck_yath($pid);
146 last;
147 }
148
149 if ($heartbeat && time() - $last_beat >= $heartbeat) {
150 $last_beat = time();
151 $ctx->note("Still waiting on yath, " . int($last_beat - $start) . "s so far");
152 }
153
154 sleep 0.02;
155 next;
156 };
157 $exit = $?;
158 last;
159 }
160
161 # Child is done — re-read the complete file with proper encoding.
162 # This avoids partial multi-byte sequences from non-blocking reads.
163 if ($enc) {
164 open(my $fh, '<', $cfile) or die "Could not re-open output file: $!";
165 apply_encoding($fh, $enc);
166 @lines = <$fh>;
167 close($fh);
168 }
169 else {
170 seek($rh, 0, SEEK_CUR); # CLEAR EOF
171 while (my @new = <$rh>) {
172 push @lines => @new;
173 print map { chomp($_); "DEBUG: > $_\n" } @new if $debug > 1;
174 }
175 }
176 }
177 else {
178 print "DEBUG: Waiting for $pid\n" if $debug;
179 waitpid($pid, 0);
180 $exit = $?;
181 }
182
183 print "DEBUG: Exit: $exit\n" if $debug;
184
185 my $out = {
186 exit => $exit,
187 $capture ? (output => join('', @lines)) : (),
188 $log ? (log => Test2::Harness::Util::File::JSONL->new(name => $logfile)) : (),
189 };
190
191 my $name = join(' ', map { length($_) < 30 ? $_ : substr($_, 0, 10) . "[...]" . substr($_, -10) } grep { defined($_) } $prefix, 'yath', @$pre, $cmd ? ($cmd) : (), @$cli);
192 run_subtest(
193 $name,
194 sub {
195 if (defined $exittest) {
196 my $ictx = context(level => 3);
197 is($exit, $exittest, "Exit Value Check");
198 $ictx->release;
199 }
200
201 if ($subtest) {
202 local $_ = $out->{output};
203 local $? = $out->{exit};
204 $subtest->($out);
205 }
206
207 my $ictx = context(level => 3);
208
209 $ictx->diag("Command = " . join(' ' => grep { defined $_ } @cmd) . "\nExit = $exit\n==== Output ====\n$out->{output}\n========")
210 unless $ictx->hub->is_passing;
211
212 $ictx->release;
213 },
214 {buffered => 1},
215 $out,
216 ) if $subtest || defined $exittest;
217
218 $ctx->release;
219
220 return $out;
221 }
222
223 # A yath wedged badly enough to hit the timeout above may also be wedged badly
224 # enough to ignore TERM, and a blocking waitpid on one that does hangs the test
225 # file with no ceiling of its own -- turning a slow suite into one that never
226 # finishes. Escalate instead, and only to this process: the tester deliberately
227 # leaves yath in its own process group, so signalling the group would take the
228 # test process with it.
229 sub _reap_stuck_yath {
230 my ($pid) = @_;
231
232 for my $sig (qw/TERM TERM KILL/) {
233 kill($sig, $pid);
234
235 my $deadline = time() + 5;
236 while (time() < $deadline) {
237 return $? if waitpid($pid, WNOHANG) > 0;
238 sleep 0.05;
239 }
240 }
241
242 # It outlived a KILL, so it is unkillable (stuck in the kernel) and there
243 # is nothing else to try. Block, and let the caller see what it gets.
244 waitpid($pid, 0);
245 return $?;
246 }
247
248 sub _gen_passing_test {
249 my ($dir, $subdir, $file) = @_;
250
251 my $path = File::Spec->catdir($dir, $subdir);
252 my $full = File::Spec->catfile($path, $file);
253
254 mkdir($path) or die "Could not make $subdir subdir: $!"
255 unless -d $path;
256
257 open(my $fh, '>', $full);
258 print $fh "use Test2::Tools::Tiny;\nok(1, 'a passing test');\ndone_testing\n";
259 close($fh);
260
261 return $full;
262 }
263
264 sub make_example_dir {
265 my $dir = tempdir(CLEANUP => 1, TMP => 1);
266
267 _gen_passing_test($dir, 't', 'test.t');
268 _gen_passing_test($dir, 't2', 't2_test.t');
269 _gen_passing_test($dir, 'xt', 'xt_test.t');
270
271 return $dir;
272 }
273
274
275 1;
276
277 __END__
278
279 =pod
280
281 =encoding UTF-8
282
283 =head1 NAME
284
285 App::Yath::Tester - Tools for testing yath
286
287 =head1 DESCRIPTION
288
289 This package provides utilities for running yath from within tests to verify
290 its behavior. This is primarily used for integration testing of yath and for
291 third party components.
292
293 =head1 SYNOPSIS
294
295 use App::Yath::Tester qw/yath/;
296
297 my $result = yath(
298 # Command and arguments
299 command => 'test',
300 args => ['-pMyPlugin', 'path/to/test', ...],
301
302 # Exit code we expect from yath
303 exit => 0,
304
305 # Subtest to verify results
306 test => sub {
307 my $result = shift;
308
309 # Redundant since we have the exit check above
310 is($result->{exit}, 0, "Verify exit");
311
312 is($result->{output}, $expected_output, "Got the expected output from yath");
313 },
314 );
315
316 =head1 EXPORTS
317
318 There are 2 exports from this module.
319
320 =head2 $result = yath(...)
321
322 my $result = yath(
323 # Command and arguments
324 command => 'test',
325 args => ['-pMyPlugin', 'path/to/test', ...],
326
327 # Exit code we expect from yath
328 exit => 0,
329
330 # Subtest to verify results
331 test => sub {
332 my $result = shift;
333
334 # Redundant since we have the exit check above
335 is($result->{exit}, 0, "Verify exit");
336
337 is($result->{output}, $expected_output, "Got the expected output from yath");
338 },
339 );
340
341 =head3 ARGUMENTS
342
343 =over 4
344
345 =item cmd => $command
346
347 =item command => $command
348
349 Either 'cmd' or 'command' can be used. This argument takes a string that should
350 be a command name.
351
352 =item cli => \@ARGS
353
354 =item args => \@ARGS
355
356 Either 'cli' or 'args' can be used. If none are provided an empty arrayref is
357 used. This argument takes an arrayref of arguments to the yath command.
358
359 $ yath [PRE_COMMAND] [COMMAND] [ARGS]
360
361 =item pre => \@ARGS
362
363 =item pre_command => \@ARGS
364
365 Either 'pre' or 'pre_command' can be used. An empty arrayref is used if none
366 are provided. These are arguments provided to yath BEFORE the command on the
367 command line.
368
369 $ yath [PRE_COMMAND] [COMMAND] [ARGS]
370
371 =item env => \%ENV
372
373 Provide custom environment variable values to set before running the yath
374 command.
375
376 =item encoding => $encoding_name
377
378 If you expect your yath command's output to be in a specific encoding you can
379 specify it here to make sure the C<< $result->{output} >> text has been read
380 properly.
381
382 =item test => sub { ... }
383
384 =item tests => sub { ... }
385
386 =item subtest => sub { ... }
387
388 These 3 arguments are all aliases for the same thing, only one should be used.
389 The codeblock will be called with C<$result> as the only argument. The
390 codeblock will be run as a subtest. If you specify the C<'exit'> argument that
391 check will also happen in the same subtest.
392
393 test => sub {
394 my $result = shift;
395
396 ... verify result ...
397 },
398
399 =item exit => $integer
400
401 Verify that the yath command exited with the specified exit code. This check
402 will be run in a subtest. If you specify a custom subtest then this check will
403 appear to come from that subtest.
404
405 =item debug => $integer
406
407 Output debug info in realtime, depending on the $integer value this may include
408 the output from the yath command being run.
409
410 0 - No debugging
411 1 - Output the command and other action being taken by the tool
412 2 - Echo yath output as it happens
413
414 =item inc => $bool
415
416 This defaults to true.
417
418 When true the tool will look for a directory next to your test file with an
419 identical name except that '.t' or '.t2' will be stripped from it. If that
420 directory exists it will be added as a dev-lib to the yath command.
421
422 If your test file is 't/foo/bar.t' then your yath command will look like this:
423
424 $ yath -D=t/foo/bar [PRE-COMMAND] [COMMAND] [ARGS]
425
426 =item capture => $bool
427
428 Defaults to true.
429
430 When true the yath output will be captured and put into
431 C<< $result->{output} >>.
432
433 =item log => $bool
434
435 Defaults to false.
436
437 When true yath will be instructed to produce a log, the log will be accessible
438 via C<< $result->{log} >>. C<< $result->{log} >> will be an instance of
439 L<Test2::Harness::Util::File::JSONL>.
440
441 =item no_app_path => $bool
442
443 Default to false.
444
445 Normally C<< -D=/path/to/lib >> is added to the yath command where
446 C<'/path/to/lib'> is the path the the lib dir L<App::Yath> was loaded from.
447 This normally insures the correct version of yath libraries is loaded.
448
449 When this argument is set to true the path is not added.
450
451 =item lib => [...]
452
453 This poorly named argument allows you to inject command line arguments between
454 C<perl> and C<yath> in the command.
455
456 perl [LIB] path/to/yath [PRE-COMMAND] [COMMAND] [ARGS]
457
458 =back
459
460 =head3 RESULT
461
462 The result hashref may contain the following fields depending on the arguments
463 passed into C<yath()>.
464
465 =over 4
466
467 =item exit => $integer
468
469 Exit value returned from yath.
470
471 =item output => $string
472
473 The output produced by the yath command.
474
475 =item log => $jsonl_object
476
477 An instance of L<Test2::Harness::Util::File::JSONL> opened from the log file
478 produced by the yath command.
479
480 B<Note:> By default no logging is done, you must specify the C<< log => 1 >>
481 argument to enable it.
482
483 =back
484
485 =head2 $path = make_example_dir()
486
487 This will create a temporary directory with 't', 't2', and 'xt' subdirectories
488 each of which will contain a single passing test.
489
490 =head1 SOURCE
491
492 The source code repository for Test2-Harness can be found at
493 F<http://github.com/Test-More/Test2-Harness/>.
494
495 =head1 MAINTAINERS
496
497 =over 4
498
499 =item Chad Granum E<lt>[email protected]<gt>
500
501 =back
502
503 =head1 AUTHORS
504
505 =over 4
506
507 =item Chad Granum E<lt>[email protected]<gt>
508
509 =back
510
511 =head1 COPYRIGHT
512
513 Copyright 2020 Chad Granum E<lt>[email protected]<gt>.
514
515 This program is free software; you can redistribute it and/or
516 modify it under the same terms as Perl itself.
517
518 See F<http://dev.perl.org/licenses/>
519
520 =cut