/
More.pm
1999 lines (1398 loc) · 51.5 KB
/
More.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package Test::More;
use 5.006;
use strict;
use warnings;
#---- perlcritic exemptions. ----#
# We use a lot of subroutine prototypes
## no critic (Subroutines::ProhibitSubroutinePrototypes)
# Can't use Carp because it might cause C<use_ok()> to accidentally succeed
# even though the module being used forgot to use Carp. Yes, this
# actually happened.
sub _carp {
my( $file, $line ) = ( caller(1) )[ 1, 2 ];
return warn @_, " at $file line $line\n";
}
our $VERSION = '1.302060';
use Test::Builder::Module;
our @ISA = qw(Test::Builder::Module);
our @EXPORT = qw(ok use_ok require_ok
is isnt like unlike is_deeply
cmp_ok
skip todo todo_skip
pass fail
eq_array eq_hash eq_set
$TODO
plan
done_testing
can_ok isa_ok new_ok
diag note explain
subtest
BAIL_OUT
);
=head1 NAME
Test::More - yet another framework for writing test scripts
=head1 SYNOPSIS
use Test::More tests => 23;
# or
use Test::More skip_all => $reason;
# or
use Test::More; # see done_testing()
require_ok( 'Some::Module' );
# Various ways to say "ok"
ok($got eq $expected, $test_name);
is ($got, $expected, $test_name);
isnt($got, $expected, $test_name);
# Rather than print STDERR "# here's what went wrong\n"
diag("here's what went wrong");
like ($got, qr/expected/, $test_name);
unlike($got, qr/expected/, $test_name);
cmp_ok($got, '==', $expected, $test_name);
is_deeply($got_complex_structure, $expected_complex_structure, $test_name);
SKIP: {
skip $why, $how_many unless $have_some_feature;
ok( foo(), $test_name );
is( foo(42), 23, $test_name );
};
TODO: {
local $TODO = $why;
ok( foo(), $test_name );
is( foo(42), 23, $test_name );
};
can_ok($module, @methods);
isa_ok($object, $class);
pass($test_name);
fail($test_name);
BAIL_OUT($why);
# UNIMPLEMENTED!!!
my @status = Test::More::status;
=head1 DESCRIPTION
B<STOP!> If you're just getting started writing tests, have a look at
L<Test::Simple> first. This is a drop in replacement for Test::Simple
which you can switch to once you get the hang of basic testing.
The purpose of this module is to provide a wide range of testing
utilities. Various ways to say "ok" with better diagnostics,
facilities to skip tests, test future features and compare complicated
data structures. While you can do almost anything with a simple
C<ok()> function, it doesn't provide good diagnostic output.
=head2 I love it when a plan comes together
Before anything else, you need a testing plan. This basically declares
how many tests your script is going to run to protect against premature
failure.
The preferred way to do this is to declare a plan when you C<use Test::More>.
use Test::More tests => 23;
There are cases when you will not know beforehand how many tests your
script is going to run. In this case, you can declare your tests at
the end.
use Test::More;
... run your tests ...
done_testing( $number_of_tests_run );
B<NOTE> C<done_testing()> should never be called in an C<END { ... }> block.
Sometimes you really don't know how many tests were run, or it's too
difficult to calculate. In which case you can leave off
$number_of_tests_run.
In some cases, you'll want to completely skip an entire testing script.
use Test::More skip_all => $skip_reason;
Your script will declare a skip with the reason why you skipped and
exit immediately with a zero (success). See L<Test::Harness> for
details.
If you want to control what functions Test::More will export, you
have to use the 'import' option. For example, to import everything
but 'fail', you'd do:
use Test::More tests => 23, import => ['!fail'];
Alternatively, you can use the C<plan()> function. Useful for when you
have to calculate the number of tests.
use Test::More;
plan tests => keys %Stuff * 3;
or for deciding between running the tests at all:
use Test::More;
if( $^O eq 'MacOS' ) {
plan skip_all => 'Test irrelevant on MacOS';
}
else {
plan tests => 42;
}
=cut
sub plan {
my $tb = Test::More->builder;
return $tb->plan(@_);
}
# This implements "use Test::More 'no_diag'" but the behavior is
# deprecated.
sub import_extra {
my $class = shift;
my $list = shift;
my @other = ();
my $idx = 0;
my $import;
while( $idx <= $#{$list} ) {
my $item = $list->[$idx];
if( defined $item and $item eq 'no_diag' ) {
$class->builder->no_diag(1);
}
elsif( defined $item and $item eq 'import' ) {
if ($import) {
push @$import, @{$list->[ ++$idx ]};
}
else {
$import = $list->[ ++$idx ];
push @other, $item, $import;
}
}
else {
push @other, $item;
}
$idx++;
}
@$list = @other;
if ($class eq __PACKAGE__ && (!$import || grep $_ eq '$TODO', @$import)) {
my $to = $class->builder->exported_to;
no strict 'refs';
*{"$to\::TODO"} = \our $TODO;
if ($import) {
@$import = grep $_ ne '$TODO', @$import;
}
else {
push @$list, import => [grep $_ ne '$TODO', @EXPORT];
}
}
return;
}
=over 4
=item B<done_testing>
done_testing();
done_testing($number_of_tests);
If you don't know how many tests you're going to run, you can issue
the plan when you're done running tests.
$number_of_tests is the same as C<plan()>, it's the number of tests you
expected to run. You can omit this, in which case the number of tests
you ran doesn't matter, just the fact that your tests ran to
conclusion.
This is safer than and replaces the "no_plan" plan.
B<Note:> You must never put C<done_testing()> inside an C<END { ... }> block.
The plan is there to ensure your test does not exit before testing has
completed. If you use an END block you completely bypass this protection.
=back
=cut
sub done_testing {
my $tb = Test::More->builder;
$tb->done_testing(@_);
}
=head2 Test names
By convention, each test is assigned a number in order. This is
largely done automatically for you. However, it's often very useful to
assign a name to each test. Which would you rather see:
ok 4
not ok 5
ok 6
or
ok 4 - basic multi-variable
not ok 5 - simple exponential
ok 6 - force == mass * acceleration
The later gives you some idea of what failed. It also makes it easier
to find the test in your script, simply search for "simple
exponential".
All test functions take a name argument. It's optional, but highly
suggested that you use it.
=head2 I'm ok, you're not ok.
The basic purpose of this module is to print out either "ok #" or "not
ok #" depending on if a given test succeeded or failed. Everything
else is just gravy.
All of the following print "ok" or "not ok" depending on if the test
succeeded or failed. They all also return true or false,
respectively.
=over 4
=item B<ok>
ok($got eq $expected, $test_name);
This simply evaluates any expression (C<$got eq $expected> is just a
simple example) and uses that to determine if the test succeeded or
failed. A true expression passes, a false one fails. Very simple.
For example:
ok( $exp{9} == 81, 'simple exponential' );
ok( Film->can('db_Main'), 'set_db()' );
ok( $p->tests == 4, 'saw tests' );
ok( !grep(!defined $_, @items), 'all items defined' );
(Mnemonic: "This is ok.")
$test_name is a very short description of the test that will be printed
out. It makes it very easy to find a test in your script when it fails
and gives others an idea of your intentions. $test_name is optional,
but we B<very> strongly encourage its use.
Should an C<ok()> fail, it will produce some diagnostics:
not ok 18 - sufficient mucus
# Failed test 'sufficient mucus'
# in foo.t at line 42.
This is the same as L<Test::Simple>'s C<ok()> routine.
=cut
sub ok ($;$) {
my( $test, $name ) = @_;
my $tb = Test::More->builder;
return $tb->ok( $test, $name );
}
=item B<is>
=item B<isnt>
is ( $got, $expected, $test_name );
isnt( $got, $expected, $test_name );
Similar to C<ok()>, C<is()> and C<isnt()> compare their two arguments
with C<eq> and C<ne> respectively and use the result of that to
determine if the test succeeded or failed. So these:
# Is the ultimate answer 42?
is( ultimate_answer(), 42, "Meaning of Life" );
# $foo isn't empty
isnt( $foo, '', "Got some foo" );
are similar to these:
ok( ultimate_answer() eq 42, "Meaning of Life" );
ok( $foo ne '', "Got some foo" );
C<undef> will only ever match C<undef>. So you can test a value
against C<undef> like this:
is($not_defined, undef, "undefined as expected");
(Mnemonic: "This is that." "This isn't that.")
So why use these? They produce better diagnostics on failure. C<ok()>
cannot know what you are testing for (beyond the name), but C<is()> and
C<isnt()> know what the test was and why it failed. For example this
test:
my $foo = 'waffle'; my $bar = 'yarblokos';
is( $foo, $bar, 'Is foo the same as bar?' );
Will produce something like this:
not ok 17 - Is foo the same as bar?
# Failed test 'Is foo the same as bar?'
# in foo.t at line 139.
# got: 'waffle'
# expected: 'yarblokos'
So you can figure out what went wrong without rerunning the test.
You are encouraged to use C<is()> and C<isnt()> over C<ok()> where possible,
however do not be tempted to use them to find out if something is
true or false!
# XXX BAD!
is( exists $brooklyn{tree}, 1, 'A tree grows in Brooklyn' );
This does not check if C<exists $brooklyn{tree}> is true, it checks if
it returns 1. Very different. Similar caveats exist for false and 0.
In these cases, use C<ok()>.
ok( exists $brooklyn{tree}, 'A tree grows in Brooklyn' );
A simple call to C<isnt()> usually does not provide a strong test but there
are cases when you cannot say much more about a value than that it is
different from some other value:
new_ok $obj, "Foo";
my $clone = $obj->clone;
isa_ok $obj, "Foo", "Foo->clone";
isnt $obj, $clone, "clone() produces a different object";
For those grammatical pedants out there, there's an C<isn't()>
function which is an alias of C<isnt()>.
=cut
sub is ($$;$) {
my $tb = Test::More->builder;
return $tb->is_eq(@_);
}
sub isnt ($$;$) {
my $tb = Test::More->builder;
return $tb->isnt_eq(@_);
}
*isn't = \&isnt;
# ' to unconfuse syntax higlighters
=item B<like>
like( $got, qr/expected/, $test_name );
Similar to C<ok()>, C<like()> matches $got against the regex C<qr/expected/>.
So this:
like($got, qr/expected/, 'this is like that');
is similar to:
ok( $got =~ m/expected/, 'this is like that');
(Mnemonic "This is like that".)
The second argument is a regular expression. It may be given as a
regex reference (i.e. C<qr//>) or (for better compatibility with older
perls) as a string that looks like a regex (alternative delimiters are
currently not supported):
like( $got, '/expected/', 'this is like that' );
Regex options may be placed on the end (C<'/expected/i'>).
Its advantages over C<ok()> are similar to that of C<is()> and C<isnt()>. Better
diagnostics on failure.
=cut
sub like ($$;$) {
my $tb = Test::More->builder;
return $tb->like(@_);
}
=item B<unlike>
unlike( $got, qr/expected/, $test_name );
Works exactly as C<like()>, only it checks if $got B<does not> match the
given pattern.
=cut
sub unlike ($$;$) {
my $tb = Test::More->builder;
return $tb->unlike(@_);
}
=item B<cmp_ok>
cmp_ok( $got, $op, $expected, $test_name );
Halfway between C<ok()> and C<is()> lies C<cmp_ok()>. This allows you
to compare two arguments using any binary perl operator. The test
passes if the comparison is true and fails otherwise.
# ok( $got eq $expected );
cmp_ok( $got, 'eq', $expected, 'this eq that' );
# ok( $got == $expected );
cmp_ok( $got, '==', $expected, 'this == that' );
# ok( $got && $expected );
cmp_ok( $got, '&&', $expected, 'this && that' );
...etc...
Its advantage over C<ok()> is when the test fails you'll know what $got
and $expected were:
not ok 1
# Failed test in foo.t at line 12.
# '23'
# &&
# undef
It's also useful in those cases where you are comparing numbers and
C<is()>'s use of C<eq> will interfere:
cmp_ok( $big_hairy_number, '==', $another_big_hairy_number );
It's especially useful when comparing greater-than or smaller-than
relation between values:
cmp_ok( $some_value, '<=', $upper_limit );
=cut
sub cmp_ok($$$;$) {
my $tb = Test::More->builder;
return $tb->cmp_ok(@_);
}
=item B<can_ok>
can_ok($module, @methods);
can_ok($object, @methods);
Checks to make sure the $module or $object can do these @methods
(works with functions, too).
can_ok('Foo', qw(this that whatever));
is almost exactly like saying:
ok( Foo->can('this') &&
Foo->can('that') &&
Foo->can('whatever')
);
only without all the typing and with a better interface. Handy for
quickly testing an interface.
No matter how many @methods you check, a single C<can_ok()> call counts
as one test. If you desire otherwise, use:
foreach my $meth (@methods) {
can_ok('Foo', $meth);
}
=cut
sub can_ok ($@) {
my( $proto, @methods ) = @_;
my $class = ref $proto || $proto;
my $tb = Test::More->builder;
unless($class) {
my $ok = $tb->ok( 0, "->can(...)" );
$tb->diag(' can_ok() called with empty class or reference');
return $ok;
}
unless(@methods) {
my $ok = $tb->ok( 0, "$class->can(...)" );
$tb->diag(' can_ok() called with no methods');
return $ok;
}
my @nok = ();
foreach my $method (@methods) {
$tb->_try( sub { $proto->can($method) } ) or push @nok, $method;
}
my $name = (@methods == 1) ? "$class->can('$methods[0]')" :
"$class->can(...)" ;
my $ok = $tb->ok( !@nok, $name );
$tb->diag( map " $class->can('$_') failed\n", @nok );
return $ok;
}
=item B<isa_ok>
isa_ok($object, $class, $object_name);
isa_ok($subclass, $class, $object_name);
isa_ok($ref, $type, $ref_name);
Checks to see if the given C<< $object->isa($class) >>. Also checks to make
sure the object was defined in the first place. Handy for this sort
of thing:
my $obj = Some::Module->new;
isa_ok( $obj, 'Some::Module' );
where you'd otherwise have to write
my $obj = Some::Module->new;
ok( defined $obj && $obj->isa('Some::Module') );
to safeguard against your test script blowing up.
You can also test a class, to make sure that it has the right ancestor:
isa_ok( 'Vole', 'Rodent' );
It works on references, too:
isa_ok( $array_ref, 'ARRAY' );
The diagnostics of this test normally just refer to 'the object'. If
you'd like them to be more specific, you can supply an $object_name
(for example 'Test customer').
=cut
sub isa_ok ($$;$) {
my( $thing, $class, $thing_name ) = @_;
my $tb = Test::More->builder;
my $whatami;
if( !defined $thing ) {
$whatami = 'undef';
}
elsif( ref $thing ) {
$whatami = 'reference';
local($@,$!);
require Scalar::Util;
if( Scalar::Util::blessed($thing) ) {
$whatami = 'object';
}
}
else {
$whatami = 'class';
}
# We can't use UNIVERSAL::isa because we want to honor isa() overrides
my( $rslt, $error ) = $tb->_try( sub { $thing->isa($class) } );
if($error) {
die <<WHOA unless $error =~ /^Can't (locate|call) method "isa"/;
WHOA! I tried to call ->isa on your $whatami and got some weird error.
Here's the error.
$error
WHOA
}
# Special case for isa_ok( [], "ARRAY" ) and like
if( $whatami eq 'reference' ) {
$rslt = UNIVERSAL::isa($thing, $class);
}
my($diag, $name);
if( defined $thing_name ) {
$name = "'$thing_name' isa '$class'";
$diag = defined $thing ? "'$thing_name' isn't a '$class'" : "'$thing_name' isn't defined";
}
elsif( $whatami eq 'object' ) {
my $my_class = ref $thing;
$thing_name = qq[An object of class '$my_class'];
$name = "$thing_name isa '$class'";
$diag = "The object of class '$my_class' isn't a '$class'";
}
elsif( $whatami eq 'reference' ) {
my $type = ref $thing;
$thing_name = qq[A reference of type '$type'];
$name = "$thing_name isa '$class'";
$diag = "The reference of type '$type' isn't a '$class'";
}
elsif( $whatami eq 'undef' ) {
$thing_name = 'undef';
$name = "$thing_name isa '$class'";
$diag = "$thing_name isn't defined";
}
elsif( $whatami eq 'class' ) {
$thing_name = qq[The class (or class-like) '$thing'];
$name = "$thing_name isa '$class'";
$diag = "$thing_name isn't a '$class'";
}
else {
die;
}
my $ok;
if($rslt) {
$ok = $tb->ok( 1, $name );
}
else {
$ok = $tb->ok( 0, $name );
$tb->diag(" $diag\n");
}
return $ok;
}
=item B<new_ok>
my $obj = new_ok( $class );
my $obj = new_ok( $class => \@args );
my $obj = new_ok( $class => \@args, $object_name );
A convenience function which combines creating an object and calling
C<isa_ok()> on that object.
It is basically equivalent to:
my $obj = $class->new(@args);
isa_ok $obj, $class, $object_name;
If @args is not given, an empty list will be used.
This function only works on C<new()> and it assumes C<new()> will return
just a single object which isa C<$class>.
=cut
sub new_ok {
my $tb = Test::More->builder;
$tb->croak("new_ok() must be given at least a class") unless @_;
my( $class, $args, $object_name ) = @_;
$args ||= [];
my $obj;
my( $success, $error ) = $tb->_try( sub { $obj = $class->new(@$args); 1 } );
if($success) {
local $Test::Builder::Level = $Test::Builder::Level + 1;
isa_ok $obj, $class, $object_name;
}
else {
$class = 'undef' if !defined $class;
$tb->ok( 0, "$class->new() died" );
$tb->diag(" Error was: $error");
}
return $obj;
}
=item B<subtest>
subtest $name => \&code, @args;
C<subtest()> runs the &code as its own little test with its own plan and
its own result. The main test counts this as a single test using the
result of the whole subtest to determine if its ok or not ok.
For example...
use Test::More tests => 3;
pass("First test");
subtest 'An example subtest' => sub {
plan tests => 2;
pass("This is a subtest");
pass("So is this");
};
pass("Third test");
This would produce.
1..3
ok 1 - First test
# Subtest: An example subtest
1..2
ok 1 - This is a subtest
ok 2 - So is this
ok 2 - An example subtest
ok 3 - Third test
A subtest may call C<skip_all>. No tests will be run, but the subtest is
considered a skip.
subtest 'skippy' => sub {
plan skip_all => 'cuz I said so';
pass('this test will never be run');
};
Returns true if the subtest passed, false otherwise.
Due to how subtests work, you may omit a plan if you desire. This adds an
implicit C<done_testing()> to the end of your subtest. The following two
subtests are equivalent:
subtest 'subtest with implicit done_testing()', sub {
ok 1, 'subtests with an implicit done testing should work';
ok 1, '... and support more than one test';
ok 1, '... no matter how many tests are run';
};
subtest 'subtest with explicit done_testing()', sub {
ok 1, 'subtests with an explicit done testing should work';
ok 1, '... and support more than one test';
ok 1, '... no matter how many tests are run';
done_testing();
};
Extra arguments given to C<subtest> are passed to the callback. For example:
sub my_subtest {
my $range = shift;
...
}
for my $range (1, 10, 100, 1000) {
subtest "testing range $range", \&my_subtest, $range;
}
=cut
sub subtest {
my $tb = Test::More->builder;
return $tb->subtest(@_);
}
=item B<pass>
=item B<fail>
pass($test_name);
fail($test_name);
Sometimes you just want to say that the tests have passed. Usually
the case is you've got some complicated condition that is difficult to
wedge into an C<ok()>. In this case, you can simply use C<pass()> (to
declare the test ok) or fail (for not ok). They are synonyms for
C<ok(1)> and C<ok(0)>.
Use these very, very, very sparingly.
=cut
sub pass (;$) {
my $tb = Test::More->builder;
return $tb->ok( 1, @_ );
}
sub fail (;$) {
my $tb = Test::More->builder;
return $tb->ok( 0, @_ );
}
=back
=head2 Module tests
Sometimes you want to test if a module, or a list of modules, can
successfully load. For example, you'll often want a first test which
simply loads all the modules in the distribution to make sure they
work before going on to do more complicated testing.
For such purposes we have C<use_ok> and C<require_ok>.
=over 4
=item B<require_ok>
require_ok($module);
require_ok($file);
Tries to C<require> the given $module or $file. If it loads
successfully, the test will pass. Otherwise it fails and displays the
load error.
C<require_ok> will guess whether the input is a module name or a
filename.
No exception will be thrown if the load fails.
# require Some::Module
require_ok "Some::Module";
# require "Some/File.pl";
require_ok "Some/File.pl";
# stop testing if any of your modules will not load
for my $module (@module) {
require_ok $module or BAIL_OUT "Can't load $module";
}
=cut
sub require_ok ($) {
my($module) = shift;
my $tb = Test::More->builder;
my $pack = caller;
# Try to determine if we've been given a module name or file.
# Module names must be barewords, files not.
$module = qq['$module'] unless _is_module_name($module);
my $code = <<REQUIRE;
package $pack;
require $module;
1;
REQUIRE
my( $eval_result, $eval_error ) = _eval($code);
my $ok = $tb->ok( $eval_result, "require $module;" );
unless($ok) {
chomp $eval_error;
$tb->diag(<<DIAGNOSTIC);
Tried to require '$module'.
Error: $eval_error
DIAGNOSTIC
}
return $ok;
}
sub _is_module_name {
my $module = shift;
# Module names start with a letter.
# End with an alphanumeric.
# The rest is an alphanumeric or ::
$module =~ s/\b::\b//g;
return $module =~ /^[a-zA-Z]\w*$/ ? 1 : 0;
}
=item B<use_ok>
BEGIN { use_ok($module); }
BEGIN { use_ok($module, @imports); }
Like C<require_ok>, but it will C<use> the $module in question and
only loads modules, not files.
If you just want to test a module can be loaded, use C<require_ok>.
If you just want to load a module in a test, we recommend simply using
C<use> directly. It will cause the test to stop.
It's recommended that you run C<use_ok()> inside a BEGIN block so its
functions are exported at compile-time and prototypes are properly
honored.
If @imports are given, they are passed through to the use. So this:
BEGIN { use_ok('Some::Module', qw(foo bar)) }
is like doing this:
use Some::Module qw(foo bar);
Version numbers can be checked like so:
# Just like "use Some::Module 1.02"
BEGIN { use_ok('Some::Module', 1.02) }
Don't try to do this:
BEGIN {
use_ok('Some::Module');
...some code that depends on the use...
...happening at compile time...
}
because the notion of "compile-time" is relative. Instead, you want:
BEGIN { use_ok('Some::Module') }
BEGIN { ...some code that depends on the use... }
If you want the equivalent of C<use Foo ()>, use a module but not
import anything, use C<require_ok>.
BEGIN { require_ok "Foo" }
=cut
sub use_ok ($;@) {
my( $module, @imports ) = @_;
@imports = () unless @imports;
my $tb = Test::More->builder;
my( $pack, $filename, $line ) = caller;
$filename =~ y/\n\r/_/; # so it doesn't run off the "#line $line $f" line
my $code;
if( @imports == 1 and $imports[0] =~ /^\d+(?:\.\d+)?$/ ) {
# probably a version check. Perl needs to see the bare number
# for it to work with non-Exporter based modules.
$code = <<USE;
package $pack;
#line $line $filename
use $module $imports[0];
1;
USE
}
else {
$code = <<USE;
package $pack;
#line $line $filename
use $module \@{\$args[0]};
1;