1Test::Deep(3)         User Contributed Perl Documentation        Test::Deep(3)
2
3
4

NAME

6       Test::Deep - Extremely flexible deep comparison
7

SYNOPSIS

9         use Test::More tests => $Num_Tests;
10         use Test::Deep;
11
12         cmp_deeply(
13           $actual_horrible_nested_data_structure,
14           $expected_horrible_nested_data_structure,
15           "got the right horrible nested data structure"
16         );
17
18         cmp_deeply(
19           $object,
20           methods(name => "John", phone => "55378008"),
21           "object methods ok"
22         );
23
24         cmp_deeply(
25           \@array,
26           [$hash1, $hash2, ignore(
27           "first 2 elements are as expected, ignoring 3"
28         );
29
30         cmp_deeply(
31           $object,
32           noclass({value => 5}),
33           "object looks ok, not checking it's class"
34         );
35
36         cmp_deeply(
37           \@result,
38           bag('a', 'b', {key => [1, 2]}),
39           "array has the 3 things we wanted in some order"
40         );
41

DESCRIPTION

43       If you don't know anything about automated testing in Perl then you
44       should probably read about Test::Simple and Test::More before preced‐
45       ing.  Test::Deep uses the Test::Builder framework.
46
47       Test::Deep gives you very flexible ways to check that the result you
48       got is the result you were expecting. At it's simplest it compares two
49       structures by going through each level, ensuring that the values match,
50       that arrays and hashes have the same elements and that references are
51       blessed into the correct class. It also handles circular data struc‐
52       tures without getting caught in an infinite loop.
53
54       Where it becomes more interesting is in allowing you to do something
55       besides simple exact comparisons. With strings, the "eq" operator
56       checks that 2 strings are exactly equal but sometimes that's not what
57       you want. When you don't know exactly what the string should be but you
58       do know some things about how it should look, "eq" is no good and you
59       must use pattern matching instead. Test::Deep provides pattern matching
60       for complex data structures
61

EXAMPLES

63       How Test::Deep works is much easier to understand by seeing some exam‐
64       ples.
65
66       Without Test::Deep
67
68       Say you want to test a function which returns a string. You know that
69       your string should be a 7 digit number beginning with 0, "eq" is no
70       good in this situation, you need a regular expression. So you could use
71       Test::More's "like()" function:
72
73         like($string, '/^0d{6}$/', "number looks good");
74
75       Similarly, to check that a string looks like a name, you could do:
76
77         like($string, '/^(Mr⎪Mrs⎪Miss) \w+ \w+$/',
78           "got title, first and last name");
79
80       Now imagine your function produces a hash with some personal details in
81       it.  You want to make sure that there are 2 keys, Name and Phone and
82       that the name looks like a name and the phone number looks like a phone
83       number. You could do:
84
85         $hash = make_person();
86         like($hash->{Name}, '/^(Mr⎪Mrs⎪Miss) \w+ \w+$/', "name ok");
87         like($hash->{Phone}, '/^0d{6}$/', "phone ok");
88         is(scalar keys %$hash, 2, "correct number of keys");
89
90       But that's not quite right, what if make_person has a serious problem
91       and didn't even return a hash? We really need to write
92
93         if (ref($hash) eq "HASH")
94         {
95           like($hash->{Name}, '/^(Mr⎪Mrs⎪Miss) \w+ \w+$/', "name ok");
96           like($hash->{Phone}, '/^0d{6}$/', "phone ok");
97           is(scalar keys %$hash, 2, "correct number of keys");
98         }
99         else
100         {
101           fail("person not a hash");
102           fail("person not a hash");
103           fail("person not a hash"); # need 3 to keep the plan correct
104         }
105
106       Already this is getting messy, now imagine another entry in the hash,
107       an array of children's names. This would require
108
109         if (ref($hash) eq "HASH")
110         {
111           like($hash->{Name}, $name_pat, "name ok");
112           like($hash->{Phone}, '/^0d{6}$/', "phone ok");
113           my $cn = $hash->{ChildNames};
114           if (ref($cn) eq "ARRAY")
115           {
116             foreach my $child (@$cn)
117             {
118               like($child, $name_pat);
119             }
120           }
121           else
122           {
123               fail("child names not an array")
124           }
125         }
126         else
127         {
128           fail("person not a hash");
129         }
130
131       This is a horrible mess and because we don't know in advance how many
132       children's names there will be, we can't make a plan for our test any‐
133       more (actually, we could but it would make things even more compli‐
134       cated).
135
136       Test::Deep to the rescue.
137
138       With Test::Deep
139
140         my $name_re = re('^(Mr⎪Mrs⎪Miss) \w+ \w+$');
141         cmp_deeply(
142           $person,
143           {
144             Name => $name_re,
145             Phone => re('^0d{6}$'),
146             ChildNames => array_each($name_re)
147           },
148           "person ok"
149         );
150
151       This will do everything that the messy code above does and it will give
152       a sensible message telling you exactly what went wrong if it finds a
153       part of $person that doesn't match the pattern. "re()" and
154       "array_each()" are special function imported from Test::Deep. They cre‐
155       ate a marker that tells Test::Deep that something different is happen‐
156       ing here. Instead of just doing a simple comparison and checking are
157       two things exactly equal, it should do something else.
158
159       If a person was asked to check that 2 structures are equal, they could
160       print them both out and compare them line by line. The markers above
161       are similar to writing a note in red pen on one of the printouts
162       telling the person that for this piece of the structure, they should
163       stop doing simple line by line comparison and do something else.
164
165       "re($regex)" means that Test::Deep should check that the current piece
166       of data matches the regex in $regex. "array_each($struct)" means that
167       Test::Deep should expect the current piece of data to be an array and
168       it should check that every element of that array matches $struct.  In
169       this case, every element of "$person-"{ChildNames}> should look like a
170       name. If say the 3rd one didn't you would get an error message some‐
171       thing like
172
173         Using Regexp on $data->{ChildNames}[3]
174            got    : 'Queen John Paul Sartre'
175            expect : /^(Mr⎪Mrs⎪Miss) \w+ \w+$/
176
177       There are lots of other special comparisons available, see "SPECIAL
178       COMPARISONS PROVIDED" below for the full list.
179
180       Reusing structures
181
182       Test::Deep is good for reusing test structures so you can do this
183
184         my $name_re = re('^(Mr⎪Mrs⎪Miss) \w+ \w+$');
185         my $person_cmp = {
186           Name => $name_re,
187           Phone => re('^0d{6}$'),
188           ChildNames => array_each($name_re)
189         };
190
191         cmp_deeply($person1, $person_cmp, "person ok");
192         cmp_deeply($person2, $person_cmp, "person ok");
193         cmp_deeply($person3, $person_cmp, "person ok");
194
195       You can even put $person_cmp in a module and let other people use it
196       when they are writing test scripts for modules that use your modules.
197
198       To make things a little more difficult, lets change the person data
199       structure so that instead of a list of ChildNames, it contains a list
200       of hashes, one for each child. So in fact our person structure will
201       contain other person structures which may contain other person struc‐
202       tures and so on.  This is easy to handle with Test::Deep because
203       Test::Deep structures can include themselves. Simply do
204
205         my $name_re = re('^(Mr⎪Mrs⎪Miss) \w+ \w+$');
206         my $person_cmp = {
207           Name => $name_re,
208           Phone => re('^0d{6}$'),
209           # note no mention of Children here
210         };
211
212         $person_cmp->{Children} = each_array($person_cmp);
213
214         cmp_deeply($person, $person_cmp, "person ok");
215
216       This will now check that $person->{Children} is an array and that every
217       element of that array also matches $person_cmp, this includes checking
218       that it's children also match the same pattern and so on.
219
220       Circular data structures
221
222       A circular data structure is one which loops back on itself, you can
223       make one easily by doing
224
225         my @b;
226         my @a = (1, 2, 3, \@b);
227         push(@b, \@a);
228
229       now @a contains a reference to be @b and @b contains a reference to @a.
230       This causes problems if you have a program that wants to look inside @a
231       and keep looking deeper and deeper at every level, it could get caught
232       in an infinite loop looking into @a then @b then @a then @b and so on.
233
234       Test::Deep avoids this problem so we can extend our example further by
235       saying that a person should also list their parents.
236
237         my $name_re = re('^(Mr⎪Mrs⎪Miss) \w+ \w+$');
238         my $person_cmp = {
239           Name => $name_re,
240           Phone => re('^0d{6}$'),
241           # note no mention of Children here
242         };
243
244         $person_cmp->{Children} = each_array($person_cmp);
245         $person_cmp->{Parents} = each_array($person_cmp);
246
247         cmp_deeply($person, $person_cmp, "person ok");
248
249       So this will check that for each child $child in "$person-"{Children}>
250       that the "$child-"{Parents} matches $person_cmp however it is smart
251       enough not to get caught in an infinite loop where it keeps bouncing
252       between the same Parent and Child.
253

TERMINOLOGY

255       "cmp_deeply($got, $expected, $name)" takes 3 arguments. $got is the
256       structure that you are checking, you must not include any special com‐
257       parisons in this structure or you will get a fatal error. $expected
258       describes what Test::Deep will be looking for in $got. You can put spe‐
259       cial comparisons in $expected if you want to.
260
261       As Test::Deep descends through the 2 structures, it compares them one
262       piece at a time, so at any point in the process, Test::Deep is thinking
263       about 2 things - the current value from $got and the current value from
264       $expected. In the documentation, I call them $got_v and "exp_v" respec‐
265       tively.
266

COMPARISON FUNCTIONS

268       $ok = cmp_deeply($got, $expected, $name)
269
270       $got is the result to be checked. $expected is the structure against
271       which $got will be check. $name is the test name.
272
273       This is the main comparison function, the others are just wrappers
274       around this. Without any special comparisons, it will descend into
275       $expected, following every reference and comparing $expected_v to
276       $got_v (using "eq") at the same position. If at any stage $expected_v
277       is a special comparison then Test::Deep may do something else besides a
278       simple string comparison, exactly what it does depends on which special
279       comparison it is.
280
281       $ok = cmp_bag(\@got, \@bag, $name)
282
283       Is shorthand for cmp_deeply(\@got, bag(@bag), $name)
284
285       $ok = cmp_set(\@got, \@set, $name)
286
287       Is shorthand for cmp_deeply(\@got, set(@set), $name)
288
289       $ok = cmp_methods(\@got, \@methods, $name)
290
291       Is shorthand for cmp_deeply(\@got, methods(@methods), $name)
292
293       $ok = eq_deeply($got, $expected, $name)
294
295       This is the same as cmp_deeply() it just returns true or false. It does
296       not create diagnostics or talk to Test::Builder, but if you want to use
297       it in a non-testing environment then you should import it through
298       Test::Deep::NoTest, for example
299
300         use Test::Deep::NoTest;
301         print "a equals b" unless eq_deeply($a, $b);
302
303       otherwise the Test::Builder framework will be loaded and testing mes‐
304       sages will be output when your program ends.
305

SPECIAL COMPARISONS PROVIDED

307       ignore()
308
309       This makes Test::Deep skip tests on $got_v. No matter what value $got_v
310       has, Test::Deep will think it's correct. This is useful if some part of
311       the structure you are testing is very complicated and already tested
312       elsewhere, or is unpredictable.
313
314         cmp_deeply($got, { name => 'John', random => ignore(), address => ['5 A
315           street', 'a town', 'a country'],
316         })
317
318       is the equivalent of checking
319
320         $got->{name} eq 'John';
321         exists $got->{random};
322         cmp_deeply($got->{address};
323         ['5 A street', 'a town', 'a country']);
324
325       methods(%hash)
326
327       %hash is a hash of method call => expected value pairs.
328
329       This lets you call methods on an object and check the result of each
330       call.  The methods will be called in the order supplied. If you want to
331       pass arguments to the method you should wrap the method name and argu‐
332       ments in an array reference.
333
334         cmp_deeply(
335           $obj,
336           methods(name => "John", ["favourite", "food"] => "taco")
337         );
338
339       is roughly the equivalent of checking that
340
341         $obj->name eq "John"
342         $obj->favourite("food") eq "taco"
343
344       The methods will be called in the order you supply them and will be
345       called in scalar context. If you need to test methods called in list
346       context then you should use listmethods().
347
348       NOTE Just as in a normal test script, you need to be careful if the
349       methods you call have side effects like changing the object or other
350       objects in the structure. Although the order of the methods is fixed,
351       the order of some other tests is not so if $expected is
352
353         {
354           manager => methods(@manager_methods),
355           coder => methods(@coder_methods)
356         }
357
358       there is no way to know which if manager and coder will be tested
359       first. If the methods you are testing depend on and alter global vari‐
360       ables or if manager and coder are the same object then you may run into
361       problems.
362
363       listmethods(%hash)
364
365       %hash is a hash of method call => expected value pairs.
366
367       This is almost identical to methods() except the methods are called in
368       list context instead of scalar context. This means that the expected
369       values supplied must be an array reference.
370
371         cmp_deeply(
372           $obj,
373           listmethods(
374             name => "John",
375             ["favourites", "food"] => ["Mapo tofu", "Gongbao chicken"]
376           )
377         );
378
379       is the equivalent of checking that
380
381         $obj->name eq "John"
382         cmp_deeply([$obj->favourites("food")], ["Mapo tofu", "Gongbao chicken"]);
383
384       The methods will be called in the order you supply them.
385
386       NOTE The same caveats apply as for methods().
387
388       shallow($thing)
389
390       $thing is a ref.
391
392       This prevents Test::Deep from looking inside $thing. It allows you to
393       check that $got_v and $thing are references to the same variable. So
394
395         my @a = @b = (1, 2, 3);
396         cmp_deeply(\@a, \@b);
397
398       will pass because @a and @b have the same elements however
399
400         cmp_deeply(\@a, shallow(\@b))
401
402       will fail because although \@a and \@b both contain "1, 2, 3" they are
403       references to different arrays.
404
405       noclass($thing)
406
407       $thing is a structure to be compared against.
408
409       This makes Test::Deep ignore the class of objects, so it just looks at
410       the data they contain. Class checking will be turned off until
411       Test::Deep is finished comparing $got_v against $thing. Once Test::Deep
412       comes out of $thing it will go back to it's previous setting for check‐
413       ing class.
414
415       This can be useful when you want to check that objects have been con‐
416       structed correctly but you don't want to write lots of "bless"es. If
417       \@people is an array of Person objects then
418
419         cmp_deeply(\@people, noclass([
420           bless {name => 'John', phone => '555-5555'}, "Person",
421           bless {name => 'Anne', phone => '444-4444'}, "Person",
422         ]));
423
424       can be replaced with
425
426         cmp_deeply(\@people, noclass([
427           {name => 'John', phone => '555-5555'},
428           {name => 'Anne', phone => '444-4444'}
429         ]));
430
431       However, this is testing so you should also check that the objects are
432       blessed correctly. You could use a map to bless all those hashes or you
433       could do a second test like
434
435         cmp_deeply($people, array_each(isa("Person"));
436
437       useclass($thing)
438
439       This turns back on the class comparison while inside a noclass().
440
441         cmp_deeply(
442           $got,
443           noclass(
444             [
445               useclass( $object )
446             ]
447           )
448         )
449
450       In this example the class of the array reference in $got is ignored but
451       the class of $object is checked, as is the class of everything inside
452       $object.
453
454       re($regexp, $capture_data, $flags)
455
456       $regexp is either a regular expression reference produced with
457       "qr/.../" or a string which will be used to construct a regular expres‐
458       sion.
459
460       $capture_data is optional and is used to check the strings captured by
461       an regex, for example should either be an array ref
462
463       $flags is an optional string which controls whether the regex runs as a
464       global match. If $flags is "g" then the regex will run as m/$regexp/g.
465
466       Without $capture_data, this simply compares $got_v with the regular
467       expression provided. So
468
469         cmp_deeply($got, [ re("ferg") ])
470
471       is the equivalent of
472
473         $got->[0] =~ /ferg/
474
475       With $capture_data
476
477         cmp_deeply($got, [re($regex, $capture_data])
478
479       is the equivalent of
480
481         my @data = $got->[0] =~ /$regex/;
482         cmp_deeply(\@data, $capture_data);
483
484       So you can do something simple like
485
486         cmp_deeply($got, re(qr/(\d\d)(\w\w)/, [25, "ab" ])
487
488       to check that (\d\d) was 25 and (\w\w) was "ab" but you can also use
489       Test::Deep objects to do more complex testing of the captured values
490
491         cmp_deeply("cat=2,dog=67,sheep=3,goat=2,dog=5",
492           re(qr/(\D+)=\d+,?/, set(qw( cat sheep dog )), "g"))
493
494       here, the regex will match the string and will capture the animal names
495       and check that they match the specified set, in this case it will fail,
496       complaining that "goat" is not in the set.
497
498       superhashof(\%hash)
499
500       This will check that the hash %$got is a "super-hash" of %hash. That is
501       that all the key and value pairs in %hash appear in %$got but %$got can
502       have extra ones also.
503
504       For example
505
506         cmp_deeply({a => 1, b => 2}, superhashof({a => 1}))
507
508       will pass but
509
510         cmp_deeply({a => 1, b => 2}, superhashof({a => 1, c => 3}))
511
512       will fail.
513
514       subhashof(\%hash)
515
516       This will check that the hash %$got is a "sub-hash" of %hash. That is
517       that all the key and value pairs in %$got also appear in %hash.
518
519       For example
520
521         cmp_deeply({a => 1}, subhashof({a => 1, b => 2}))
522
523       will pass but
524
525         cmp_deeply({a => 1, c => 3}, subhashof({a => 1, b => 2}))
526
527       will fail.
528
529       bag(@elements)
530
531       @elements is an array of elements.
532
533       This does a bag comparison, that is, it compares two arrays but ignores
534       the order of the elements so
535
536         cmp_deeply([1, 2, 2], bag(2, 2, 1))
537
538       will be a pass.
539
540       The object returned by bag() has an add() method.
541
542         my $bag = bag(1, 2, 3);
543         $bag->add(2, 3, 4);
544
545       will result in a bag containing 1, 2, 2, 3, 3, 4.
546
547       "NOTE" If you use certain special comparisons within a bag or set com‐
548       parison there is a danger that a test will fail when it should have
549       passed. It can only happen if two or more special comparisons in the
550       bag are competing to match elements. Consider this comparison
551
552         cmp_deeply(['furry', 'furball'], bag(re("^fur"), re("furb")))
553
554       There are two things that could happen, hopefully "re("^fur")" is
555       paired with "furry" and "re("^furb")" is paired with "furb" and every‐
556       thing is fine but it could happen that "re("^fur")" is paired with
557       "furball" and then "re("^furb")" cannot find a match and so the test
558       fails. Examples of other competing comparisons are "bag(1, 2, 2)" vs
559       "set(1, 2)" and "methods(m1 =" "v1", m2 => "v2")> vs "methods(m1 ="
560       "v1")>
561
562       This problem is could be solved by using a slower and more complicated
563       algorithm for set and bag matching. Something for the future...
564
565       set(@elements)
566
567       @elements is an array of elements.
568
569       This does a set comparison, that is, it compares two arrays but ignores
570       the order of the elements and it ignores duplicate elements, so
571
572         cmp_deeply([1, 2, 2, 3], set(3, 2, 1, 1))
573
574       will be a pass.
575
576       The object returned by set() has an add() method.
577
578         my $set = set(1, 2, 3);
579         $set->add(4, 5, 6);
580
581       will result in a set containing 1, 2, 3, 4, 5, 5.
582
583       "NOTE" See the NOTE on the bag() comparison for some dangers in using
584       special comparisons inside set()
585
586       superbagof(@elements), subbagof(@elements), supersetof(@elements) and
587       subsetof(@elements)
588
589       @elements is an array of elements.
590
591       These do exactly what you'd expect them to do, so for example
592
593         cmp_deeply($data, subbagof(1, 1, 3, 4));
594
595       checks that @$data contains at most 2 "1"s, 1 "3" and 1 "4" and
596
597         cmp_deeply($data, supsersetof(1, 4));
598
599       check that @$data contains at least 1 "1" and 1 "4".
600
601       These are just special cases of the Set and Bag comparisons so they
602       also give you an add() method and they also have the same limitations
603       when using special comparisons inside them (see the NOTE in the bag()
604       section).
605
606       all(@expecteds)
607
608       @expecteds is an array of expected structures.
609
610       This allows you to compare data against multiple expected results and
611       make sure each of them matches.
612
613         cmp_deeply($got, all(isa("Person"), methods(name => 'John')))
614
615       is equivalent to
616
617         $got->isa("Person")
618         $got->name eq 'John'
619
620       If either test fails then the whole thing is considered a fail. This is
621       a short-circuit test, the testing is stopped after the first failure,
622       although in the future it may complete all tests so that diagnostics
623       can be output for all failures. When reporting failure, the parts are
624       counted from 1.
625
626       Thanks to the magic of overloading, you can write
627
628         all(isa("Person"), methods(name => 'John'), re("^wi"))
629
630       as
631
632         isa("Person") & methods(name => 'John') ⎪ re("^wi")
633
634       Note single ⎪ not double as ⎪⎪ cannot be overloaded. This will only
635       work when there is a special comparison involved. If you write
636
637         "john" ⎪ "anne" ⎪ "robert"
638
639       Perl will turn this into
640
641         "{onort"
642
643       which is presumably not what you wanted. This is because Perl ⎪s them
644       together as strings before Test::Deep gets a chance to do any overload
645       tricks.
646
647       any(@expecteds)
648
649       @expecteds is an array of expected structures.
650
651       This can be used to compare data against multiple expected results and
652       make sure that at least one of them matches. This is a short-circuit
653       test so if a test passes then none of the tests after that will be
654       attempted.
655
656       You can also use overloading with ⎪ similarly to all().
657
658       isa($class)
659
660       $class is a class name.
661
662       This uses UNIVERSAL::isa() to check that $got_v is blessed into the
663       class $class.
664
665       array_each($thing)
666
667       $thing is a structure to be compared against.
668
669       <$got_v> must be an array reference. Each element of it will be com‐
670       pared to $thing. This is useful when you have an array of similar
671       things, for example objects of a known type and you don't want to have
672       to repeat the same test for each one.
673
674         my $common_tests = all(
675            isa("MyFile"),
676            methods(
677              handle => isa("IO::Handle")
678              filename => re("^/home/ted/tmp"),
679           )
680         );
681
682         cmp_deeply($got, array_each($common_tests));
683
684       is similar to
685
686         foreach my $got_v (@$got) {
687           cmp_deeply($got_v, $common_tests)
688         }
689
690       Except it will not explode is $got is not an array reference. It will
691       check that each of the objects in @$got is a MyFile and that each one
692       gives the correct results for it's methods.
693
694       You could go further, if for example there were 3 files and you knew
695       the size of each one you could do this
696
697         cmp_deeply(
698           $got,
699           all(
700             array_each($common_tests),
701             [
702               methods(size => 1000),
703               methods(size => 200),
704               methods(size => 20)
705             ]
706           )
707         )
708         cmp_deeply($got, array_each($structure));
709
710       str($string)
711
712       $string is a string.
713
714       This will stringify $got_v and compare it to $string using "eq", even
715       if $got_v is a ref. It is useful for checking the stringified value of
716       an overloaded reference.
717
718       num($number, $tolerance)
719
720       $number is a number.  $tolerance is an optional number.
721
722       This will add 0 to $got_v and check if it's numerically equal to $num‐
723       ber, even if $got_v is a ref. It is useful for checking the numerical
724       value of an overloaded reference. If $tolerance is supplied then this
725       will check that $got_v and $exp_v are less than $tolerance apart. This
726       is useful when comparing floating point numbers as rounding errors can
727       make it hard or impossible for $got_v to be exactly equal to $exp_v.
728       When $tolerance is supplied, the test passes if "abs($got_v - $exp_v)
729       <= $tolerance".
730
731       Note in Perl, ""12blah" == 12" because Perl will be smart and convert
732       "12blah" into 12. You may not want this. There was a strict mode but
733       that is now gone. A "lookslike s number" test will replace it soon.
734       Until then you can usually just use the string() comparison to be more
735       strict. This will work fine for almost all situations, however it will
736       not work when <$got_v> is an overloaded value who's string and numeri‐
737       cal values differ.
738
739       bool($value)
740
741       $value is anything you like but it's probably best to use 0 or 1
742
743       This will check that $got_v and $value have the same truth value, that
744       is they will give the same result when used in boolean context, like in
745       an if() statement.
746
747       code(\&subref)
748
749       \&subref is a reference to a subroutine which will be passed a single
750       argument, it then should return a true or false and possibly a string
751
752       This will pass $got_v to the subroutine which returns true or false to
753       indicate a pass or fail. Fails can be accompanied by a diagnostic
754       string which gives an explanation of why it's a fail.
755
756         sub check_name
757         {
758           my $name = shift;
759           if ($boss->likes($name))
760           {
761             return 1;
762           }
763           else
764           {
765             return (0, "the boss doesn't like your name");
766           }
767         }
768
769         cmp_deeply("Brian", \&check_name);
770

ANOTHER EXAMPLE

772       You've written a module to handle people and their film interests. Say
773       you have a function that returns an array of people from a query, each
774       person is a hash with 2 keys: Name and Age and the array is sorted by
775       Name. You can do
776
777         cmp_deeply(
778           $result,
779           [
780             {Name => 'Anne', Age => 26},
781             {Name => "Bill", Age => 47}
782             {Name => 'John', Age => 25},
783           ]
784         );
785
786       Soon after, your query function changes and all the results now have an
787       ID field. Now your test is failing again because you left out ID from
788       each of the hashes. The problem is that the IDs are generated by the
789       database and you have no way of knowing what each person's ID is. With
790       Test::Deep you can change your query to
791
792         cmp_deeply(
793           $result,
794           [
795             {Name => 'John', Age => 25, ID => ignore()},
796             {Name => 'Anne', Age => 26, ID => ignore()},
797             {Name => "Bill", Age => 47, ID => ignore()}
798           ]
799         );
800
801       But your test still fails. Now, because you're using a database, you no
802       longer know what order the people will appear in. You could add a sort
803       into the database query but that could slow down your application.
804       Instead you can get Test::Deep to ignore the order of the array by
805       doing a bag comparison instead.
806
807         cmp_deeply(
808           $result,
809           bag(
810             {Name => 'John', Age => 25, ID => ignore()},
811             {Name => 'Anne', Age => 26, ID => ignore()},
812             {Name => "Bill", Age => 47, ID => ignore()}
813           )
814         );
815
816       Finally person gets even more complicated and includes a new field
817       called Movies, this is a list of movies that the person has seen
818       recently, again these movies could also come back in any order so we
819       need a bag inside our other bag comparison, giving us something like
820
821         cmp_deeply(
822         $result,
823           bag(
824             {Name => 'John', Age => 25, ID => ignore(), Movies => bag(...)},
825             {Name => 'Anne', Age => 26, ID => ignore(), Movies => bag(...)},
826             {Name => "Bill", Age => 47, ID => ignore(), Movies => bag(...)}
827           )
828         );
829

LIMITITATIONS

831       Currently any CODE, GLOB or IO refs will be compared using shallow(),
832       which means only their memory addresses are compared.
833

BUGS

835       There is a bug in set and bag compare to do with competing SCs. It only
836       occurs when you put certain special comparisons inside bag or set com‐
837       parisons you don't need to worry about it. The full details are in the
838       bag() docs. It will be fixed in an upcoming version.
839

WHAT ARE SPECIAL COMPARISONS?

841       A special comparison (SC) is simply an object that inherits from
842       Test::Deep::Cmp. Whenever $expected_v is an SC then instead of checking
843       "$got_v eq $expected_v", we pass control over to the SC and let it do
844       it's thing.
845
846       Test::Deep exports lots of SC constructors, to make it easy for you to
847       use them in you tests scripts. For example is "re("hello")" is just a
848       handy way of creating a Test::Deep::Regexp object that will match any
849       string containing "hello". So
850
851         cmp_deeply([ 'a', 'b', 'hello world'], ['a', 'b', re("^hello")]);
852
853       will check 'a' eq 'a', 'b' eq 'b' but when it comes to comparing 'hello
854       world' and "re("^hello")" it will see that $expected_v is an SC and so
855       will pass control to the Test::Deep::Regex class by do something like
856       "$expected_v-"descend($got_v)>. The "descend()" method should just
857       return true or false.
858
859       This gives you enough to write your own SCs but I haven't documented
860       how diagnostics works because it's about to get an overhaul.
861

SEE ALSO

863       Test::More
864

AUTHOR

866       Fergal Daly <fergal@esatclear.ie>, with thanks to Michael G Schwern for
867       Test::More's is_deeply function which inspired this.
868
870       Copyright 2003, 2004 by Fergal Daly <fergal@esatclear.ie>.
871
872       This program is free software; you can redistribute it and/or modify it
873       under the same terms as Perl itself.
874
875       See http://www.perl.com/perl/misc/Artistic.html
876
877
878
879perl v5.8.8                       2005-11-30                     Test::Deep(3)
Impressum