This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Update to Test::More alpha 064
[perl5.git] / cpan / Test-Simple / lib / Test / Builder / Tester.pm
1 package Test::Builder::Tester;
2
3 use strict;
4 our $VERSION = '1.301001_064';
5 $VERSION = eval $VERSION;    ## no critic (BuiltinFunctions::ProhibitStringyEval)
6
7 use Test::Builder 1.301001;
8 use Symbol;
9 use Test::Stream::Carp qw/croak/;
10
11 =head1 NAME
12
13 Test::Builder::Tester - *DEPRECATED* test testsuites that have been built with
14 Test::Builder
15
16 =head1 DEPRECATED
17
18 B<This module is deprecated.> Please see L<Test::Stream::Tester> for a
19 better alternative that does not involve dealing with TAP/string output.
20
21 =head1 SYNOPSIS
22
23     use Test::Builder::Tester tests => 1;
24     use Test::More;
25
26     test_out("not ok 1 - foo");
27     test_fail(+1);
28     fail("foo");
29     test_test("fail works");
30
31 =head1 DESCRIPTION
32
33 A module that helps you test testing modules that are built with
34 L<Test::Builder>.
35
36 The testing system is designed to be used by performing a three step
37 process for each test you wish to test.  This process starts with using
38 C<test_out> and C<test_err> in advance to declare what the testsuite you
39 are testing will output with L<Test::Builder> to stdout and stderr.
40
41 You then can run the test(s) from your test suite that call
42 L<Test::Builder>.  At this point the output of L<Test::Builder> is
43 safely captured by L<Test::Builder::Tester> rather than being
44 interpreted as real test output.
45
46 The final stage is to call C<test_test> that will simply compare what you
47 predeclared to what L<Test::Builder> actually outputted, and report the
48 results back with a "ok" or "not ok" (with debugging) to the normal
49 output.
50
51 =cut
52
53 ####
54 # set up testing
55 ####
56
57 #my $t = Test::Builder->new;
58
59 ###
60 # make us an exporter
61 ###
62
63 use Test::Stream::Toolset;
64 use Test::Stream::Exporter;
65 default_exports qw/test_out test_err test_fail test_diag test_test line_num/;
66 Test::Stream::Exporter->cleanup;
67
68 sub before_import {
69     my $class = shift;
70     my ($importer, $list) = @_;
71
72     my $meta    = init_tester($importer);
73     my $context = context(1);
74     my $other   = [];
75     my $idx     = 0;
76
77     while ($idx <= $#{$list}) {
78         my $item = $list->[$idx++];
79         next unless $item;
80
81         if (defined $item and $item eq 'no_diag') {
82             Test::Stream->shared->set_no_diag(1);
83         }
84         elsif ($item eq 'tests') {
85             $context->plan($list->[$idx++]);
86         }
87         elsif ($item eq 'skip_all') {
88             $context->plan(0, 'SKIP', $list->[$idx++]);
89         }
90         elsif ($item eq 'no_plan') {
91             $context->plan(0, 'NO PLAN');
92         }
93         elsif ($item eq 'import') {
94             push @$other => @{$list->[$idx++]};
95         }
96     }
97
98     @$list = @$other;
99
100     return;
101 }
102
103
104 sub builder { Test::Builder->new }
105
106 ###
107 # set up file handles
108 ###
109
110 # create some private file handles
111 my $output_handle = gensym;
112 my $error_handle  = gensym;
113
114 # and tie them to this package
115 my $out = tie *$output_handle, "Test::Builder::Tester::Tie", "STDOUT";
116 my $err = tie *$error_handle,  "Test::Builder::Tester::Tie", "STDERR";
117
118 ####
119 # exported functions
120 ####
121
122 # for remembering that we're testing and where we're testing at
123 my $testing = 0;
124 my $testing_num;
125 my $original_is_passing;
126
127 my $original_stream;
128 my $original_state;
129
130 # remembering where the file handles were originally connected
131 my $original_output_handle;
132 my $original_failure_handle;
133 my $original_todo_handle;
134
135 my $original_harness_env;
136
137 # function that starts testing and redirects the filehandles for now
138 sub _start_testing {
139     # even if we're running under Test::Harness pretend we're not
140     # for now.  This needed so Test::Builder doesn't add extra spaces
141     $original_harness_env = $ENV{HARNESS_ACTIVE} || 0;
142     $ENV{HARNESS_ACTIVE} = 0;
143
144     $original_stream = builder->{stream} || Test::Stream->shared;
145     $original_state  = [@{$original_stream->state->[-1]}];
146
147     # remember what the handles were set to
148     $original_output_handle  = builder()->output();
149     $original_failure_handle = builder()->failure_output();
150     $original_todo_handle    = builder()->todo_output();
151
152     # switch out to our own handles
153     builder()->output($output_handle);
154     builder()->failure_output($error_handle);
155     builder()->todo_output($output_handle);
156
157     # clear the expected list
158     $out->reset();
159     $err->reset();
160
161     # remember that we're testing
162     $testing     = 1;
163     $testing_num = builder()->current_test;
164     builder()->current_test(0);
165     $original_is_passing  = builder()->is_passing;
166     builder()->is_passing(1);
167
168     # look, we shouldn't do the ending stuff
169     builder()->no_ending(1);
170 }
171
172 =head2 Functions
173
174 These are the six methods that are exported as default.
175
176 =over 4
177
178 =item test_out
179
180 =item test_err
181
182 Procedures for predeclaring the output that your test suite is
183 expected to produce until C<test_test> is called.  These procedures
184 automatically assume that each line terminates with "\n".  So
185
186    test_out("ok 1","ok 2");
187
188 is the same as
189
190    test_out("ok 1\nok 2");
191
192 which is even the same as
193
194    test_out("ok 1");
195    test_out("ok 2");
196
197 Once C<test_out> or C<test_err> (or C<test_fail> or C<test_diag>) have
198 been called, all further output from L<Test::Builder> will be
199 captured by L<Test::Builder::Tester>.  This means that you will not
200 be able perform further tests to the normal output in the normal way
201 until you call C<test_test> (well, unless you manually meddle with the
202 output filehandles)
203
204 =cut
205
206 sub test_out {
207     my $ctx = context;
208     # do we need to do any setup?
209     _start_testing() unless $testing;
210
211     $out->expect(@_);
212 }
213
214 sub test_err {
215     my $ctx = context;
216     # do we need to do any setup?
217     _start_testing() unless $testing;
218
219     $err->expect(@_);
220 }
221
222 =item test_fail
223
224 Because the standard failure message that L<Test::Builder> produces
225 whenever a test fails will be a common occurrence in your test error
226 output, and because it has changed between Test::Builder versions, rather
227 than forcing you to call C<test_err> with the string all the time like
228 so
229
230     test_err("# Failed test ($0 at line ".line_num(+1).")");
231
232 C<test_fail> exists as a convenience function that can be called
233 instead.  It takes one argument, the offset from the current line that
234 the line that causes the fail is on.
235
236     test_fail(+1);
237
238 This means that the example in the synopsis could be rewritten
239 more simply as:
240
241    test_out("not ok 1 - foo");
242    test_fail(+1);
243    fail("foo");
244    test_test("fail works");
245
246 =cut
247
248 sub test_fail {
249     my $ctx = context;
250     # do we need to do any setup?
251     _start_testing() unless $testing;
252
253     # work out what line we should be on
254     my( $package, $filename, $line ) = caller;
255     $line = $line + ( shift() || 0 );    # prevent warnings
256
257     # expect that on stderr
258     $err->expect("#     Failed test ($filename at line $line)");
259 }
260
261 =item test_diag
262
263 As most of the remaining expected output to the error stream will be
264 created by L<Test::Builder>'s C<diag> function, L<Test::Builder::Tester>
265 provides a convenience function C<test_diag> that you can use instead of
266 C<test_err>.
267
268 The C<test_diag> function prepends comment hashes and spacing to the
269 start and newlines to the end of the expected output passed to it and
270 adds it to the list of expected error output.  So, instead of writing
271
272    test_err("# Couldn't open file");
273
274 you can write
275
276    test_diag("Couldn't open file");
277
278 Remember that L<Test::Builder>'s diag function will not add newlines to
279 the end of output and test_diag will. So to check
280
281    Test::Builder->new->diag("foo\n","bar\n");
282
283 You would do
284
285   test_diag("foo","bar")
286
287 without the newlines.
288
289 =cut
290
291 sub test_diag {
292     my $ctx = context;
293     # do we need to do any setup?
294     _start_testing() unless $testing;
295
296     # expect the same thing, but prepended with "#     "
297     local $_;
298     $err->expect( map { m/\S/ ? "# $_" : "" } @_ );
299 }
300
301 =item test_test
302
303 Actually performs the output check testing the tests, comparing the
304 data (with C<eq>) that we have captured from L<Test::Builder> against
305 what was declared with C<test_out> and C<test_err>.
306
307 This takes name/value pairs that effect how the test is run.
308
309 =over
310
311 =item title (synonym 'name', 'label')
312
313 The name of the test that will be displayed after the C<ok> or C<not
314 ok>.
315
316 =item skip_out
317
318 Setting this to a true value will cause the test to ignore if the
319 output sent by the test to the output stream does not match that
320 declared with C<test_out>.
321
322 =item skip_err
323
324 Setting this to a true value will cause the test to ignore if the
325 output sent by the test to the error stream does not match that
326 declared with C<test_err>.
327
328 =back
329
330 As a convenience, if only one argument is passed then this argument
331 is assumed to be the name of the test (as in the above examples.)
332
333 Once C<test_test> has been run test output will be redirected back to
334 the original filehandles that L<Test::Builder> was connected to
335 (probably STDOUT and STDERR,) meaning any further tests you run
336 will function normally and cause success/errors for L<Test::Harness>.
337
338 =cut
339
340 sub test_test {
341     my $ctx = context;
342     # decode the arguments as described in the pod
343     my $mess;
344     my %args;
345     if( @_ == 1 ) {
346         $mess = shift
347     }
348     else {
349         %args = @_;
350         $mess = $args{name} if exists( $args{name} );
351         $mess = $args{title} if exists( $args{title} );
352         $mess = $args{label} if exists( $args{label} );
353     }
354
355     # er, are we testing?
356     croak "Not testing.  You must declare output with a test function first."
357       unless $testing;
358
359     # okay, reconnect the test suite back to the saved handles
360     builder()->output($original_output_handle);
361     builder()->failure_output($original_failure_handle);
362     builder()->todo_output($original_todo_handle);
363
364     # restore the test no, etc, back to the original point
365     builder()->current_test($testing_num);
366     $testing = 0;
367     builder()->is_passing($original_is_passing);
368
369     # re-enable the original setting of the harness
370     $ENV{HARNESS_ACTIVE} = $original_harness_env;
371
372     $original_stream->state->[-1] = $original_state;
373
374     # check the output we've stashed
375     unless( builder()->ok( ( $args{skip_out} || $out->check ) &&
376                     ( $args{skip_err} || $err->check ), $mess )
377     )
378     {
379         # print out the diagnostic information about why this
380         # test failed
381
382         local $_;
383
384         builder()->diag( map { "$_\n" } $out->complaint )
385           unless $args{skip_out} || $out->check;
386
387         builder()->diag( map { "$_\n" } $err->complaint )
388           unless $args{skip_err} || $err->check;
389     }
390 }
391
392 =item line_num
393
394 A utility function that returns the line number that the function was
395 called on.  You can pass it an offset which will be added to the
396 result.  This is very useful for working out the correct text of
397 diagnostic functions that contain line numbers.
398
399 Essentially this is the same as the C<__LINE__> macro, but the
400 C<line_num(+3)> idiom is arguably nicer.
401
402 =cut
403
404 sub line_num {
405     my( $package, $filename, $line ) = caller;
406     return $line + ( shift() || 0 );    # prevent warnings
407 }
408
409 =back
410
411 In addition to the six exported functions there exists one
412 function that can only be accessed with a fully qualified function
413 call.
414
415 =over 4
416
417 =item color
418
419 When C<test_test> is called and the output that your tests generate
420 does not match that which you declared, C<test_test> will print out
421 debug information showing the two conflicting versions.  As this
422 output itself is debug information it can be confusing which part of
423 the output is from C<test_test> and which was the original output from
424 your original tests.  Also, it may be hard to spot things like
425 extraneous whitespace at the end of lines that may cause your test to
426 fail even though the output looks similar.
427
428 To assist you C<test_test> can colour the background of the debug
429 information to disambiguate the different types of output. The debug
430 output will have its background coloured green and red.  The green
431 part represents the text which is the same between the executed and
432 actual output, the red shows which part differs.
433
434 The C<color> function determines if colouring should occur or not.
435 Passing it a true or false value will enable or disable colouring
436 respectively, and the function called with no argument will return the
437 current setting.
438
439 To enable colouring from the command line, you can use the
440 L<Text::Builder::Tester::Color> module like so:
441
442    perl -Mlib=Text::Builder::Tester::Color test.t
443
444 Or by including the L<Test::Builder::Tester::Color> module directly in
445 the PERL5LIB.
446
447 =cut
448
449 my $color;
450
451 sub color {
452     $color = shift if @_;
453     $color;
454 }
455
456 =back
457
458 =head1 NOTES
459
460 Thanks to Richard Clamp E<lt>richardc@unixbeard.netE<gt> for letting
461 me use his testing system to try this module out on.
462
463 =head1 SEE ALSO
464
465 L<Test::Builder>, L<Test::Builder::Tester::Color>, L<Test::More>.
466
467 =encoding utf8
468
469 =head1 SOURCE
470
471 The source code repository for Test::More can be found at
472 F<http://github.com/Test-More/test-more/>.
473
474 =head1 MAINTAINER
475
476 =over 4
477
478 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
479
480 =back
481
482 =head1 AUTHORS
483
484 The following people have all contributed to the Test-More dist (sorted using
485 VIM's sort function).
486
487 =over 4
488
489 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
490
491 =item Fergal Daly E<lt>fergal@esatclear.ie>E<gt>
492
493 =item Mark Fowler E<lt>mark@twoshortplanks.comE<gt>
494
495 =item Michael G Schwern E<lt>schwern@pobox.comE<gt>
496
497 =item 唐鳳
498
499 =back
500
501 =head1 COPYRIGHT
502
503 There has been a lot of code migration between modules,
504 here are all the original copyrights together:
505
506 =over 4
507
508 =item Test::Stream
509
510 =item Test::Stream::Tester
511
512 Copyright 2014 Chad Granum E<lt>exodist7@gmail.comE<gt>.
513
514 This program is free software; you can redistribute it and/or
515 modify it under the same terms as Perl itself.
516
517 See F<http://www.perl.com/perl/misc/Artistic.html>
518
519 =item Test::Simple
520
521 =item Test::More
522
523 =item Test::Builder
524
525 Originally authored by Michael G Schwern E<lt>schwern@pobox.comE<gt> with much
526 inspiration from Joshua Pritikin's Test module and lots of help from Barrie
527 Slaymaker, Tony Bowden, blackstar.co.uk, chromatic, Fergal Daly and the perl-qa
528 gang.
529
530 Idea by Tony Bowden and Paul Johnson, code by Michael G Schwern
531 E<lt>schwern@pobox.comE<gt>, wardrobe by Calvin Klein.
532
533 Copyright 2001-2008 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
534
535 This program is free software; you can redistribute it and/or
536 modify it under the same terms as Perl itself.
537
538 See F<http://www.perl.com/perl/misc/Artistic.html>
539
540 =item Test::use::ok
541
542 To the extent possible under law, 唐鳳 has waived all copyright and related
543 or neighboring rights to L<Test-use-ok>.
544
545 This work is published from Taiwan.
546
547 L<http://creativecommons.org/publicdomain/zero/1.0>
548
549 =item Test::Tester
550
551 This module is copyright 2005 Fergal Daly <fergal@esatclear.ie>, some parts
552 are based on other people's work.
553
554 Under the same license as Perl itself
555
556 See http://www.perl.com/perl/misc/Artistic.html
557
558 =item Test::Builder::Tester
559
560 Copyright Mark Fowler E<lt>mark@twoshortplanks.comE<gt> 2002, 2004.
561
562 This program is free software; you can redistribute it
563 and/or modify it under the same terms as Perl itself.
564
565 =back
566
567 =cut
568
569 1;
570
571 ####################################################################
572 # Helper class that is used to remember expected and received data
573
574 package Test::Builder::Tester::Tie;
575
576 ##
577 # add line(s) to be expected
578
579 sub expect {
580     my $self = shift;
581
582     my @checks = @_;
583     foreach my $check (@checks) {
584         $check = $self->_account_for_subtest($check);
585         $check = $self->_translate_Failed_check($check);
586         push @{ $self->{wanted} }, ref $check ? $check : "$check\n";
587     }
588 }
589
590 sub _account_for_subtest {
591     my( $self, $check ) = @_;
592
593     my $ctx = Test::Stream::Context::context();
594     my $depth = @{$ctx->stream->subtests};
595     # Since we ship with Test::Builder, calling a private method is safe...ish.
596     return ref($check) ? $check : ($depth ? '    ' x $depth : '') . $check;
597 }
598
599 sub _translate_Failed_check {
600     my( $self, $check ) = @_;
601
602     if( $check =~ /\A(.*)#     (Failed .*test) \((.*?) at line (\d+)\)\Z(?!\n)/ ) {
603         $check = "/\Q$1\E#\\s+\Q$2\E.*?\\n?.*?\Qat $3\E line \Q$4\E.*\\n?/";
604     }
605
606     return $check;
607 }
608
609 ##
610 # return true iff the expected data matches the got data
611
612 sub check {
613     my $self = shift;
614
615     # turn off warnings as these might be undef
616     local $^W = 0;
617
618     my @checks = @{ $self->{wanted} };
619     my $got    = $self->{got};
620     foreach my $check (@checks) {
621         $check = "\Q$check\E" unless( $check =~ s,^/(.*)/$,$1, or ref $check );
622         return 0 unless $got =~ s/^$check//;
623     }
624
625     return length $got == 0;
626 }
627
628 ##
629 # a complaint message about the inputs not matching (to be
630 # used for debugging messages)
631
632 sub complaint {
633     my $self   = shift;
634     my $type   = $self->type;
635     my $got    = $self->got;
636     my $wanted = join '', @{ $self->wanted };
637
638     # are we running in colour mode?
639     if(Test::Builder::Tester::color) {
640         # get color
641         eval { require Term::ANSIColor };
642         unless($@) {
643             # colours
644
645             my $green = Term::ANSIColor::color("black") . Term::ANSIColor::color("on_green");
646             my $red   = Term::ANSIColor::color("black") . Term::ANSIColor::color("on_red");
647             my $reset = Term::ANSIColor::color("reset");
648
649             # work out where the two strings start to differ
650             my $char = 0;
651             $char++ while substr( $got, $char, 1 ) eq substr( $wanted, $char, 1 );
652
653             # get the start string and the two end strings
654             my $start = $green . substr( $wanted, 0, $char );
655             my $gotend    = $red . substr( $got,    $char ) . $reset;
656             my $wantedend = $red . substr( $wanted, $char ) . $reset;
657
658             # make the start turn green on and off
659             $start =~ s/\n/$reset\n$green/g;
660
661             # make the ends turn red on and off
662             $gotend    =~ s/\n/$reset\n$red/g;
663             $wantedend =~ s/\n/$reset\n$red/g;
664
665             # rebuild the strings
666             $got    = $start . $gotend;
667             $wanted = $start . $wantedend;
668         }
669     }
670
671     return "$type is:\n" . "$got\nnot:\n$wanted\nas expected";
672 }
673
674 ##
675 # forget all expected and got data
676
677 sub reset {
678     my $self = shift;
679     %$self = (
680         type   => $self->{type},
681         got    => '',
682         wanted => [],
683     );
684 }
685
686 sub got {
687     my $self = shift;
688     return $self->{got};
689 }
690
691 sub wanted {
692     my $self = shift;
693     return $self->{wanted};
694 }
695
696 sub type {
697     my $self = shift;
698     return $self->{type};
699 }
700
701 ###
702 # tie interface
703 ###
704
705 sub PRINT {
706     my $self = shift;
707     $self->{got} .= join '', @_;
708 }
709
710 sub TIEHANDLE {
711     my( $class, $type ) = @_;
712
713     my $self = bless { type => $type }, $class;
714
715     $self->reset;
716
717     return $self;
718 }
719
720 sub READ     { }
721 sub READLINE { }
722 sub GETC     { }
723 sub FILENO   { }
724
725 1;