Debian Codegraph @

lib/Test/Inter.pm

raw symbols SCIP
1 package Test::Inter;
2 # Copyright (c) 2010-2024 Sullivan Beck. All rights reserved.
3 # This program is free software; you can redistribute it and/or modify it
4 # under the same terms as Perl itself.
5
6 ###############################################################################
7
8 require 5.004;
9
10 use warnings;
11 use strict;
12 use File::Basename;
13 use IO::File;
14 use Cwd 'abs_path';
15
16 our($VERSION);
17 $VERSION='1.13';
18
19 ###############################################################################
20 # BASE METHODS
21 ###############################################################################
22
23 sub version {
24 my($self) = @_;
25
26 return $VERSION;
27 }
28
29 sub new {
30 my($class,@args) = @_;
31 my($name,%opts);
32
33 if (@args % 2) {
34 ($name,%opts) = @args;
35 } else {
36 $name = $0;
37 $name =~ s,^\./,,;
38 %opts = @args;
39 }
40
41 # The basic structure
42
43 my $self = {
44 'name' => $name, # the name of the test script
45 'start' => 1, # the first test to run
46 'end' => 0, # the last test to end
47 'plan' => 0, # the number of tests planned
48 'abort' => 0, # abort on the first failed test
49 'quiet' => 0, # if 1, no output on successes
50 # (this should only be done when
51 # running as an interactive script)
52 'mode' => 'test', # mode to run script in
53 'width' => 80, # width of terminal
54 'features' => {}, # a list of available features
55 'use_lib' => 'on', # whether to run 'use lib' when loading
56 # this module
57
58 'skipall' => '', # the reason for skipping all
59 # remaining tests
60
61 'plandone' => 0, # 1 if a plan is done
62 'testsrun' => 0, # 1 if any tests have been run
63
64 'libdir' => '', # a directory to load modules from
65 'testdir' => '', # the test directory
66 };
67
68 bless $self, $class;
69 $main::TI_NUM = 0;
70
71 # Handle options, environment variables, global variables
72
73 my @opts = qw(start end testnum plan abort quiet mode width skip_all);
74 my %o = map { $_,1 } @opts;
75
76 no strict 'refs';
77 foreach my $opt (@opts) {
78 my $OPT = uc("ti_$opt");
79
80 my $val;
81 if (defined ${ "main::$OPT" }) {
82 $val = ${ "main::$OPT" };
83 } elsif (exists $ENV{$OPT}) {
84 $val = $ENV{$OPT};
85 } elsif (exists $opts{$opt}) {
86 $val = $opts{$opt};
87 } else {
88 next;
89 }
90
91 &{ "Test::Inter::$opt" }($self,$val);
92 }
93
94 # uncoverable branch true
95 if ($$self{'mode'} ne 'test') {
96 print "\nRunning $name...\n"; # uncoverable statement
97 }
98
99 # We assume that the module is distributed in a directory with the correct
100 # hierarchy. This is:
101 # /some/path MODDIR
102 # /t TESTDIR
103 # /lib LIBDIR
104 # We'll find the full path to each.
105
106 my($moddir,$testdir,$libdir);
107
108 # uncoverable branch false
109 # uncoverable branch true count:2
110 # uncoverable branch false count:2
111 # uncoverable branch true count:3
112 # uncoverable branch false count:3
113 if (-f "$0") {
114 $moddir = dirname(dirname(abs_path($0)));
115 } elsif (-d "./t") {
116 $moddir = dirname(abs_path('.')); # uncoverable statement
117 } elsif (-d "../t") {
118 $moddir = dirname(abs_path('..')); # uncoverable statement
119 }
120
121 # uncoverable branch false
122 if (-d "$moddir/t") {
123 $testdir = "$moddir/t";
124 }
125 # uncoverable branch false
126 if (-d "$moddir/lib") {
127 $libdir = "$moddir/lib";
128 }
129
130 $$self{'moddir'} = $moddir;
131 $$self{'testdir'} = $testdir;
132 $$self{'libdir'} = $libdir;
133
134 $self->use_lib();
135
136 return $self;
137 }
138
139 sub use_lib {
140 my($self,$val) = @_;
141 if (defined $val) {
142 $$self{'use_lib'} = $val;
143 return;
144 }
145
146 if ($$self{'use_lib'} eq 'on') {
147 foreach my $dir ($$self{'libdir'},$$self{'testdir'}) {
148 next if (! defined $dir);
149 eval "use lib '$dir'";
150 }
151 }
152 }
153
154 sub testdir {
155 my($self,$req) = @_;
156 if ($req && $req eq 'mod') {
157 return $$self{'moddir'};
158 } elsif ($req && $req eq 'lib') {
159 return $$self{'libdir'};
160 }
161 return $$self{'testdir'};
162 }
163
164 sub start {
165 my($self,$val) = @_;
166 $val = 1 if (! defined($val));
167 $self->_die("start requires an integer value") if ($val !~ /^\d+$/);
168 $$self{'start'} = $val;
169 }
170
171 sub end {
172 my($self,$val) = @_;
173 $val = 0 if (! $val);
174 $self->_die("end requires an integer value") if ($val !~ /^\d+$/);
175 $$self{'end'} = $val;
176 }
177
178 sub testnum {
179 my($self,$val) = @_;
180 if (! defined($val)) {
181 $$self{'start'} = 1;
182 $$self{'end'} = 0;
183 } else {
184 $self->_die("testnum requires an integer value") if ($val !~ /^\d+$/);
185 $$self{'start'} = $$self{'end'} = $val;
186 }
187 }
188
189 sub plan {
190 my($self,$val) = @_;
191
192 if ($$self{'plandone'}) {
193 $self->_die('Plan/done_testing included twice');
194 }
195 $$self{'plandone'} = 1;
196
197 $val = 0 if (! defined($val));
198 $self->_die("plan requires an integer value") if ($val !~ /^\d+$/);
199 $$self{'plan'} = $val;
200
201 if ($val != 0) {
202 $self->_plan($val);
203 }
204 }
205
206 sub done_testing {
207 my($self,$val) = @_;
208
209 if ($$self{'plandone'}) {
210 $self->_die('Plan/done_testing included twice');
211 }
212 $$self{'plandone'} = 1;
213
214 $val = $main::TI_NUM if (! $val);
215 $self->_die("done_testing requires an integer value") if ($val !~ /^\d+$/);
216 $self->_plan($val);
217
218 if ($val != $main::TI_NUM) {
219 $self->_die("Ran $main::TI_NUM tests, expected $val");
220 }
221 }
222
223 sub abort {
224 my($self,$val) = @_;
225 $val = 0 if (! $val);
226 $$self{'abort'} = $val;
227 }
228
229 sub quiet {
230 my($self,$val) = @_;
231 $val = 0 if (! $val);
232 $$self{'quiet'} = $val;
233 }
234
235 sub mode {
236 my($self,$val) = @_;
237 $val = 'test' if (! $val);
238 $$self{'mode'} = $val;
239 }
240
241 sub width {
242 my($self,$val) = @_;
243 $val = 0 if (! $val);
244 $$self{'width'} = $val;
245 }
246
247 sub skip_all {
248 my($self,$reason,@features) = @_;
249
250 if (@features) {
251 my $skip = 0;
252 foreach my $feature (@features) {
253 if (! exists $$self{'features'}{$feature} ||
254 ! $$self{'features'}{$feature}) {
255 $skip = 1;
256 $reason = "Required feature ($feature) missing"
257 if (! $reason);
258 last;
259 }
260 }
261 return if (! $skip);
262 }
263
264 if ($$self{'plandone'} ||
265 $$self{'testsrun'}) {
266 $reason = 'Remaining tests skipped' if (! $reason);
267 $$self{'skipall'} = $reason;
268
269 } else {
270 $reason = 'Test script skipped' if (! $reason);
271 $self->_plan(0,$reason);
272 exit 0;
273 }
274 }
275
276 sub _die {
277 my($self,$message) = @_;
278
279 print "ERROR: $message\n";
280 exit 1;
281 }
282
283 sub feature {
284 my($self,$feature,$val) = @_;
285 $$self{'features'}{$feature} = $val;
286 }
287
288 sub diag {
289 my($self,$message) = @_;
290 return if ($$self{'quiet'} == 2);
291 $self->_diag($message);
292 }
293
294 sub note {
295 my($self,$message) = @_;
296 return if ($$self{'quiet'});
297 $self->_diag($message);
298 }
299
300 ###############################################################################
301 # LOAD METHODS
302 ###############################################################################
303 # The routines were originally from Test::More (though they have been
304 # changed... some to a greater extent than others).
305
306 sub require_ok {
307 my($self,$module,$mode) = @_;
308 $mode = '' if (! $mode);
309 $main::TI_NUM++ unless ($mode eq 'feature');
310
311 my $pack = caller;
312 my @inc = map { "unshift(\@INC,'$_');\n" }
313 ($$self{'libdir'},$$self{'testdir'});
314
315 my($desc,$code);
316
317 if ( $module =~ /^\d+(?:\.\d+)?$/ ) {
318 # A perl version check.
319 $desc = "require perl $module";
320 $code = <<REQUIRE;
321 require $module;
322 1;
323 REQUIRE
324 } else {
325 $module = qq['$module'] unless $self->_is_module_name($module);
326 $desc = "require $module";
327 # So the following do not get picked up by cpantorpm-depreq or other
328 # tools that try to determine dependencies and prereqs
329 my $p = "package";
330 my $r = "require";
331 $code = <<REQUIRE;
332 $p $pack;
333 @inc
334 $r $module;
335 1;
336 REQUIRE
337 }
338
339 $desc .= ' (should not load)' if ($mode eq 'forbid');
340 $desc .= ' (feature)' if ($mode eq 'feature');
341
342 my($eval_result,$eval_error) = $self->_eval($code);
343 chomp($eval_error);
344 my @eval_error = split(/\n/,$eval_error);
345 foreach my $err (@eval_error) {
346 $err =~ s/ \(\@INC contains.*//; # strip out the actual @INC values
347 }
348
349 my $ok = 1;
350 if ($eval_result) {
351 # Able to load the module
352 if ($mode eq 'forbid') {
353 $$self{'skipall'} = 'Loaded a module not supposed to be present';
354 $self->_not_ok($desc);
355 $self->_diag('Test required that module not be loadable')
356 unless ($$self{'quiet'} == 2);
357 $ok = 0;
358 } elsif ($mode eq 'feature') {
359 $self->feature($module,1);
360 if (! $$self{'quiet'}) {
361 $self->_diag($desc);
362 $self->_diag("Feature available: $module");
363 }
364 } else {
365 $self->_ok($desc);
366 }
367
368 } else {
369 # Unable to load the module
370 if ($mode eq 'forbid') {
371 $self->_ok($desc);
372 } elsif ($mode eq 'feature') {
373 $self->feature($module,0);
374 if (! $$self{'quiet'}) {
375 $self->_diag($desc);
376 $self->_diag("Feature unavailable: $module");
377 }
378 } else {
379 $$self{'skipall'} = 'Unable to load a required module';
380 $self->_not_ok($desc);
381 $ok = 0;
382 }
383 }
384
385 return
386 if ( ($ok && $$self{'quiet'}) ||
387 (! $ok && $$self{'quiet'} == 2) );
388
389 foreach my $err (@eval_error) {
390 $self->_diag($err);
391 }
392 }
393
394 sub use_ok {
395 my($self,@args) = @_;
396
397 my $mode = '';
398 if ($args[$#args] eq 'forbid' ||
399 $args[$#args] eq 'feature') {
400 $mode = pop(@args);
401 }
402 $main::TI_NUM++ unless ($mode eq 'feature');
403
404 my $pack = caller;
405
406 my($code,$desc,$module);
407 if ( @args == 1 and $args[0] =~ /^\d+(?:\.\d+)?$/ ) {
408 # A perl version check.
409 $desc = "require perl $args[0]";
410 $module = 'perl';
411 $code = <<USE;
412 use $args[0];
413 1;
414 USE
415
416 } elsif (@args) {
417 $module = shift(@args);
418
419 if (! $self->_is_module_name($module)) {
420 $self->_not_ok("use module: invalid module name: $module");
421 return;
422 }
423
424 my $vers = '';
425 if ( @args and $args[0] =~ /^\d+(?:\.\d+)?$/ ) {
426 $vers = shift(@args);
427 }
428
429 my $imports = (@args ? 'qw(' . join(' ',@args) . ')' : '');
430 $desc = "use $module $vers $imports";
431
432 my @inc = map { "unshift(\@INC,'$_');\n" } ($$self{'libdir'},$$self{'testdir'});
433
434 # So the following do not get picked up by cpantorpm-depreq or other
435 # tools that try to determine dependencies and prereqs
436 my $p = "package";
437 $code = <<USE;
438 $p $pack;
439 @inc
440 use $module $vers $imports;
441 1;
442 USE
443
444 } else {
445 $self->_not_ok('use module: no module specified');
446 return;
447 }
448
449 $desc .= ' (should not load)' if ($mode eq 'forbid');
450 $desc .= ' (feature)' if ($mode eq 'feature');
451
452 my($eval_result,$eval_error) = $self->_eval($code);
453 chomp($eval_error);
454 my @eval_error = split(/\n/,$eval_error);
455 @eval_error = grep(!/^BEGIN failed--compilation aborted/,@eval_error);
456 foreach my $err (@eval_error) {
457 $err =~ s/ \(\@INC contains.*//; # strip out the actual @INC values
458 }
459
460 my $ok = 1;
461 if ($eval_result) {
462 # Able to load the module
463 if ($mode eq 'forbid') {
464 $$self{'skipall'} = 'Loaded a module not supposed to be present';
465 $self->_not_ok($desc);
466 $self->_diag('Test required that module not be usable')
467 unless ($$self{'quiet'} == 2);
468 $ok = 0;
469 } elsif ($mode eq 'feature') {
470 $self->feature($module,1);
471 if (! $$self{'quiet'}) {
472 $self->_diag($desc);
473 $self->_diag("Feature available: $module");
474 }
475 } else {
476 $self->_ok($desc);
477 }
478
479 } else {
480 # Unable to load the module
481 if ($mode eq 'forbid') {
482 $self->_ok($desc);
483 } elsif ($mode eq 'feature') {
484 $self->feature($module,0);
485 if (! $$self{'quiet'}) {
486 $self->_diag($desc);
487 $self->_diag("Feature unavailable: $module");
488 }
489 } else {
490 $$self{'skipall'} = 'Unable to load a required module';
491 $self->_not_ok($desc);
492 $ok = 0;
493 }
494 }
495
496 return
497 if ( ($ok && $$self{'quiet'}) ||
498 (! $ok && $$self{'quiet'} == 2) );
499
500 foreach my $err (@eval_error) {
501 $self->_diag($err);
502 }
503 }
504
505 sub _is_module_name {
506 my($self,$module) = @_;
507
508 # Module names start with a letter.
509 # End with an alphanumeric.
510 # The rest is an alphanumeric or ::
511 $module =~ s/\b::\b//g;
512
513 return $module =~ /^[a-zA-Z]\w*$/ ? 1 : 0;
514 }
515
516 sub _eval {
517 my($self,$code) = @_;
518
519 my( $sigdie, $eval_result, $eval_error );
520 {
521 local( $@, $!, $SIG{__DIE__} ); # isolate eval
522 $eval_result = eval $code;
523 $eval_error = $@;
524 $sigdie = $SIG{__DIE__} || undef;
525 }
526 # make sure that $code got a chance to set $SIG{__DIE__}
527 $SIG{__DIE__} = $sigdie if defined $sigdie;
528
529 return( $eval_result, $eval_error );
530 }
531
532 ###############################################################################
533 # OK/IS/ISNT METHODS
534 ###############################################################################
535
536 sub ok {
537 my($self,@args) = @_;
538 $main::TI_NUM++;
539
540 my($op,@ret) = $self->_ok_result(@args);
541 my($name,@diag);
542 my $ok = 1;
543
544 if ($op eq 'skip') {
545 my $reason = shift(@ret);
546 $self->_skip($reason);
547
548 } elsif ($op eq 'pass') {
549 ($name,@diag) = @ret;
550 $self->_ok($name);
551
552 } else {
553 ($name,@diag) = @ret;
554 $self->_not_ok($name);
555 $ok = 0;
556 }
557
558 return
559 if ( ($ok && $$self{'quiet'}) ||
560 (! $ok && $$self{'quiet'} == 2) );
561
562 foreach my $diag (@diag) {
563 $self->_diag($diag);
564 }
565 }
566
567 sub _ok_result {
568 my($self,@args) = @_;
569
570 # Test if we're skipping this test
571
572 my($skip,$reason) = $self->_skip_test();
573 return ('skip',$reason) if ($skip);
574
575 # No args == always pass
576
577 if (@args == 0) {
578 return ('pass','Empty test');
579 }
580
581 # Get the result
582
583 my($func,$funcargs,$result) = $self->_get_result(\@args);
584
585 # Get name/expected
586
587 my($name,$expected);
588 if (@args == 1) {
589 $name = $args[0];
590 } elsif (@args == 2) {
591 ($expected,$name) = @args;
592 } elsif (@args > 2) {
593 return(0,'','Improperly formed test: too many arguments');
594 }
595
596 # Check the result
597
598 my($pass,@diag) = $self->_cmp_result('ok',$func,$funcargs,$result,$expected);
599 return($pass,$name,@diag);
600 }
601
602 sub is {
603 my($self,@args) = @_;
604 $self->_is("is",@args);
605 }
606
607 sub isnt {
608 my($self,@args) = @_;
609 $self->_is("isnt",@args);
610 }
611
612 sub _is {
613 my($self,$is,@args) = @_;
614 $main::TI_NUM++;
615
616 my($op,@ret) = $self->_is_result($is,@args);
617 my($name,@diag);
618 my $ok = 1;
619
620 if ($op eq 'skip') {
621 my $reason = shift(@ret);
622 $self->_skip($reason);
623
624 } elsif ($op eq 'pass') {
625 ($name,@diag) = @ret;
626 $self->_ok($name);
627
628 } else {
629 ($name,@diag) = @ret;
630 $self->_not_ok($name);
631 $ok = 0;
632 }
633
634 return
635 if ( ($ok && $$self{'quiet'}) ||
636 (! $ok && $$self{'quiet'} == 2) );
637
638 foreach my $diag (@diag) {
639 $self->_diag($diag);
640 }
641 }
642
643 sub _is_result {
644 my($self,$is,@args) = @_;
645
646 # Test if we're skipping this test
647
648 my($skip,$reason) = $self->_skip_test();
649 return ('skip',$reason) if ($skip);
650
651 # Test args
652
653 if (@args < 2) {
654 return ('fail','','Improperly formed test: too few arguments');
655 }
656
657 my($func,$funcargs,$result) = $self->_get_result(\@args);
658
659 my($name,$expected);
660 if (@args == 1) {
661 ($expected) = @args;
662 } elsif (@args == 2) {
663 ($expected,$name) = @args;
664 } else {
665 return(0,'','Improperly formed test: too many arguments');
666 }
667
668 # Check the result
669
670 my($pass,@diag) = $self->_cmp_result($is,$func,$funcargs,$result,$expected);
671 return($pass,$name,@diag);
672 }
673
674 # Returns $func,$args and $results. The first two are returned only if
675 # there is a function.
676 #
677 sub _get_result {
678 my($self,$args) = @_;
679 my($func,@funcargs,@result,$result);
680
681 if (ref($$args[0]) eq 'CODE') {
682 $func = shift(@$args);
683
684 if (ref($$args[0]) eq 'ARRAY') {
685 @funcargs = @{ $$args[0] };
686 shift(@$args);
687 }
688
689 @result = &$func(@funcargs);
690 return ($func,\@funcargs,\@result);
691
692 } elsif (ref($$args[0]) eq 'ARRAY') {
693 @result = @{ $$args[0] };
694 shift(@$args);
695 return ('','',\@result);
696
697 } else {
698 $result = shift(@$args);
699 return ('','',$result);
700 }
701 }
702
703 sub _cmp_result {
704 my($self,$type,$func,$funcargs,$result,$expected) = @_;
705 my $pass = 0;
706 my $identical = 0;
707 my @diag;
708
709 if ($type eq 'ok') {
710 if (ref($result) eq 'ARRAY') {
711 foreach my $ele (@$result) {
712 $pass = 1 if (defined($ele));
713 }
714
715 } elsif (ref($result) eq 'HASH') {
716 foreach my $key (keys %$result) {
717 my $val = $$result{$key};
718 $pass = 1 if (defined($val));
719 }
720
721 } else {
722 $pass = ($result ? 1 : 0);
723 }
724
725 if (! defined($expected)) {
726 # If no expected result passed in, we don't test the results
727 $identical = 1;
728 } else {
729 # Results/expected must be the same structure
730 $identical = $self->_cmp_structure($result,$expected);
731 }
732
733 } else {
734 $identical = $self->_cmp_structure($result,$expected);
735 if ($type eq 'is') {
736 $pass = $identical;
737 } else {
738 $pass = 1 - $identical;
739 }
740 }
741
742 if (! $identical && $type ne 'isnt') {
743 if ($func) {
744 push(@diag,"Arguments: " . $self->_stringify($funcargs));
745 }
746 push(@diag, "Results : " . $self->_stringify($result));
747 push(@diag, "Expected : " . $self->_stringify($expected)) unless ($type eq 'ok' &&
748 ! defined($result));
749 }
750
751 return (($pass ? 'pass' : 'fail'),@diag);
752 }
753
754 # Turn a data structure into a string (poor-man's Data::Dumper)
755 sub _stringify {
756 my($self,$s) = @_;
757
758 my($str) = $self->__stringify($s);
759 my($width) = $$self{'width'};
760 if ($width) {
761 $width -= 21; # The leading string
762 $width = 10 if ($width < 10);
763 $str = substr($str,0,$width) if (length($str)>$width);
764 }
765 return $str;
766 }
767
768 sub __stringify {
769 my($self,$s) = @_;
770
771 if (! defined($s)) {
772 return '__undef__';
773
774 } elsif (ref($s) eq 'ARRAY') {
775 my $str = '[ ';
776 foreach my $val (@$s) {
777 $str .= $self->__stringify($val) . ' ';
778 }
779 $str .= ']';
780 return $str;
781
782 } elsif (ref($s) eq 'HASH') {
783 my $str = '{ ';
784 foreach my $key (sort keys %$s) {
785 my $key = $self->__stringify($key);
786 my $val = $self->__stringify($$s{$key});
787 $str .= "$key=>$val ";
788 }
789 $str .= '}';
790 return $str;
791
792 } elsif (ref($s)) {
793 return '<' . ref($s) . '>';
794
795 } elsif ($s eq '') {
796 return "''";
797
798 } else {
799 if ($s =~ /\s/) {
800 my $q = qr/\'/; # single quote
801 my $qq = qr/\"/; # double quote
802 if ($s !~ $q) {
803 return "'$s'";
804 }
805 if ($s !~ $qq) {
806 return '"' . $s . '"';
807 }
808 return "<$s>";
809
810 } else {
811 return $s;
812 }
813 }
814 }
815
816 sub _cmp_structure {
817 my($self,$s1,$s2) = @_;
818
819 return 1 if (! defined($s1) && ! defined($s2)); # undef = undef
820 return 0 if (! defined($s1) || ! defined($s2)); # undef != def
821 return 0 if (ref($s1) ne ref($s2)); # must be same type
822
823 if (ref($s1) eq 'ARRAY') {
824 return 0 if ($#$s1 != $#$s2); # two lists must be the same length
825 foreach (my $i=0; $i<=$#$s1; $i++) {
826 return 0 unless $self->_cmp_structure($$s1[$i],$$s2[$i]);
827 }
828 return 1;
829
830 } elsif (ref($s1) eq 'HASH') {
831 my @k1 = keys %$s1;
832 my @k2 = keys %$s2;
833 return 0 if ($#k1 != $#k2); # two hashes must be the same length
834 foreach my $key (@k1) {
835 return 0 if (! exists $$s2{$key}); # keys must be the same
836 return 0 unless $self->_cmp_structure($$s1{$key},$$s2{$key});
837 }
838 return 1;
839
840 } elsif (ref($s1)) {
841 # Two references (other than ARRAY and HASH are assumed equal.
842 return 1;
843
844 } else {
845 # Two scalars are compared stringwise
846 return ($s1 eq $s2);
847 }
848 }
849
850 sub _skip_test {
851 my($self) = @_;
852
853 if ($$self{'skipall'}) {
854 return (1,$$self{'skipall'});
855 } elsif ( $main::TI_NUM < $$self{'start'} ||
856 ($$self{'end'} && $main::TI_NUM > $$self{'end'}) ) {
857 return (1,'Test not in list of tests specified to run');
858 }
859 return 0;
860 }
861
862 ###############################################################################
863 # FILE METHOD
864 ###############################################################################
865
866 sub file {
867 my($self,$func,$input,$outputdir,$expected,$name,@args) = @_;
868 $name = "" if (! $name);
869
870 if (! (ref($func) eq 'CODE')) {
871 $self->_die("file method required a coderef");
872 }
873
874 my @funcargs;
875 my $testdir = $$self{'testdir'};
876
877 # Input file
878
879 if ($input) {
880 if (-r $input) {
881 # Nothing
882
883 } elsif (-r "$testdir/$input") {
884 $input = "$testdir/$input";
885
886 } else {
887 $self->_die("Input file not readable: $input");
888 }
889 push(@funcargs,$input);
890 }
891
892 # Output file and directory
893
894 if (! $outputdir) {
895 if (-d $testdir &&
896 -w $testdir) {
897 $outputdir = $testdir;
898 } else {
899 $outputdir = ".";
900 }
901 }
902 if ($outputdir) {
903 if (! -d $outputdir ||
904 ! -w $outputdir) {
905 $self->_die("Output directory not writable: $outputdir");
906 }
907 }
908 my $output = "$outputdir/tmp_test_inter";
909 push(@funcargs,$output);
910
911 # Expected output
912
913 if (! $expected) {
914 $self->_die("Expected output file not specified");
915
916 } elsif (-r $expected) {
917 # Nothing
918
919 } elsif (-r "$testdir/$expected") {
920 $expected = "$testdir/$expected";
921
922 } else {
923 $self->_die("Expected output file not readable: $expected");
924 }
925
926 # Create the temporary output file.
927
928 &$func(@funcargs,@args);
929 if (! -r "$output") {
930 $self->_die("Output file not created");
931 }
932
933 # Test each line
934
935 my $in = new IO::File;
936 $in->open($output);
937 my @out = <$in>;
938 $in->close();
939 chomp(@out);
940
941 $in->open($expected);
942 my @exp = <$in>;
943 $in->close();
944 chomp(@exp);
945 unlink($output) if (! $ENV{'TI_NOCLEAN'});
946
947 while (@out < @exp) {
948 push(@out,'');
949 }
950 while (@exp < @out) {
951 push(@exp,'');
952 }
953
954 for (my $i=0; $i<@out; $i++) {
955 my $line = $i+1;
956 my $n = ($name ? "$name : Line $line" : "Line $line");
957 $self->_is('is',$out[$i],$exp[$i],$n);
958 }
959 }
960
961 ###############################################################################
962 # TESTS METHOD
963 ###############################################################################
964
965 sub tests {
966 my($self,%opts) = @_;
967
968 #
969 # feature => [ FEATURE, FEATURE, ... ]
970 # disable => [ FEATURE, FEATURE, ... ]
971 #
972
973 my $skip = '';
974 if (exists $opts{'feature'}) {
975 foreach my $feature (@{ $opts{'feature'} }) {
976 $skip = "Required feature unavailable: $feature", last
977 if (! exists $$self{'features'}{$feature} ||
978 ! $$self{'features'}{$feature});
979 }
980 }
981 if (exists $opts{'disable'} && ! $skip) {
982 foreach my $feature (@{ $opts{'disable'} }) {
983 $skip = "Disabled due to feature being available: $feature", last
984 if (exists $$self{'features'}{$feature} &&
985 $$self{'features'}{$feature});
986 }
987 }
988
989 #
990 # name => NAME
991 # skip => REASON
992 # todo => 0/1
993 #
994
995 my $name = '';
996 if (exists $opts{'name'}) {
997 $name = $opts{'name'};
998 }
999
1000 if (exists $opts{'skip'}) {
1001 $skip = $opts{'skip'};
1002 }
1003
1004 my $todo = 0;
1005 if (exists $opts{'todo'}) {
1006 $todo = $opts{'todo'};
1007 }
1008
1009 #
1010 # tests => STRING OR LISTREF
1011 # func => CODEREF
1012 # expected => STRING OR LISTREF
1013 #
1014
1015 # tests
1016 if (! exists $opts{'tests'}) {
1017 $self->_die("invalid test format: tests required");
1018 }
1019 my $tests = $opts{'tests'};
1020 my(%tests,$gotexpected);
1021
1022 my($ntest,$nexp);
1023 if (ref($tests) eq 'ARRAY') {
1024 my @results = @$tests;
1025 $ntest = 0;
1026 foreach my $result (@results) {
1027 $ntest++;
1028 $tests{$ntest}{'err'} = 0;
1029 if (ref($result) eq 'ARRAY') {
1030 $tests{$ntest}{'args'} = $result;
1031 } else {
1032 $tests{$ntest}{'args'} = [$result];
1033 }
1034 }
1035 $gotexpected = 0;
1036
1037 } else {
1038 ($ntest,$gotexpected,%tests) = $self->_parse($tests);
1039 $nexp = $ntest if ($gotexpected);
1040 }
1041
1042 # expected
1043 if (exists $opts{'expected'}) {
1044 if ($gotexpected) {
1045 $self->_die("invalid test format: expected results included twice");
1046 }
1047 my $expected = $opts{'expected'};
1048
1049 if (ref($expected) eq 'ARRAY') {
1050 my @exp = @$expected;
1051 $nexp = 0;
1052 foreach my $exp (@exp) {
1053 $nexp++;
1054 if (ref($exp) eq 'ARRAY') {
1055 $tests{$nexp}{'expected'} = $exp;
1056 } else {
1057 $tests{$nexp}{'expected'} = [$exp];
1058 }
1059 }
1060
1061 } else {
1062 my($g,%t);
1063 ($nexp,$g,%t) = $self->_parse($expected);
1064 if ($g) {
1065 $self->_die("invalid test format: expected results contain '=>'");
1066 }
1067 foreach my $t (1..$nexp) {
1068 $tests{$t}{'expected'} = $t{$t}{'args'};
1069 }
1070 }
1071 $gotexpected = 1;
1072 }
1073
1074 if ($gotexpected &&
1075 ($nexp != 1 && $nexp != $ntest)) {
1076 $self->_die("invalid test format: number expected results differs from number of tests");
1077 }
1078
1079 # func
1080 my $func;
1081 if (exists $opts{'func'}) {
1082 $func = $opts{'func'};
1083 if (ref($func) ne 'CODE') {
1084 $self->_die("invalid test format: func must be a code reference");
1085 }
1086 }
1087
1088 #
1089 # Compare results
1090 #
1091
1092 foreach my $t (1..$ntest) {
1093 $main::TI_NUM++;
1094
1095 if ($skip) {
1096 $self->_skip($skip,$name);
1097 next;
1098 }
1099
1100 if ($tests{$t}{'err'}) {
1101 $self->_not_ok($name);
1102 $self->diag($tests{$t}{'err'});
1103 next;
1104 }
1105
1106 my($op,@ret);
1107
1108 # Test results
1109
1110 if ($gotexpected) {
1111 # Do an 'is' test
1112
1113 my @a = ('is');
1114 push(@a,$func) if ($func);
1115 push(@a,$tests{$t}{'args'});
1116 push(@a,($nexp == 1 ? $tests{'1'}{'expected'}
1117 : $tests{$t}{'expected'}));
1118 push(@a,$name);
1119
1120 ($op,@ret) = $self->_is_result(@a);
1121
1122 } else {
1123 # Do an 'ok' test
1124
1125 my $result = $tests{$t}{'args'};
1126 if (@$result == 1) {
1127 $result = $$result[0];
1128 }
1129 ($op,@ret) = $self->_ok_result($result,$name);
1130 }
1131
1132 # Print it out
1133
1134 my($name,@diag);
1135 my $ok = 1;
1136
1137 if ($op eq 'skip') {
1138 my $reason = shift(@ret);
1139 $self->_skip($reason);
1140
1141 } elsif ($op eq 'pass') {
1142 ($name,@diag) = @ret;
1143 $self->_ok($name);
1144
1145 } else {
1146 ($name,@diag) = @ret;
1147 $self->_not_ok($name);
1148 $ok = 0;
1149 }
1150
1151 next
1152 if ( ($ok && $$self{'quiet'}) ||
1153 (! $ok && $$self{'quiet'} == 2) );
1154
1155 foreach my $diag (@diag) {
1156 $self->_diag($diag);
1157 }
1158 }
1159 }
1160
1161 ###############################################################################
1162 # TAP METHODS
1163 ###############################################################################
1164
1165 sub _diag {
1166 my($self,$message) = @_;
1167 print '#' . ' 'x10 . "$message\n";
1168 }
1169
1170 sub _plan {
1171 my($self,$n,$reason) = @_;
1172 $reason = '' if (! $reason);
1173
1174 if ($$self{'mode'} eq 'test') {
1175
1176 # Test mode
1177
1178 if (! $n) {
1179 $reason = '' if (! $reason);
1180 print "1..0 # Skipped $reason\n";
1181 return;
1182 }
1183
1184 print "1..$n\n";
1185
1186 } else {
1187
1188 if (! $n) {
1189 print " All tests skipped: $reason\n";
1190 } else {
1191 print " Epected number of tests: $n\n"
1192 unless ($$self{'quiet'});
1193 }
1194 }
1195 }
1196
1197 sub _ok {
1198 my($self,$name) = @_;
1199
1200 $name = '' if (! $name);
1201 $name =~ s/\#//;
1202
1203 $$self{'testsrun'} = 1;
1204
1205 return if ($$self{'mode'} ne 'test' &&
1206 $$self{'quiet'});
1207
1208 print "ok $main::TI_NUM" . ' 'x(8-length($main::TI_NUM)) . "$name\n";
1209
1210 if ($name =~ /^\d/ && $$self{'quiet'} != 2) {
1211 $self->_diag('It is strongly recommended that the name of a test not');
1212 $self->_diag('begin with a digit so it will not be confused with the');
1213 $self->_diag('test number.');
1214 }
1215 }
1216
1217 sub _not_ok {
1218 my($self,$name) = @_;
1219 $name = '' if (! $name);
1220 $name =~ s/\#//;
1221
1222 $$self{'testsrun'} = 1;
1223
1224 print "not ok $main::TI_NUM" . ' 'x(4-length($main::TI_NUM)) . "$name\n";
1225
1226 if ($$self{'abort'} == 2) {
1227 exit 1;
1228 } elsif ($$self{'abort'}) {
1229 $$self{'skipall'} = 'Tests aborted due to failed test';
1230 }
1231 }
1232
1233 sub _skip {
1234 my($self,$reason,$name) = @_;
1235 $name = '' if (! $name);
1236 $name =~ s/\#//;
1237
1238 $$self{'testsrun'} = 1;
1239
1240 return if ($$self{'mode'} ne 'test' &&
1241 $$self{'quiet'});
1242
1243 print "ok $main::TI_NUM" . ' 'x(8-length($main::TI_NUM)) .
1244 ($name ? "$name " : "") . "# SKIPPED $reason\n";
1245 }
1246
1247 ###############################################################################
1248 # TEST PARSING METHODS
1249 ###############################################################################
1250
1251 {
1252 my $l; # current line number
1253 my $sp_opt = qr/\s*/; # optional whitespace
1254 my $sp = qr/\s+/; # required whitespace
1255 my $lparen = qr/\(/; # opening paren
1256 my $lbrack = qr/\[/; # opening brack
1257 my $lbrace = qr/\{/; # opening brace
1258 my $q = qr/\'/; # single quote
1259 my $qq = qr/\"/; # double quote
1260 my $token = qr/\S+/; # a token of non-whitespace characters
1261 my $min_str = qr/.*?/; # a minimum length string
1262 my $results = qr/=>/; # the string to switch to results
1263
1264 # We'll also need to match delimiters and other special characters that
1265 # signal the end of a token. The default delimiter is just whitespace,
1266 # both other end-of-token regular expressions will include closing
1267 # parens, delimiters, etc.
1268 #
1269 # The end-of-token regexp will return a match for a special character (if
1270 # any) that terminates the token. If a token ends a whitespace or EOL,
1271 # nothing is matched.
1272 #
1273 my $eot = qr/()(?:\s+|$)/;
1274
1275 # Allowed delimiters is anything except () [] {} alphanumeric,
1276 # underscore, and whitespace.
1277 #
1278 my $delim = qr/[^\'\"\(\)\[\]\{\}a-zA-Z0-9_ \t]/;
1279
1280 # This takes a string which may contain a partial or complete
1281 # descritpion of any number of tests, and parses it.
1282 #
1283 # The string is multiline, and tests must be separated from each other
1284 # by one or more blank lines. Lines starting with a pound sign (#)
1285 # are comments.
1286 #
1287 # A test may include arguments (or obtained results), expected results,
1288 # or both.
1289 #
1290 # Returns
1291 # ($n,$gotboth,%tests)
1292 # where
1293 # $n is the number of tests
1294 # $gotboth is 1 if both arguments and expected results are obtained
1295 # $tests{$i} is the i'th test.
1296 #
1297 sub _parse {
1298 my($self,$string) = @_;
1299 my $t = 0;
1300 my $gotboth = -1;
1301 my %tests = ();
1302
1303 # Split on newlines
1304 $string = [ split(/\n/s,$string) ];
1305
1306 $t = 0;
1307 while (@$string) {
1308 my $test = $self->_next_test($string);
1309 last if (! @$test);
1310
1311 # All tests must contain both args/results OR only one of them.
1312 my ($err,$both,$args,$results) = $self->_parse_test($test);
1313 if ($gotboth == -1) {
1314 $gotboth = $both;
1315 } elsif ($gotboth != $both) {
1316 $err = "Malformed test [$l]: expected results for some tests, not others";
1317 }
1318
1319 $t++;
1320 $tests{$t}{'err'} = $err;
1321 $tests{$t}{'args'} = $args;
1322 $tests{$t}{'expected'} = $results if ($gotboth);
1323 }
1324
1325 return ($t,$gotboth,%tests);
1326 }
1327
1328 # Get all lines up to the end of lines or a blank line. Both
1329 # signal the end of a test.
1330 #
1331 sub _next_test {
1332 my($self,$list) = @_;
1333 my @test;
1334 my $started = 0;
1335
1336 while (1) {
1337 last if (! @$list);
1338 my $line = shift(@$list);
1339
1340 $line =~ s/^\s*//;
1341 $line =~ s/\s*$//;
1342
1343 # If it's a blank line, add it to the test. If we've
1344 # already done test lines, then this signals the end
1345 # of the test. Otherwise, this is before the test,
1346 # so keep looking.
1347 if ($line eq '') {
1348 push(@test,$line);
1349 next if (! $started);
1350 last;
1351 }
1352
1353 # Comments are added to the test as a blank line.
1354 if ($line =~ /^#/) {
1355 push(@test,'');
1356 next;
1357 }
1358
1359 push(@test,$line);
1360 $started = 1;
1361 }
1362
1363 return [] if (! $started);
1364 return \@test;
1365 }
1366
1367 # Parse an entire test. Look for arguments, =>, and expected results.
1368 #
1369 sub _parse_test {
1370 my($self,$test) = @_;
1371 my($err,$both,@args,@results);
1372
1373 my $curr = 'args';
1374
1375 while (@$test) {
1376
1377 last if (! $self->_test_line($test));
1378
1379 # Check for '=>'
1380
1381 if ($self->_parse_begin_results($test)) {
1382 if ($curr eq 'args') {
1383 $curr = 'results';
1384 } else {
1385 return ("Malformed test [$l]: '=>' found twice");
1386 }
1387 next;
1388 }
1389
1390 # Get the next item(s) to add.
1391
1392 my($err,$match,@val) = $self->_parse_token($test,$eot);
1393 return ($err) if ($err);
1394
1395 if ($curr eq 'args') {
1396 push(@args,@val);
1397 } else {
1398 push(@results,@val);
1399 }
1400 }
1401
1402 $both = ($curr eq 'results' ? 1 : 0);
1403 return ("",$both,\@args,\@results);
1404 }
1405
1406 # Makes sure that the first line in the test contains
1407 # something. Blank lines are ignored.
1408 #
1409 sub _test_line {
1410 my($self,$test) = @_;
1411
1412 while (@$test &&
1413 (! defined($$test[0]) ||
1414 $$test[0] eq '')) {
1415 shift(@$test);
1416 $l++;
1417 next;
1418 }
1419 return 1 if (@$test);
1420 return 0;
1421 }
1422
1423 # Check for '=>'.
1424 #
1425 # Return 1 if found, 0 otherwise.
1426 #
1427 sub _parse_begin_results {
1428 my($self,$test) = @_;
1429
1430 return 1 if ($$test[0] =~ s/^ $sp_opt $results $eot //x);
1431 return 0;
1432 }
1433
1434 # Gets the next item to add to the current list.
1435 #
1436 # Returns ($err,$match,@val) where $match is the character that
1437 # matched the end of the current element (either a delimiter,
1438 # closing character, or nothing if the element ends on
1439 # whitespace/newline).
1440 #
1441 sub _parse_token {
1442 my($self,$test,$EOT) = @_;
1443
1444 my($err,$found,$match,@val);
1445
1446 {
1447 last if (! $self->_test_line($test));
1448
1449 # Check for quoted
1450
1451 ($err,$found,$match,@val) = $self->_parse_quoted($test,$EOT);
1452 last if ($err);
1453 if ($found) {
1454 # '' remains ''
1455 last;
1456 }
1457
1458 # Check for open
1459
1460 ($err,$found,$match,@val) = $self->_parse_open_close($test,$EOT,$lparen,')');
1461 last if ($err);
1462 if ($found) {
1463 # () is an empty list
1464 if (@val == 1 && $val[0] eq '') {
1465 @val = ();
1466 }
1467 last;
1468 }
1469
1470 ($err,$found,$match,@val) = $self->_parse_open_close($test,$EOT,$lbrack,']');
1471 last if ($err);
1472 if ($found) {
1473 # [] is []
1474 if (@val == 1 && $val[0] eq '') {
1475 @val = ([]);
1476 } else {
1477 @val = ( [@val] );
1478 }
1479 last;
1480 }
1481
1482 ($err,$found,$match,@val) = $self->_parse_open_close($test,$EOT,$lbrace,'}');
1483 last if ($err);
1484 if ($found) {
1485 if (@val == 1 && $val[0] eq '') {
1486 @val = ( {} );
1487 } elsif (@val % 2 == 0) {
1488 # Even number of elements
1489 @val = ( {@val} );
1490 } elsif (! defined $val[$#val] ||
1491 $val[$#val] eq '') {
1492 # Odd number of elements with nothing as the
1493 # last element.
1494 pop(@val);
1495 @val = ( {@val} );
1496 } else {
1497 # Odd number of elements not supported for a hash
1498 $err = "Malformed test [$l]: hash with odd number of elements";
1499 }
1500 last;
1501 }
1502
1503 # Check for some other token
1504
1505 ($err,$found,$match,@val) = $self->_parse_simple_token($test,$EOT);
1506 last if ($err);
1507
1508 last;
1509 }
1510
1511 return ($err) if ($err);
1512 return ("Malformed test: unable to parse") if (! $found);
1513
1514 foreach my $v (@val) {
1515 $v = '' if ($v eq '__blank__');
1516 $v = undef if ($v eq '__undef__');
1517 $v =~ s/__nl__/\n/g if ($v);
1518 }
1519 return (0,$match,@val) if ($found);
1520 return (0,0);
1521 }
1522
1523 ###
1524 ### The next few routines parse parts of the test. Each of them
1525 ### take as arguments:
1526 ###
1527 ### $test : the listref containing the unparsed portion of
1528 ### the test
1529 ### $EOT : the end of a token
1530 ###
1531 ### + other args as needed.
1532 ###
1533 ### They all return:
1534 ###
1535 ### $err : a string containing the error (if any)
1536 ### $found : 1 if something matched
1537 ### $match : the character which terminates the current
1538 ### token signaling the start of the next token
1539 ### (this will either be a delimiter, a closing
1540 ### character, or nothing if the string ended on
1541 ### whitespace or a newline)
1542 ### @val : the value (or values) of the token
1543 ###
1544
1545 # Check for a quoted string
1546 # 'STRING'
1547 # "STRING"
1548 # The string must be on one line, and everything up to the
1549 # closing quote is included (the quotes themselves are
1550 # stripped).
1551 #
1552 sub _parse_quoted {
1553 my($self,$test,$EOT) = @_;
1554
1555 if ($$test[0] =~ s/^ $sp_opt $q ($min_str) $q $EOT//x ||
1556 $$test[0] =~ s/^ $sp_opt $qq ($min_str) $qq $EOT//x) {
1557 return (0,1,$2,$1);
1558
1559 } elsif ($$test[0] =~ /^ $sp_opt $q/x ||
1560 $$test[0] =~ /^ $sp_opt $qq/x) {
1561 return ("Malformed test [$l]: improper quoting");
1562 }
1563 return (0,0);
1564 }
1565
1566 # Parses an open/close section.
1567 #
1568 # ( TOKEN TOKEN ... )
1569 # (, TOKEN, TOKEN, ... )
1570 #
1571 # $open is a regular expression matching the open, $close is the
1572 # actual closing character.
1573 #
1574 # After the closing character must be an $EOT.
1575 #
1576 sub _parse_open_close {
1577 my($self,$test,$EOT,$open,$close) = @_;
1578
1579 # See if there is an open
1580
1581 my($del,$newEOT);
1582 if ($$test[0] =~ s/^ $sp_opt $open ($delim) $sp_opt //x) {
1583 $del = $1;
1584 $newEOT = qr/ $sp_opt ($|\Q$del\E|\Q$close\E) /x;
1585
1586 } elsif ($$test[0] =~ s/^ $sp_opt $open $sp_opt //x) {
1587 $del = '';
1588 $newEOT = qr/ ($sp_opt $|$sp_opt \Q$close\E|$sp) /x;
1589
1590 } else {
1591 return (0,0);
1592 }
1593
1594 # If there was, then we need to read tokens until either:
1595 # the string is all used up => error
1596 # $close is found
1597
1598 my($match,@val);
1599 while (1) {
1600
1601 # Get a token. We MUST find something valid even if it is
1602 # an empty list followed by the closing character.
1603 my($e,$m,@v) = $self->_parse_token($test,$newEOT);
1604 return ($e) if ($e);
1605 $m =~ s/^$sp//;
1606
1607 # If we ended on nothing, and $del is something, then we
1608 # ended on a newline with no delimiter. The next line MUST
1609 # start with a delimiter or close character or the test is
1610 # invalid.
1611
1612 if (! $m && $del) {
1613
1614 if (! $self->_test_line($test)) {
1615 return ("Malformed test [$l]: premature end of test");
1616 }
1617
1618 if ($$test[0] =~ s/^ $sp_opt $newEOT //x) {
1619 $m = $1;
1620 } else {
1621 return ("Malformed test [$l]: unexpected token (expected '$close' or '$del')");
1622 }
1623 }
1624
1625 # Figure out what value(s) were returned
1626 if ($m eq $close && ! @v) {
1627 push(@val,'');
1628 } else {
1629 push(@val,@v);
1630 }
1631
1632 last if ($m eq $close);
1633
1634 }
1635
1636 # Now we need to find out what character ends this token:
1637
1638 if ($$test[0] eq '') {
1639 # Ended at EOL
1640 return (0,1,'',@val);
1641 }
1642 if ($$test[0] =~ s/^ $sp_opt $EOT //x) {
1643 return (0,1,$1,@val);
1644 } else {
1645 return ("Malformed test [$l]: unexpected token");
1646 }
1647 }
1648
1649 # Checks for a simple token.
1650 #
1651 sub _parse_simple_token {
1652 my($self,$test,$EOT) = @_;
1653
1654 $$test[0] =~ s/^ $sp_opt (.*?) $EOT//x;
1655 return (0,1,$2,$1);
1656 }
1657 }
1658
1659 1;
1660 # Local Variables:
1661 # mode: cperl
1662 # indent-tabs-mode: nil
1663 # cperl-indent-level: 3
1664 # cperl-continued-statement-offset: 2
1665 # cperl-continued-brace-offset: 0
1666 # cperl-brace-offset: 0
1667 # cperl-brace-imaginary-offset: 0
1668 # cperl-label-offset: 0
1669 # End: