sync blead with Update Archive::Extract 0.34
[p5sagit/p5-mst-13.2.git] / lib / Test / Tutorial.pod
CommitLineData
3c4bf434 1# $Id$
9dc10e63 2=head1 NAME
3
4Test::Tutorial - A tutorial about writing really basic tests
5
6=head1 DESCRIPTION
7
9dc10e63 8
4bd4e70a 9I<AHHHHHHH!!!! NOT TESTING! Anything but testing!
0cd946aa 10Beat me, whip me, send me to Detroit, but don't make
11me write tests!>
12
4bd4e70a 13I<*sob*>
0cd946aa 14
4bd4e70a 15I<Besides, I don't know how to write the damned things.>
9dc10e63 16
9dc10e63 17
18Is this you? Is writing tests right up there with writing
0cd946aa 19documentation and having your fingernails pulled out? Did you open up
20a test and read
21
22 ######## We start with some black magic
23
24and decide that's quite enough for you?
25
26It's ok. That's all gone now. We've done all the black magic for
27you. And here are the tricks...
9dc10e63 28
29
30=head2 Nuts and bolts of testing.
31
32Here's the most basic test program.
33
34 #!/usr/bin/perl -w
35
36 print "1..1\n";
37
38 print 1 + 1 == 2 ? "ok 1\n" : "not ok 1\n";
39
40since 1 + 1 is 2, it prints:
41
42 1..1
43 ok 1
44
45What this says is: C<1..1> "I'm going to run one test." [1] C<ok 1>
46"The first test passed". And that's about all magic there is to
4bd4e70a 47testing. Your basic unit of testing is the I<ok>. For each thing you
48test, an C<ok> is printed. Simple. B<Test::Harness> interprets your test
9dc10e63 49results to determine if you succeeded or failed (more on that later).
50
51Writing all these print statements rapidly gets tedious. Fortunately,
4bd4e70a 52there's B<Test::Simple>. It has one function, C<ok()>.
9dc10e63 53
54 #!/usr/bin/perl -w
55
56 use Test::Simple tests => 1;
57
58 ok( 1 + 1 == 2 );
59
4bd4e70a 60and that does the same thing as the code above. C<ok()> is the backbone
9dc10e63 61of Perl testing, and we'll be using it instead of roll-your-own from
4bd4e70a 62here on. If C<ok()> gets a true value, the test passes. False, it
9dc10e63 63fails.
64
65 #!/usr/bin/perl -w
66
67 use Test::Simple tests => 2;
68 ok( 1 + 1 == 2 );
69 ok( 2 + 2 == 5 );
70
71from that comes
72
73 1..2
74 ok 1
75 not ok 2
76 # Failed test (test.pl at line 5)
77 # Looks like you failed 1 tests of 2.
78
79C<1..2> "I'm going to run two tests." This number is used to ensure
80your test program ran all the way through and didn't die or skip some
81tests. C<ok 1> "The first test passed." C<not ok 2> "The second test
4bd4e70a 82failed". Test::Simple helpfully prints out some extra commentary about
9dc10e63 83your tests.
84
85It's not scary. Come, hold my hand. We're going to give an example
86of testing a module. For our example, we'll be testing a date
4bd4e70a 87library, B<Date::ICal>. It's on CPAN, so download a copy and follow
9dc10e63 88along. [2]
89
90
91=head2 Where to start?
92
93This is the hardest part of testing, where do you start? People often
94get overwhelmed at the apparent enormity of the task of testing a
95whole module. Best place to start is at the beginning. Date::ICal is
96an object-oriented module, and that means you start by making an
4bd4e70a 97object. So we test C<new()>.
9dc10e63 98
99 #!/usr/bin/perl -w
100
101 use Test::Simple tests => 2;
102
103 use Date::ICal;
104
105 my $ical = Date::ICal->new; # create an object
106 ok( defined $ical ); # check that we got something
107 ok( $ical->isa('Date::ICal') ); # and it's the right class
108
109run that and you should get:
110
111 1..2
112 ok 1
113 ok 2
114
115congratulations, you've written your first useful test.
116
117
118=head2 Names
119
120That output isn't terribly descriptive, is it? When you have two
121tests you can figure out which one is #2, but what if you have 102?
122
123Each test can be given a little descriptive name as the second
4bd4e70a 124argument to C<ok()>.
9dc10e63 125
126 use Test::Simple tests => 2;
127
128 ok( defined $ical, 'new() returned something' );
129 ok( $ical->isa('Date::ICal'), " and it's the right class" );
130
131So now you'd see...
132
133 1..2
134 ok 1 - new() returned something
135 ok 2 - and it's the right class
136
137
138=head2 Test the manual
139
140Simplest way to build up a decent testing suite is to just test what
a9153838 141the manual says it does. [3] Let's pull something out of the
142L<Date::ICal/SYNOPSIS> and test that all its bits work.
9dc10e63 143
144 #!/usr/bin/perl -w
145
146 use Test::Simple tests => 8;
147
148 use Date::ICal;
149
150 $ical = Date::ICal->new( year => 1964, month => 10, day => 16,
151 hour => 16, min => 12, sec => 47,
152 tz => '0530' );
153
154 ok( defined $ical, 'new() returned something' );
155 ok( $ical->isa('Date::ICal'), " and it's the right class" );
156 ok( $ical->sec == 47, ' sec()' );
157 ok( $ical->min == 12, ' min()' );
158 ok( $ical->hour == 16, ' hour()' );
159 ok( $ical->day == 17, ' day()' );
160 ok( $ical->month == 10, ' month()' );
161 ok( $ical->year == 1964, ' year()' );
162
163run that and you get:
164
165 1..8
166 ok 1 - new() returned something
167 ok 2 - and it's the right class
168 ok 3 - sec()
169 ok 4 - min()
170 ok 5 - hour()
171 not ok 6 - day()
172 # Failed test (- at line 16)
173 ok 7 - month()
174 ok 8 - year()
175 # Looks like you failed 1 tests of 8.
176
177Whoops, a failure! [4] Test::Simple helpfully lets us know on what line
c2878c71 178the failure occurred, but not much else. We were supposed to get 17,
9dc10e63 179but we didn't. What did we get?? Dunno. We'll have to re-run the
180test in the debugger or throw in some print statements to find out.
181
4bd4e70a 182Instead, we'll switch from B<Test::Simple> to B<Test::More>. B<Test::More>
183does everything B<Test::Simple> does, and more! In fact, Test::More does
9dc10e63 184things I<exactly> the way Test::Simple does. You can literally swap
185Test::Simple out and put Test::More in its place. That's just what
186we're going to do.
187
4bd4e70a 188Test::More does more than Test::Simple. The most important difference
189at this point is it provides more informative ways to say "ok".
190Although you can write almost any test with a generic C<ok()>, it
191can't tell you what went wrong. Instead, we'll use the C<is()>
192function, which lets us declare that something is supposed to be the
193same as something else:
9dc10e63 194
195 #!/usr/bin/perl -w
196
197 use Test::More tests => 8;
198
199 use Date::ICal;
200
201 $ical = Date::ICal->new( year => 1964, month => 10, day => 16,
202 hour => 16, min => 12, sec => 47,
203 tz => '0530' );
204
205 ok( defined $ical, 'new() returned something' );
206 ok( $ical->isa('Date::ICal'), " and it's the right class" );
207 is( $ical->sec, 47, ' sec()' );
208 is( $ical->min, 12, ' min()' );
209 is( $ical->hour, 16, ' hour()' );
210 is( $ical->day, 17, ' day()' );
211 is( $ical->month, 10, ' month()' );
212 is( $ical->year, 1964, ' year()' );
213
4bd4e70a 214"Is C<$ical-E<gt>sec> 47?" "Is C<$ical-E<gt>min> 12?" With C<is()> in place,
9dc10e63 215you get some more information
216
217 1..8
218 ok 1 - new() returned something
219 ok 2 - and it's the right class
220 ok 3 - sec()
221 ok 4 - min()
222 ok 5 - hour()
223 not ok 6 - day()
224 # Failed test (- at line 16)
225 # got: '16'
226 # expected: '17'
227 ok 7 - month()
228 ok 8 - year()
229 # Looks like you failed 1 tests of 8.
230
4bd4e70a 231letting us know that C<$ical-E<gt>day> returned 16, but we expected 17. A
9dc10e63 232quick check shows that the code is working fine, we made a mistake
233when writing up the tests. Just change it to:
234
235 is( $ical->day, 16, ' day()' );
236
237and everything works.
238
4bd4e70a 239So any time you're doing a "this equals that" sort of test, use C<is()>.
9dc10e63 240It even works on arrays. The test is always in scalar context, so you
241can test how many elements are in a list this way. [5]
242
243 is( @foo, 5, 'foo has 5 elements' );
244
245
246=head2 Sometimes the tests are wrong
247
248Which brings us to a very important lesson. Code has bugs. Tests are
249code. Ergo, tests have bugs. A failing test could mean a bug in the
250code, but don't discount the possibility that the test is wrong.
251
252On the flip side, don't be tempted to prematurely declare a test
253incorrect just because you're having trouble finding the bug.
254Invalidating a test isn't something to be taken lightly, and don't use
255it as a cop out to avoid work.
256
257
258=head2 Testing lots of values
259
260We're going to be wanting to test a lot of dates here, trying to trick
261the code with lots of different edge cases. Does it work before 1970?
262After 2038? Before 1904? Do years after 10,000 give it trouble?
263Does it get leap years right? We could keep repeating the code above,
264or we could set up a little try/expect loop.
265
266 use Test::More tests => 32;
267 use Date::ICal;
268
269 my %ICal_Dates = (
270 # An ICal string And the year, month, date
271 # hour, minute and second we expect.
272 '19971024T120000' => # from the docs.
273 [ 1997, 10, 24, 12, 0, 0 ],
274 '20390123T232832' => # after the Unix epoch
275 [ 2039, 1, 23, 23, 28, 32 ],
276 '19671225T000000' => # before the Unix epoch
277 [ 1967, 12, 25, 0, 0, 0 ],
278 '18990505T232323' => # before the MacOS epoch
279 [ 1899, 5, 5, 23, 23, 23 ],
280 );
281
282
283 while( my($ical_str, $expect) = each %ICal_Dates ) {
284 my $ical = Date::ICal->new( ical => $ical_str );
285
286 ok( defined $ical, "new(ical => '$ical_str')" );
287 ok( $ical->isa('Date::ICal'), " and it's the right class" );
288
289 is( $ical->year, $expect->[0], ' year()' );
290 is( $ical->month, $expect->[1], ' month()' );
291 is( $ical->day, $expect->[2], ' day()' );
292 is( $ical->hour, $expect->[3], ' hour()' );
293 is( $ical->min, $expect->[4], ' min()' );
294 is( $ical->sec, $expect->[5], ' sec()' );
295 }
296
297So now we can test bunches of dates by just adding them to
4bd4e70a 298C<%ICal_Dates>. Now that it's less work to test with more dates, you'll
9dc10e63 299be inclined to just throw more in as you think of them.
300Only problem is, every time we add to that we have to keep adjusting
4bd4e70a 301the C<use Test::More tests =E<gt> ##> line. That can rapidly get
60ffb308 302annoying. There's two ways to make this work better.
303
304First, we can calculate the plan dynamically using the C<plan()>
305function.
306
307 use Test::More;
308 use Date::ICal;
309
310 my %ICal_Dates = (
311 ...same as before...
312 );
313
314 # For each key in the hash we're running 8 tests.
315 plan tests => keys %ICal_Dates * 8;
316
317Or to be even more flexible, we use C<no_plan>. This means we're just
318running some tests, don't know how many. [6]
9dc10e63 319
320 use Test::More 'no_plan'; # instead of tests => 32
321
322now we can just add tests and not have to do all sorts of math to
323figure out how many we're running.
324
325
326=head2 Informative names
327
328Take a look at this line here
329
330 ok( defined $ical, "new(ical => '$ical_str')" );
331
332we've added more detail about what we're testing and the ICal string
333itself we're trying out to the name. So you get results like:
334
335 ok 25 - new(ical => '19971024T120000')
336 ok 26 - and it's the right class
337 ok 27 - year()
338 ok 28 - month()
339 ok 29 - day()
340 ok 30 - hour()
341 ok 31 - min()
342 ok 32 - sec()
343
344if something in there fails, you'll know which one it was and that
345will make tracking down the problem easier. So try to put a bit of
346debugging information into the test names.
347
4bd4e70a 348Describe what the tests test, to make debugging a failed test easier
349for you or for the next person who runs your test.
350
9dc10e63 351
352=head2 Skipping tests
353
354Poking around in the existing Date::ICal tests, I found this in
4bd4e70a 355F<t/01sanity.t> [7]
9dc10e63 356
357 #!/usr/bin/perl -w
358
359 use Test::More tests => 7;
360 use Date::ICal;
361
362 # Make sure epoch time is being handled sanely.
363 my $t1 = Date::ICal->new( epoch => 0 );
364 is( $t1->epoch, 0, "Epoch time of 0" );
365
366 # XXX This will only work on unix systems.
367 is( $t1->ical, '19700101Z', " epoch to ical" );
368
369 is( $t1->year, 1970, " year()" );
370 is( $t1->month, 1, " month()" );
371 is( $t1->day, 1, " day()" );
372
373 # like the tests above, but starting with ical instead of epoch
374 my $t2 = Date::ICal->new( ical => '19700101Z' );
375 is( $t2->ical, '19700101Z', "Start of epoch in ICal notation" );
376
377 is( $t2->epoch, 0, " and back to ICal" );
378
379The beginning of the epoch is different on most non-Unix operating
380systems [8]. Even though Perl smooths out the differences for the most
381part, certain ports do it differently. MacPerl is one off the top of
382my head. [9] We I<know> this will never work on MacOS. So rather than
383just putting a comment in the test, we can explicitly say it's never
384going to work and skip the test.
385
386 use Test::More tests => 7;
387 use Date::ICal;
388
389 # Make sure epoch time is being handled sanely.
390 my $t1 = Date::ICal->new( epoch => 0 );
391 is( $t1->epoch, 0, "Epoch time of 0" );
392
393 SKIP: {
394 skip('epoch to ICal not working on MacOS', 6)
395 if $^O eq 'MacOS';
396
397 is( $t1->ical, '19700101Z', " epoch to ical" );
398
399 is( $t1->year, 1970, " year()" );
400 is( $t1->month, 1, " month()" );
401 is( $t1->day, 1, " day()" );
402
403 # like the tests above, but starting with ical instead of epoch
404 my $t2 = Date::ICal->new( ical => '19700101Z' );
405 is( $t2->ical, '19700101Z', "Start of epoch in ICal notation" );
406
407 is( $t2->epoch, 0, " and back to ICal" );
408 }
409
410A little bit of magic happens here. When running on anything but
4bd4e70a 411MacOS, all the tests run normally. But when on MacOS, C<skip()> causes
9dc10e63 412the entire contents of the SKIP block to be jumped over. It's never
413run. Instead, it prints special output that tells Test::Harness that
414the tests have been skipped.
415
416 1..7
417 ok 1 - Epoch time of 0
418 ok 2 # skip epoch to ICal not working on MacOS
419 ok 3 # skip epoch to ICal not working on MacOS
420 ok 4 # skip epoch to ICal not working on MacOS
421 ok 5 # skip epoch to ICal not working on MacOS
422 ok 6 # skip epoch to ICal not working on MacOS
423 ok 7 # skip epoch to ICal not working on MacOS
424
425This means your tests won't fail on MacOS. This means less emails
426from MacPerl users telling you about failing tests that you know will
427never work. You've got to be careful with skip tests. These are for
4bd4e70a 428tests which don't work and I<never will>. It is not for skipping
9dc10e63 429genuine bugs (we'll get to that in a moment).
430
4bd4e70a 431The tests are wholly and completely skipped. [10] This will work.
9dc10e63 432
433 SKIP: {
434 skip("I don't wanna die!");
435
436 die, die, die, die, die;
437 }
438
439
440=head2 Todo tests
441
442Thumbing through the Date::ICal man page, I came across this:
443
444 ical
445
446 $ical_string = $ical->ical;
447
448 Retrieves, or sets, the date on the object, using any
449 valid ICal date/time string.
450
4bd4e70a 451"Retrieves or sets". Hmmm, didn't see a test for using C<ical()> to set
9dc10e63 452the date in the Date::ICal test suite. So I'll write one.
453
454 use Test::More tests => 1;
60ffb308 455 use Date::ICal;
9dc10e63 456
457 my $ical = Date::ICal->new;
458 $ical->ical('20201231Z');
459 is( $ical->ical, '20201231Z', 'Setting via ical()' );
460
461run that and I get
462
463 1..1
464 not ok 1 - Setting via ical()
465 # Failed test (- at line 6)
466 # got: '20010814T233649Z'
467 # expected: '20201231Z'
468 # Looks like you failed 1 tests of 1.
469
470Whoops! Looks like it's unimplemented. Let's assume we don't have
471the time to fix this. [11] Normally, you'd just comment out the test
472and put a note in a todo list somewhere. Instead, we're going to
4bd4e70a 473explicitly state "this test will fail" by wrapping it in a C<TODO> block.
9dc10e63 474
475 use Test::More tests => 1;
476
477 TODO: {
478 local $TODO = 'ical($ical) not yet implemented';
479
480 my $ical = Date::ICal->new;
481 $ical->ical('20201231Z');
482
483 is( $ical->ical, '20201231Z', 'Setting via ical()' );
484 }
485
486Now when you run, it's a little different:
487
488 1..1
489 not ok 1 - Setting via ical() # TODO ical($ical) not yet implemented
490 # got: '20010822T201551Z'
491 # expected: '20201231Z'
492
493Test::More doesn't say "Looks like you failed 1 tests of 1". That '#
494TODO' tells Test::Harness "this is supposed to fail" and it treats a
495failure as a successful test. So you can write tests even before
496you've fixed the underlying code.
497
498If a TODO test passes, Test::Harness will report it "UNEXPECTEDLY
4bd4e70a 499SUCCEEDED". When that happens, you simply remove the TODO block with
9dc10e63 500C<local $TODO> and turn it into a real test.
501
502
503=head2 Testing with taint mode.
504
505Taint mode is a funny thing. It's the globalest of all global
30e302f8 506features. Once you turn it on, it affects I<all> code in your program
4bd4e70a 507and I<all> modules used (and all the modules they use). If a single
9dc10e63 508piece of code isn't taint clean, the whole thing explodes. With that
509in mind, it's very important to ensure your module works under taint
510mode.
511
512It's very simple to have your tests run under taint mode. Just throw
4bd4e70a 513a C<-T> into the C<#!> line. Test::Harness will read the switches
514in C<#!> and use them to run your tests.
9dc10e63 515
516 #!/usr/bin/perl -Tw
517
9dc10e63 518 ...test normally here...
519
4bd4e70a 520So when you say C<make test> it will be run with taint mode and
9dc10e63 521warnings on.
522
523
524=head1 FOOTNOTES
525
526=over 4
527
528=item 1
529
530The first number doesn't really mean anything, but it has to be 1.
531It's the second number that's important.
532
533=item 2
534
535For those following along at home, I'm using version 1.31. It has
536some bugs, which is good -- we'll uncover them with our tests.
537
538=item 3
539
540You can actually take this one step further and test the manual
4bd4e70a 541itself. Have a look at B<Test::Inline> (formerly B<Pod::Tests>).
9dc10e63 542
543=item 4
544
545Yes, there's a mistake in the test suite. What! Me, contrived?
546
547=item 5
548
549We'll get to testing the contents of lists later.
550
551=item 6
552
553But what happens if your test program dies halfway through?! Since we
554didn't say how many tests we're going to run, how can we know it
555failed? No problem, Test::More employs some magic to catch that death
556and turn the test into a failure, even if every test passed up to that
557point.
558
559=item 7
560
561I cleaned it up a little.
562
563=item 8
564
565Most Operating Systems record time as the number of seconds since a
566certain date. This date is the beginning of the epoch. Unix's starts
567at midnight January 1st, 1970 GMT.
568
569=item 9
570
571MacOS's epoch is midnight January 1st, 1904. VMS's is midnight,
572November 17th, 1858, but vmsperl emulates the Unix epoch so it's not a
573problem.
574
575=item 10
576
577As long as the code inside the SKIP block at least compiles. Please
578don't ask how. No, it's not a filter.
579
580=item 11
581
582Do NOT be tempted to use TODO tests as a way to avoid fixing simple
583bugs!
584
585=back
4bd4e70a 586
587=head1 AUTHORS
588
589Michael G Schwern E<lt>schwern@pobox.comE<gt> and the perl-qa dancers!
590
591=head1 COPYRIGHT
592
593Copyright 2001 by Michael G Schwern E<lt>schwern@pobox.comE<gt>.
594
595This documentation is free; you can redistribute it and/or modify it
596under the same terms as Perl itself.
597
598Irrespective of its distribution, all code examples in these files
599are hereby placed into the public domain. You are permitted and
600encouraged to use this code in your own programs for fun
601or for profit as you see fit. A simple comment in the code giving
602credit would be courteous but is not required.
603
604=cut