1Test::Deep(3) User Contributed Perl Documentation Test::Deep(3)
2
3
4
6 Test::Deep - Extremely flexible deep comparison
7
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
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
45 preceding. 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
52 structures 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
63 How Test::Deep works is much easier to understand by seeing some
64 examples.
65
66 Without Test::Deep
67 Say you want to test a function which returns a string. You know that
68 your string should be a 7 digit number beginning with 0, "eq" is no
69 good in this situation, you need a regular expression. So you could use
70 Test::More's "like()" function:
71
72 like($string, '/^0d{6}$/', "number looks good");
73
74 Similarly, to check that a string looks like a name, you could do:
75
76 like($string, '/^(Mr|Mrs|Miss) \w+ \w+$/',
77 "got title, first and last name");
78
79 Now imagine your function produces a hash with some personal details in
80 it. You want to make sure that there are 2 keys, Name and Phone and
81 that the name looks like a name and the phone number looks like a phone
82 number. You could do:
83
84 $hash = make_person();
85 like($hash->{Name}, '/^(Mr|Mrs|Miss) \w+ \w+$/', "name ok");
86 like($hash->{Phone}, '/^0d{6}$/', "phone ok");
87 is(scalar keys %$hash, 2, "correct number of keys");
88
89 But that's not quite right, what if make_person has a serious problem
90 and didn't even return a hash? We really need to write
91
92 if (ref($hash) eq "HASH")
93 {
94 like($hash->{Name}, '/^(Mr|Mrs|Miss) \w+ \w+$/', "name ok");
95 like($hash->{Phone}, '/^0d{6}$/', "phone ok");
96 is(scalar keys %$hash, 2, "correct number of keys");
97 }
98 else
99 {
100 fail("person not a hash");
101 fail("person not a hash");
102 fail("person not a hash"); # need 3 to keep the plan correct
103 }
104
105 Already this is getting messy, now imagine another entry in the hash,
106 an array of children's names. This would require
107
108 if (ref($hash) eq "HASH")
109 {
110 like($hash->{Name}, $name_pat, "name ok");
111 like($hash->{Phone}, '/^0d{6}$/', "phone ok");
112 my $cn = $hash->{ChildNames};
113 if (ref($cn) eq "ARRAY")
114 {
115 foreach my $child (@$cn)
116 {
117 like($child, $name_pat);
118 }
119 }
120 else
121 {
122 fail("child names not an array")
123 }
124 }
125 else
126 {
127 fail("person not a hash");
128 }
129
130 This is a horrible mess and because we don't know in advance how many
131 children's names there will be, we can't make a plan for our test
132 anymore (actually, we could but it would make things even more
133 complicated).
134
135 Test::Deep to the rescue.
136
137 With Test::Deep
138 my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$');
139 cmp_deeply(
140 $person,
141 {
142 Name => $name_re,
143 Phone => re('^0d{6}$'),
144 ChildNames => array_each($name_re)
145 },
146 "person ok"
147 );
148
149 This will do everything that the messy code above does and it will give
150 a sensible message telling you exactly what went wrong if it finds a
151 part of $person that doesn't match the pattern. "re()" and
152 "array_each()" are special function imported from Test::Deep. They
153 create a marker that tells Test::Deep that something different is
154 happening here. Instead of just doing a simple comparison and checking
155 are two things exactly equal, it should do something else.
156
157 If a person was asked to check that 2 structures are equal, they could
158 print them both out and compare them line by line. The markers above
159 are similar to writing a note in red pen on one of the printouts
160 telling the person that for this piece of the structure, they should
161 stop doing simple line by line comparison and do something else.
162
163 "re($regex)" means that Test::Deep should check that the current piece
164 of data matches the regex in $regex. "array_each($struct)" means that
165 Test::Deep should expect the current piece of data to be an array and
166 it should check that every element of that array matches $struct. In
167 this case, every element of "$person->{ChildNames}" should look like a
168 name. If say the 3rd one didn't you would get an error message
169 something like
170
171 Using Regexp on $data->{ChildNames}[3]
172 got : 'Queen John Paul Sartre'
173 expect : /^(Mr|Mrs|Miss) \w+ \w+$/
174
175 There are lots of other special comparisons available, see "SPECIAL
176 COMPARISONS PROVIDED" below for the full list.
177
178 Reusing structures
179 Test::Deep is good for reusing test structures so you can do this
180
181 my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$');
182 my $person_cmp = {
183 Name => $name_re,
184 Phone => re('^0d{6}$'),
185 ChildNames => array_each($name_re)
186 };
187
188 cmp_deeply($person1, $person_cmp, "person ok");
189 cmp_deeply($person2, $person_cmp, "person ok");
190 cmp_deeply($person3, $person_cmp, "person ok");
191
192 You can even put $person_cmp in a module and let other people use it
193 when they are writing test scripts for modules that use your modules.
194
195 To make things a little more difficult, lets change the person data
196 structure so that instead of a list of ChildNames, it contains a list
197 of hashes, one for each child. So in fact our person structure will
198 contain other person structures which may contain other person
199 structures and so on. This is easy to handle with Test::Deep because
200 Test::Deep structures can include themselves. Simply do
201
202 my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$');
203 my $person_cmp = {
204 Name => $name_re,
205 Phone => re('^0d{6}$'),
206 # note no mention of Children here
207 };
208
209 $person_cmp->{Children} = each_array($person_cmp);
210
211 cmp_deeply($person, $person_cmp, "person ok");
212
213 This will now check that $person->{Children} is an array and that every
214 element of that array also matches $person_cmp, this includes checking
215 that it's children also match the same pattern and so on.
216
217 Circular data structures
218 A circular data structure is one which loops back on itself, you can
219 make one easily by doing
220
221 my @b;
222 my @a = (1, 2, 3, \@b);
223 push(@b, \@a);
224
225 now @a contains a reference to be @b and @b contains a reference to @a.
226 This causes problems if you have a program that wants to look inside @a
227 and keep looking deeper and deeper at every level, it could get caught
228 in an infinite loop looking into @a then @b then @a then @b and so on.
229
230 Test::Deep avoids this problem so we can extend our example further by
231 saying that a person should also list their parents.
232
233 my $name_re = re('^(Mr|Mrs|Miss) \w+ \w+$');
234 my $person_cmp = {
235 Name => $name_re,
236 Phone => re('^0d{6}$'),
237 # note no mention of Children here
238 };
239
240 $person_cmp->{Children} = each_array($person_cmp);
241 $person_cmp->{Parents} = each_array($person_cmp);
242
243 cmp_deeply($person, $person_cmp, "person ok");
244
245 So this will check that for each child $child in "$person->{Children}"
246 that the "$child->{Parents}" matches $person_cmp however it is smart
247 enough not to get caught in an infinite loop where it keeps bouncing
248 between the same Parent and Child.
249
251 "cmp_deeply($got, $expected, $name)" takes 3 arguments. $got is the
252 structure that you are checking, you must not include any special
253 comparisons in this structure or you will get a fatal error. $expected
254 describes what Test::Deep will be looking for in $got. You can put
255 special comparisons in $expected if you want to.
256
257 As Test::Deep descends through the 2 structures, it compares them one
258 piece at a time, so at any point in the process, Test::Deep is thinking
259 about 2 things - the current value from $got and the current value from
260 $expected. In the documentation, I call them $got_v and "exp_v"
261 respectively.
262
264 $ok = cmp_deeply($got, $expected, $name)
265
266 $got is the result to be checked. $expected is the structure against
267 which $got will be check. $name is the test name.
268
269 This is the main comparison function, the others are just wrappers
270 around this. Without any special comparisons, it will descend into
271 $expected, following every reference and comparing $expected_v to
272 $got_v (using "eq") at the same position. If at any stage $expected_v
273 is a special comparison then Test::Deep may do something else besides a
274 simple string comparison, exactly what it does depends on which special
275 comparison it is.
276
277 $ok = cmp_bag(\@got, \@bag, $name)
278
279 Is shorthand for cmp_deeply(\@got, bag(@bag), $name)
280
281 N.B. Both arguments must be array refs. If they aren't an error will be
282 raised via die.
283
284 $ok = cmp_set(\@got, \@set, $name)
285
286 Is shorthand for cmp_deeply(\@got, set(@set), $name)
287
288 $ok = cmp_methods(\@got, \@methods, $name)
289
290 Is shorthand for cmp_deeply(\@got, methods(@methods), $name)
291
292 $ok = eq_deeply($got, $expected)
293
294 This is the same as cmp_deeply() except it just returns true or false.
295 It does not create diagnostics or talk to Test::Builder, but if you
296 want to use it in a non-testing environment then you should import it
297 through Test::Deep::NoTest. For example
298
299 use Test::Deep::NoTest;
300 print "a equals b" unless eq_deeply($a, $b);
301
302 otherwise the Test::Builder framework will be loaded and testing
303 messages will be output when your program ends.
304
305 ($ok, $stack) = cmp_details($got, $expected)
306
307 This behaves much like eq_deeply, but it additionally allows you to
308 produce diagnostics in case of failure by passing the value in $stack
309 to "deep_diag".
310
311 Do not make assumptions about the structure or content of $stack and do
312 not use it if $ok contains a true value.
313
314 See "USING TEST::DEEP WITH TEST::BUILDER" for example uses.
315
317 ignore()
318
319 This makes Test::Deep skip tests on $got_v. No matter what value $got_v
320 has, Test::Deep will think it's correct. This is useful if some part of
321 the structure you are testing is very complicated and already tested
322 elsewhere, or is unpredictable.
323
324 cmp_deeply($got, { name => 'John', random => ignore(), address => ['5 A
325 street', 'a town', 'a country'],
326 })
327
328 is the equivalent of checking
329
330 $got->{name} eq 'John';
331 exists $got->{random};
332 cmp_deeply($got->{address};
333 ['5 A street', 'a town', 'a country']);
334
335 methods(%hash)
336
337 %hash is a hash of method call => expected value pairs.
338
339 This lets you call methods on an object and check the result of each
340 call. The methods will be called in the order supplied. If you want to
341 pass arguments to the method you should wrap the method name and
342 arguments in an array reference.
343
344 cmp_deeply(
345 $obj,
346 methods(name => "John", ["favourite", "food"] => "taco")
347 );
348
349 is roughly the equivalent of checking that
350
351 $obj->name eq "John"
352 $obj->favourite("food") eq "taco"
353
354 The methods will be called in the order you supply them and will be
355 called in scalar context. If you need to test methods called in list
356 context then you should use listmethods().
357
358 NOTE Just as in a normal test script, you need to be careful if the
359 methods you call have side effects like changing the object or other
360 objects in the structure. Although the order of the methods is fixed,
361 the order of some other tests is not so if $expected is
362
363 {
364 manager => methods(@manager_methods),
365 coder => methods(@coder_methods)
366 }
367
368 there is no way to know which if manager and coder will be tested
369 first. If the methods you are testing depend on and alter global
370 variables or if manager and coder are the same object then you may run
371 into problems.
372
373 listmethods(%hash)
374
375 %hash is a hash of method call => expected value pairs.
376
377 This is almost identical to methods() except the methods are called in
378 list context instead of scalar context. This means that the expected
379 values supplied must be an array reference.
380
381 cmp_deeply(
382 $obj,
383 listmethods(
384 name => "John",
385 ["favourites", "food"] => ["Mapo tofu", "Gongbao chicken"]
386 )
387 );
388
389 is the equivalent of checking that
390
391 $obj->name eq "John"
392 cmp_deeply([$obj->favourites("food")], ["Mapo tofu", "Gongbao chicken"]);
393
394 The methods will be called in the order you supply them.
395
396 NOTE The same caveats apply as for methods().
397
398 shallow($thing)
399
400 $thing is a ref.
401
402 This prevents Test::Deep from looking inside $thing. It allows you to
403 check that $got_v and $thing are references to the same variable. So
404
405 my @a = @b = (1, 2, 3);
406 cmp_deeply(\@a, \@b);
407
408 will pass because @a and @b have the same elements however
409
410 cmp_deeply(\@a, shallow(\@b))
411
412 will fail because although \@a and \@b both contain "1, 2, 3" they are
413 references to different arrays.
414
415 noclass($thing)
416
417 $thing is a structure to be compared against.
418
419 This makes Test::Deep ignore the class of objects, so it just looks at
420 the data they contain. Class checking will be turned off until
421 Test::Deep is finished comparing $got_v against $thing. Once Test::Deep
422 comes out of $thing it will go back to it's previous setting for
423 checking class.
424
425 This can be useful when you want to check that objects have been
426 constructed correctly but you don't want to write lots of "bless"es. If
427 \@people is an array of Person objects then
428
429 cmp_deeply(\@people, noclass([
430 bless {name => 'John', phone => '555-5555'}, "Person",
431 bless {name => 'Anne', phone => '444-4444'}, "Person",
432 ]));
433
434 can be replaced with
435
436 cmp_deeply(\@people, noclass([
437 {name => 'John', phone => '555-5555'},
438 {name => 'Anne', phone => '444-4444'}
439 ]));
440
441 However, this is testing so you should also check that the objects are
442 blessed correctly. You could use a map to bless all those hashes or you
443 could do a second test like
444
445 cmp_deeply($people, array_each(isa("Person"));
446
447 useclass($thing)
448
449 This turns back on the class comparison while inside a noclass().
450
451 cmp_deeply(
452 $got,
453 noclass(
454 [
455 useclass( $object )
456 ]
457 )
458 )
459
460 In this example the class of the array reference in $got is ignored but
461 the class of $object is checked, as is the class of everything inside
462 $object.
463
464 re($regexp, $capture_data, $flags)
465
466 $regexp is either a regular expression reference produced with
467 "qr/.../" or a string which will be used to construct a regular
468 expression.
469
470 $capture_data is optional and is used to check the strings captured by
471 an regex. This should can be an array ref or a Test::Deep comparator
472 that works on array refs.
473
474 $flags is an optional string which controls whether the regex runs as a
475 global match. If $flags is "g" then the regex will run as m/$regexp/g.
476
477 Without $capture_data, this simply compares $got_v with the regular
478 expression provided. So
479
480 cmp_deeply($got, [ re("ferg") ])
481
482 is the equivalent of
483
484 $got->[0] =~ /ferg/
485
486 With $capture_data
487
488 cmp_deeply($got, [re($regex, $capture_data])
489
490 is the equivalent of
491
492 my @data = $got->[0] =~ /$regex/;
493 cmp_deeply(\@data, $capture_data);
494
495 So you can do something simple like
496
497 cmp_deeply($got, re(qr/(\d\d)(\w\w)/, [25, "ab" ])
498
499 to check that (\d\d) was 25 and (\w\w) was "ab" but you can also use
500 Test::Deep objects to do more complex testing of the captured values
501
502 cmp_deeply("cat=2,dog=67,sheep=3,goat=2,dog=5",
503 re(qr/(\D+)=\d+,?/, set(qw( cat sheep dog )), "g"))
504
505 here, the regex will match the string and will capture the animal names
506 and check that they match the specified set, in this case it will fail,
507 complaining that "goat" is not in the set.
508
509 superhashof(\%hash)
510
511 This will check that the hash %$got is a "super-hash" of %hash. That is
512 that all the key and value pairs in %hash appear in %$got but %$got can
513 have extra ones also.
514
515 For example
516
517 cmp_deeply({a => 1, b => 2}, superhashof({a => 1}))
518
519 will pass but
520
521 cmp_deeply({a => 1, b => 2}, superhashof({a => 1, c => 3}))
522
523 will fail.
524
525 subhashof(\%hash)
526
527 This will check that the hash %$got is a "sub-hash" of %hash. That is
528 that all the key and value pairs in %$got also appear in %hash.
529
530 For example
531
532 cmp_deeply({a => 1}, subhashof({a => 1, b => 2}))
533
534 will pass but
535
536 cmp_deeply({a => 1, c => 3}, subhashof({a => 1, b => 2}))
537
538 will fail.
539
540 bag(@elements)
541
542 @elements is an array of elements.
543
544 This does a bag comparison, that is, it compares two arrays but ignores
545 the order of the elements so
546
547 cmp_deeply([1, 2, 2], bag(2, 2, 1))
548
549 will be a pass.
550
551 The object returned by bag() has an add() method.
552
553 my $bag = bag(1, 2, 3);
554 $bag->add(2, 3, 4);
555
556 will result in a bag containing 1, 2, 2, 3, 3, 4.
557
558 "NOTE" If you use certain special comparisons within a bag or set
559 comparison there is a danger that a test will fail when it should have
560 passed. It can only happen if two or more special comparisons in the
561 bag are competing to match elements. Consider this comparison
562
563 cmp_deeply(['furry', 'furball'], bag(re("^fur"), re("furb")))
564
565 There are two things that could happen, hopefully "re("^fur")" is
566 paired with "furry" and "re("^furb")" is paired with "furb" and
567 everything is fine but it could happen that "re("^fur")" is paired with
568 "furball" and then "re("^furb")" cannot find a match and so the test
569 fails. Examples of other competing comparisons are "bag(1, 2, 2)" vs
570 "set(1, 2)" and "methods(m1 => "v1", m2 => "v2")" vs "methods(m1 =>
571 "v1")"
572
573 This problem is could be solved by using a slower and more complicated
574 algorithm for set and bag matching. Something for the future...
575
576 set(@elements)
577
578 @elements is an array of elements.
579
580 This does a set comparison, that is, it compares two arrays but ignores
581 the order of the elements and it ignores duplicate elements, so
582
583 cmp_deeply([1, 2, 2, 3], set(3, 2, 1, 1))
584
585 will be a pass.
586
587 The object returned by set() has an add() method.
588
589 my $set = set(1, 2, 3);
590 $set->add(4, 5, 6);
591
592 will result in a set containing 1, 2, 3, 4, 5, 5.
593
594 "NOTE" See the NOTE on the bag() comparison for some dangers in using
595 special comparisons inside set()
596
597 superbagof(@elements), subbagof(@elements), supersetof(@elements) and
598 subsetof(@elements)
599
600 @elements is an array of elements.
601
602 These do exactly what you'd expect them to do, so for example
603
604 cmp_deeply($data, subbagof(1, 1, 3, 4));
605
606 checks that @$data contains at most 2 "1"s, 1 "3" and 1 "4" and
607
608 cmp_deeply($data, supersetof(1, 4));
609
610 check that @$data contains at least 1 "1" and 1 "4".
611
612 These are just special cases of the Set and Bag comparisons so they
613 also give you an add() method and they also have the same limitations
614 when using special comparisons inside them (see the NOTE in the bag()
615 section).
616
617 all(@expecteds)
618
619 @expecteds is an array of expected structures.
620
621 This allows you to compare data against multiple expected results and
622 make sure each of them matches.
623
624 cmp_deeply($got, all(isa("Person"), methods(name => 'John')))
625
626 is equivalent to
627
628 $got->isa("Person")
629 $got->name eq 'John'
630
631 If either test fails then the whole thing is considered a fail. This is
632 a short-circuit test, the testing is stopped after the first failure,
633 although in the future it may complete all tests so that diagnostics
634 can be output for all failures. When reporting failure, the parts are
635 counted from 1.
636
637 Thanks to the magic of overloading, you can write
638
639 all(isa("Person"), methods(name => 'John'), re("^wi"))
640
641 as
642
643 isa("Person") & methods(name => 'John') | re("^wi")
644
645 Note single | not double as || cannot be overloaded. This will only
646 work when there is a special comparison involved. If you write
647
648 "john" | "anne" | "robert"
649
650 Perl will turn this into
651
652 "{onort"
653
654 which is presumably not what you wanted. This is because Perl |s them
655 together as strings before Test::Deep gets a chance to do any overload
656 tricks.
657
658 any(@expecteds)
659
660 @expecteds is an array of expected structures.
661
662 This can be used to compare data against multiple expected results and
663 make sure that at least one of them matches. This is a short-circuit
664 test so if a test passes then none of the tests after that will be
665 attempted.
666
667 You can also use overloading with | similarly to all().
668
669 isa($class), Isa($class)
670
671 $class is a class name.
672
673 This uses UNIVERSAL::isa() to check that $got_v is blessed into the
674 class $class.
675
676 NOTE: Isa() does exactly as documented here, but isa() is slightly
677 different. If isa() is called with 1 argument it falls through to
678 Isa(). If isa() called with 2 arguments, it falls through to
679 UNIVERSAL::isa. This is to prevent breakage when you import isa() into
680 a package that is used as a class. Without this, anyone calling
681 "Class->isa($other_class)" would get the wrong answer. This is a hack
682 to patch over the fact that isa is exported by default.
683
684 array_each($thing)
685
686 $thing is a structure to be compared against.
687
688 <$got_v> must be an array reference. Each element of it will be
689 compared to $thing. This is useful when you have an array of similar
690 things, for example objects of a known type and you don't want to have
691 to repeat the same test for each one.
692
693 my $common_tests = all(
694 isa("MyFile"),
695 methods(
696 handle => isa("IO::Handle")
697 filename => re("^/home/ted/tmp"),
698 )
699 );
700
701 cmp_deeply($got, array_each($common_tests));
702
703 is similar to
704
705 foreach my $got_v (@$got) {
706 cmp_deeply($got_v, $common_tests)
707 }
708
709 Except it will not explode is $got is not an array reference. It will
710 check that each of the objects in @$got is a MyFile and that each one
711 gives the correct results for it's methods.
712
713 You could go further, if for example there were 3 files and you knew
714 the size of each one you could do this
715
716 cmp_deeply(
717 $got,
718 all(
719 array_each($common_tests),
720 [
721 methods(size => 1000),
722 methods(size => 200),
723 methods(size => 20)
724 ]
725 )
726 )
727 cmp_deeply($got, array_each($structure));
728
729 str($string)
730
731 $string is a string.
732
733 This will stringify $got_v and compare it to $string using "eq", even
734 if $got_v is a ref. It is useful for checking the stringified value of
735 an overloaded reference.
736
737 num($number, $tolerance)
738
739 $number is a number. $tolerance is an optional number.
740
741 This will add 0 to $got_v and check if it's numerically equal to
742 $number, even if $got_v is a ref. It is useful for checking the
743 numerical value of an overloaded reference. If $tolerance is supplied
744 then this will check that $got_v and $exp_v are less than $tolerance
745 apart. This is useful when comparing floating point numbers as rounding
746 errors can make it hard or impossible for $got_v to be exactly equal to
747 $exp_v. When $tolerance is supplied, the test passes if "abs($got_v -
748 $exp_v) <= $tolerance".
749
750 Note in Perl, ""12blah" == 12" because Perl will be smart and convert
751 "12blah" into 12. You may not want this. There was a strict mode but
752 that is now gone. A "lookslike s number" test will replace it soon.
753 Until then you can usually just use the string() comparison to be more
754 strict. This will work fine for almost all situations, however it will
755 not work when <$got_v> is an overloaded value who's string and
756 numerical values differ.
757
758 bool($value)
759
760 $value is anything you like but it's probably best to use 0 or 1
761
762 This will check that $got_v and $value have the same truth value, that
763 is they will give the same result when used in boolean context, like in
764 an if() statement.
765
766 code(\&subref)
767
768 \&subref is a reference to a subroutine which will be passed a single
769 argument, it then should return a true or false and possibly a string
770
771 This will pass $got_v to the subroutine which returns true or false to
772 indicate a pass or fail. Fails can be accompanied by a diagnostic
773 string which gives an explanation of why it's a fail.
774
775 sub check_name
776 {
777 my $name = shift;
778 if ($boss->likes($name))
779 {
780 return 1;
781 }
782 else
783 {
784 return (0, "the boss doesn't like your name");
785 }
786 }
787
788 cmp_deeply("Brian", \&check_name);
789
791 my $reason = deep_diag($stack)
792
793 $stack is a value returned by cmp_details. Do not call this function
794 if cmp_details returned a true value for $ok.
795
796 deep_diag() returns a human readable string describing how the
797 comparison failed.
798
800 You've written a module to handle people and their film interests. Say
801 you have a function that returns an array of people from a query, each
802 person is a hash with 2 keys: Name and Age and the array is sorted by
803 Name. You can do
804
805 cmp_deeply(
806 $result,
807 [
808 {Name => 'Anne', Age => 26},
809 {Name => "Bill", Age => 47}
810 {Name => 'John', Age => 25},
811 ]
812 );
813
814 Soon after, your query function changes and all the results now have an
815 ID field. Now your test is failing again because you left out ID from
816 each of the hashes. The problem is that the IDs are generated by the
817 database and you have no way of knowing what each person's ID is. With
818 Test::Deep you can change your query to
819
820 cmp_deeply(
821 $result,
822 [
823 {Name => 'John', Age => 25, ID => ignore()},
824 {Name => 'Anne', Age => 26, ID => ignore()},
825 {Name => "Bill", Age => 47, ID => ignore()}
826 ]
827 );
828
829 But your test still fails. Now, because you're using a database, you no
830 longer know what order the people will appear in. You could add a sort
831 into the database query but that could slow down your application.
832 Instead you can get Test::Deep to ignore the order of the array by
833 doing a bag comparison instead.
834
835 cmp_deeply(
836 $result,
837 bag(
838 {Name => 'John', Age => 25, ID => ignore()},
839 {Name => 'Anne', Age => 26, ID => ignore()},
840 {Name => "Bill", Age => 47, ID => ignore()}
841 )
842 );
843
844 Finally person gets even more complicated and includes a new field
845 called Movies, this is a list of movies that the person has seen
846 recently, again these movies could also come back in any order so we
847 need a bag inside our other bag comparison, giving us something like
848
849 cmp_deeply(
850 $result,
851 bag(
852 {Name => 'John', Age => 25, ID => ignore(), Movies => bag(...)},
853 {Name => 'Anne', Age => 26, ID => ignore(), Movies => bag(...)},
854 {Name => "Bill", Age => 47, ID => ignore(), Movies => bag(...)}
855 )
856 );
857
859 Combining "cmp_details" and "test_diag" makes it possible to use
860 Test::Deep in your own test classes.
861
862 In a Test::Builder subclass, create a test method in the following
863 form:
864
865 sub behaves_ok {
866 my $self = shift;
867 my $expected = shift;
868 my $test_name = shift;
869
870 my $got = do_the_important_work_here();
871
872 my ($ok, $stack) = cmp_details($got, $expected);
873 unless ($Test->ok($ok, $test_name)) {
874 my $diag = deep_diag($stack);
875 $Test->diag($diag);
876 }
877 }
878
879 As the subclass defines a test class, not tests themselves, make sure
880 it uses Test::Deep::NoTest, not "Test::Deep" itself.
881
883 Currently any CODE, GLOB or IO refs will be compared using shallow(),
884 which means only their memory addresses are compared.
885
887 There is a bug in set and bag compare to do with competing SCs. It only
888 occurs when you put certain special comparisons inside bag or set
889 comparisons you don't need to worry about it. The full details are in
890 the bag() docs. It will be fixed in an upcoming version.
891
893 A special comparison (SC) is simply an object that inherits from
894 Test::Deep::Cmp. Whenever $expected_v is an SC then instead of checking
895 "$got_v eq $expected_v", we pass control over to the SC and let it do
896 it's thing.
897
898 Test::Deep exports lots of SC constructors, to make it easy for you to
899 use them in your test scripts. For example is "re("hello")" is just a
900 handy way of creating a Test::Deep::Regexp object that will match any
901 string containing "hello". So
902
903 cmp_deeply([ 'a', 'b', 'hello world'], ['a', 'b', re("^hello")]);
904
905 will check 'a' eq 'a', 'b' eq 'b' but when it comes to comparing 'hello
906 world' and "re("^hello")" it will see that $expected_v is an SC and so
907 will pass control to the Test::Deep::Regexp class by do something like
908 "$expected_v->descend($got_v)". The "descend()" method should just
909 return true or false.
910
911 This gives you enough to write your own SCs but I haven't documented
912 how diagnostics works because it's about to get an overhaul.
913
915 Test::More
916
918 Ricardo Signes <rjbs@cpan.org>
919
921 Fergal Daly <fergal@esatclear.ie>, with thanks to Michael G Schwern for
922 Test::More's is_deeply function which inspired this.
923
924 Please do not bother Fergal Daly with bug reports. Send them to the
925 maintainer (above) or submit them at the request tracker
926 <https://rt.cpan.org/Dist/Display.html?Queue=Test-Deep>.
927
929 Copyright 2003, 2004 by Fergal Daly <fergal@esatclear.ie>.
930
931 This program is free software; you can redistribute it and/or modify it
932 under the same terms as Perl itself.
933
934 See http://www.perl.com/perl/misc/Artistic.html
935
936
937
938perl v5.16.3 2012-06-16 Test::Deep(3)