1Test::Stream::Plugin::CUosmeprarCeo(n3t)ributed Perl DocTuemsetn:t:aSttiroenam::Plugin::Compare(3)
2
3
4
6 Test::Stream::Plugin::Compare - Tools for comparing deep data
7 structures.
8
10 This distribution is deprecated in favor of Test2, Test2::Suite, and
11 Test2::Workflow.
12
13 See Test::Stream::Manual::ToTest2 for a conversion guide.
14
16 Test::More had is_deeply(). This library is the Test::Stream version.
17 This library can be used to compare data structures. This library goes
18 a step further though, it provides tools for building a data structure
19 specification against which you can verify your data. There are both
20 'strict' and 'relaxed' versions of the tools.
21
23 use Test::Stream 'Compare';
24
25 # Hash for demonstration purposes
26 my $some_hash = {a => 1, b => 2, c => 3};
27
28 # Strict checking, everything must match
29 is(
30 $some_hash,
31 {a => 1, b => 2, c => 3},
32 "The hash we got matches our expectations"
33 );
34
35 # Relaxed Checking, only fields we care about are checked, and we can use a
36 # regex to approximate a field.
37 like(
38 $some_hash,
39 {a => 1, b => qr/\d+/},
40 "'a' is 1, 'b' is an integer, we don't care about 'c'."
41 );
42
43 ADVANCED
44 Declarative hash, array, and objects builders are available that allow
45 you to generate specifications. These are more verbose than simply
46 providing a hash, but have the advantage that every component you
47 specify has a line number associated. This is helpful for debugging as
48 the failure output will tell you not only which fields was incorrect,
49 but also the line on which you declared the field.
50
51 use Test::Stream 'Compare' => '*';
52
53 is(
54 $some_hash,
55 hash {
56 field a => 1;
57 field b => 2;
58 field c => 3;
59 },
60 "Hash matches spec"
61 );
62
64 $bool = is($got, $expect)
65 $bool = is($got, $expect, $name)
66 $bool = is($got, $expect, $name, @diag)
67 $got is the data structure you want to check. $expect is what you
68 want $got to look like. $name is an optional name for the test.
69 @diag is optional diagnostics messages that will be printed to
70 STDERR in event of failure, they will not be displayed when the
71 comparison is successful. The boolean true/false result of the
72 comparison is returned.
73
74 This is the strict checker. The strict checker requires a perfect
75 match between $got and $expect. All hash fields must be specfied,
76 all array items must be present, etc. All
77 non-scalar/hash/array/regex references must be identical (same
78 memory address). Scalar, hash and array references will be
79 traversed and compared. Regex references will be compared to see if
80 they have the same pattern.
81
82 is(
83 $some_hash,
84 {a => 1, b => 2, c => 3},
85 "The hash we got matches our expectations"
86 );
87
88 The only exception to strictness is when it is given an $expect
89 object that was built from a specification, in which case the
90 specification determines the strictness. Strictness only applies to
91 literal values/references that are provided and converted to a
92 specification for you.
93
94 is(
95 $some_hash,
96 hash { # Note: the hash function is not exported by default
97 field a => 1;
98 field b => match(qr/\d+/); # Note: The match function is not exported by default
99 # Don't care about other fields.
100 },
101 "The hash comparison is not strict"
102 );
103
104 This works for both deep and shallow structures. For instance you
105 can use this to compare 2 strings:
106
107 is('foo', 'foo', "strings match");
108
109 Note: This is not the tool to use if you want to check if 2
110 references are the same exact reference, use ref_is() from the
111 Test::Stream::Plugin::Core plugin instead. Most of the time this
112 will work as well, however there are problems if your reference
113 contains a cyle and refers back to itself at some point, if this
114 happens an exception will be thrown to break an otherwise infinite
115 recursion.
116
117 Note: Non-reference values will be compared as strings using "eq",
118 that means '2.0' and '2' will match.
119
120 like($got, $expect)
121 like($got, $expect, $name)
122 like($got, $expect, $name, @diag)
123 $got is the data structure you want to check. $expect is what you
124 want $got to look like. $name is an optional name for the test.
125 @diag is optional diagnostics messages that will be printed to
126 STDERR in event of failure, they will not be displayed when the
127 comparison is successful. The boolean true/false result of the
128 comparison is returned.
129
130 This is the relaxed checker. This will ignore hash keys or array
131 indexes that you do not actually specify in your $expect structure.
132 In addition regex and sub references will be used as validators. If
133 you provide a regex using "qr/.../", the regex itself will be used
134 to validate the corresponding value in the $got structure. The same
135 is true for coderefs, the value is passed in as the first argument
136 (and in $_) and the sub should return a boolean value. In this
137 tool regexes will stringify the thing they are checking.
138
139 like(
140 $some_hash,
141 {a => 1, b => qr/\d+/},
142 "'a' is 1, 'b' is an integer, we don't care about other fields"
143 );
144
145 This works for both deep and shallow structures. For instance you
146 can use this to compare 2 strings:
147
148 like('foo bar', qr/^foo/, "string matches the pattern");
149
150 QUICK CHECKS
151 Note: None of these are exported by default, you need to request them.
152
153 Quick checks are a way to quickly generate a common value
154 specification. These can be used in structures passed into "is" and
155 "like" through the $expect argument.
156
157 Example:
158
159 is($foo, T(), '$foo has a true value');
160
161 $check = T()
162 This verifies that the value in the corresponding $got structure is
163 true, any true value will do.
164
165 is($foo, T(), '$foo has a true value');
166
167 is(
168 { a => 'xxx' },
169 { a => T() },
170 "The 'a' key is true"
171 );
172
173 $check = F()
174 This verifies that the value in the corresponding $got structure is
175 false, any false value will do, but the value must exist.
176
177 is($foo, F(), '$foo has a false value');
178
179 is(
180 { a => 0 },
181 { a => F() },
182 "The 'a' key is false"
183 );
184
185 It is important to note that a non-existant value does not count as
186 false, this check will generate a failing test result:
187
188 is(
189 { a => 1 },
190 { a => 1, b => F() },
191 "The 'b' key is false"
192 );
193
194 This will produce the following output:
195
196 not ok 1 - The b key is false
197 # Failed test "The 'b' key is false"
198 # at some_file.t line 10.
199 # +------+------------------+-------+---------+
200 # | PATH | GOT | OP | CHECK |
201 # +------+------------------+-------+---------+
202 # | {b} | <DOES NOT EXIST> | FALSE | FALSE() |
203 # +------+------------------+-------+---------+
204
205 In perl you can have behavior that is different for a missing key
206 vs a false key, as such it was decided not to count a completely
207 absent value as false. See the DNE() shortcut below for checking
208 that a field is missing.
209
210 If you want to check for false and/or DNE use the FDNE() check.
211
212 $check = D()
213 This is to verify that the value in the $got structure is defined.
214 Any value other than "undef" will pass.
215
216 This will pass:
217
218 is('foo', D(), 'foo is defined');
219
220 This will fail:
221
222 is(undef, D(), 'foo is defined');
223
224 $check = DNE()
225 This can be used to check that no value exists. This is useful to
226 check the end bound of an array, or to check that a key does not
227 exist in a hash.
228
229 These pass:
230
231 is(['a', 'b'], ['a', 'b', DNE()], "There is no third item in the array");
232 is({a => 1}, {a => 1, b => DNE()}, "The 'b' key does not exist in the hash");
233
234 These will fail:
235
236 is(['a', 'b', 'c'], ['a', 'b', DNE()], "No third item");
237 is({a => 1, b => 2}, {a => 1, b => DNE()}, "No 'b' key");
238
239 $check = FDNE()
240 This is a combination of F() and DNE(). This will pass for a false
241 value, or a non-existant value.
242
243 VALUE SPECIFICATIONS
244 Note: None of these are exported by default, you need to request them.
245
246 $check = string "..."
247 Verify that the value matches the given string using the "eq"
248 operator.
249
250 $check = number ...;
251 Verify that the value matches the given number using the "=="
252 operator.
253
254 $check = match qr/.../
255 Verify that the value matches the regex pattern. This form of
256 pattern check will NOT stringify references being checked.
257
258 $check = mismatch qr/.../
259 Verify that the value does not match the regex pattern. This form
260 of pattern check will NOT stringify references being checked.
261
262 $check = validator(sub{ ... })
263 $check = validator($NAME => sub{ ... })
264 $check = validator($OP, $NAME, sub{ ... })
265 The coderef is the only required argument. The coderef should check
266 that the value is what you expect, it should return a boolean true
267 or false. Optionally you can specify a name and operator that are
268 used in diagnostics, they are also provided to the sub itself as
269 named parameters.
270
271 Check the value using this sub. The sub gets the value in $_, as
272 well it received the value and several other items as named
273 parameters.
274
275 my $check = validator(sub {
276 my %params = @_;
277
278 # These both work:
279 my $got = $_;
280 my $got = $params{got};
281
282 # Check if a value exists at all
283 my $exists = $params{exists}
284
285 # What $OP (if any) did we specify when creating the validator
286 my $operator = $params{operator};
287
288 # What name (if any) did we specify when creating the validator
289 my $name = $params{name};
290
291 ...
292
293 return $bool;
294 }
295
296 $check = exact_ref($ref)
297 Check that the value is exactly the same reference as the one
298 provided.
299
300 SET BUILDERS
301 Note: None of these are exported by default, you need to request them.
302
303 my $check = check_set($check1, $check2, ...)
304 Check that the value matches ALL of the specified checks.
305
306 my $check = in_set($check1, $check2, ...)
307 Check that the value matches 1 OR MORE of the specified checks.
308
309 not_in_set($check1, $check2, ...)
310 Check that the value DOES NOT match ANY of the specified checks.
311
312 check $thing
313 Check that the value matches the specified thing.
314
315 HASH BUILDER
316 Note: None of these are exported by default, you need to request them.
317
318 $check = hash {
319 field foo => 1;
320 field bar => 2;
321
322 # Ensure the 'baz' keys does not even exist in the hash.
323 field baz => DNE();
324
325 # Ensure the key exists, but is set to undef
326 field bat => undef;
327
328 # Any check can be used
329 field boo => $check;
330
331 ...
332
333 end(); # optional, enforces that no other keys are present.
334 };
335
336 $check = hash { ... }
337 This is used to define a hash check.
338
339 field $NAME => $VAL
340 field $NAME => $CHECK
341 Specify a field check. This will check the hash key specified by
342 $NAME and ensure it matches the value in $VAL. You can put any
343 valid check in $VAL, such as the result of another call to "array {
344 ... }", DNE(), etc.
345
346 Note: This function can only be used inside a hash builder sub, and
347 must be called in void context.
348
349 end()
350 Enforce that no keys are found in the hash other than those
351 specified. This is essentually the 'use strict' of a hash check.
352 This can be used anywhere in the hash builder, though typically it
353 is placed at the end.
354
355 DNE()
356 This is a handy check that can be used with field() to ensure that
357 a field (D)oes (N)not (E)xist.
358
359 field foo => DNE();
360
361 ARRAY BUILDER
362 Note: None of these are exported by default, you need to request them.
363
364 $check = hash {
365 # Uses the next index, in this case index 0;
366 item 'a';
367
368 # Gets index 1 automatically
369 item 'b';
370
371 # Specify the index
372 item 2 => 'c';
373
374 # We skipped index 3, which means we don't care what it is.
375 item 4 => 'e';
376
377 # Gets index 5.
378 item 'f';
379
380 # Remove any REMAINING items that contain 0-9.
381 filter_items { grep {m/\D/} @_ };
382
383 # Of the remaining items (after the filter is applied) the next one
384 # (which is now index 6) should be 'g'.
385 item 6 => 'g';
386
387 item 7 => DNE; # Ensure index 7 does not exist.
388
389 end(); # Ensure no other indexes exist.
390 };
391
392 $check = array { ... }
393 item $VAL
394 item $CHECK
395 item $IDX, $VAL
396 item $IDX, $CHECK
397 Add an expected item to the array. If $IDX is not specified it will
398 automatically calculate it based on the last item added. You can
399 skip indexes, which means you do not want them to be checked.
400
401 You can provide any value to check in $VAL, or you can provide any
402 valid check object.
403
404 Note: Items MUST be added in order.
405
406 Note: This function can only be used inside an array builder sub,
407 and must be called in void context.
408
409 filter_items { my @remaining = @_; ...; return @filtered }
410 This function adds a filter, all items remaining in the array from
411 the point the filter is reached will be passed into the filter sub
412 as arguments, the sub should return only the items that should be
413 checked.
414
415 Note: This function can only be used inside an array builder sub,
416 and must be called in void context.
417
418 end()
419 Enforce that there are no indexes after the last one specified.
420 This will not force checking of skipped indexes.
421
422 DNE()
423 This is a handy check that can be used with item() to ensure that
424 an index (D)oes (N)not (E)xist.
425
426 item 5 => DNE();
427
428 META BUILDER
429 Note: None of these are exported by default, you need to request them.
430
431 my $check = meta {
432 prop blessed => 'My::Module'; # Ensure value is blessed as our package
433 prop reftype => 'HASH'; # Ensure value is a blessed hash
434 prop size => 4; # Check the number of hash keys
435 prop this => ...; # Check the item itself
436 };
437
438 meta { ... }
439 Build a meta check
440
441 prop $NAME => $VAL
442 prop $NAME => $CHECK
443 Check the property specified by $name against the value or check.
444
445 Valid properties are:
446
447 'blessed'
448 What package (if any) the thing is blessed as.
449
450 'reftype'
451 Reference type (if any) the thing is.
452
453 'this'
454 The thing itself.
455
456 'size'
457 For array references this returns the number of elements. For
458 hashes this returns the number of keys. For everything else
459 this returns undef.
460
461 OBJECT BUILDER
462 Note: None of these are exported by default, you need to request them.
463
464 my $check = object {
465 call foo => 1; # Call the 'foo' method, check the result.
466
467 # Call the specified sub-ref as a method on the object, check the
468 # result. This is useful for wrapping methods that return multiple
469 # values.
470 call sub { [ shift->get_list ] } => [...];
471
472 # This can be used to ensure a method does not exist.
473 call nope => DNE();
474
475 # Check the hash key 'foo' of the underlying reference, this only works
476 # on blessed hashes.
477 field foo => 1;
478
479 # Check the value of index 4 on the underlying reference, this only
480 # works on blessed arrays.
481 item 4 => 'foo';
482
483 # Check the meta-property 'blessed' of the object.
484 prop blessed => 'My::Module';
485
486 # Ensure only the specified hash keys or array indexes are present in
487 # the underlying hash. Has no effect on meta-property checks or method
488 # checks.
489 end();
490 };
491
492 $check = object { ... }
493 Specify an object check for use in comparisons.
494
495 call $METHOD_NAME => $RESULT
496 call $METHOD_NAME => $CHECK
497 call sub { ... }, $RESULT
498 call sub { ... }, $CHECK
499 Call the specified method (or coderef) and verify the result. The
500 coderef form us useful if you want to check a method that returns a
501 list as it allows you to wrap the result in a reference.
502
503 my $ref = sub {
504 my $self = shift;
505 my @result = $self->get_list;
506 return \@result;
507 };
508
509 call $ref => [ ... ];
510
511 field $NAME => $VAL
512 Works just like it does for hash checks.
513
514 item $VAL
515 item $IDX, $VAL
516 Works just like it does for array checks.
517
518 prop $NAME => $VAL
519 prop $NAME => $CHECK
520 Check the property specified by $name against the value or check.
521
522 Valid properties are:
523
524 'blessed'
525 What package (if any) the thing is blessed as.
526
527 'reftype'
528 Reference type (if any) the thing is.
529
530 'this'
531 The thing itself.
532
533 'size'
534 For array references this returns the number of elements. For
535 hashes this returns the number of keys. For everything else
536 this returns undef.
537
538 DNE()
539 Can be used with "item", or "field" to ensure the hash field or
540 array index does not exist. Can also be used with "call" to ensure
541 a method does not exist.
542
543 end()
544 Turn on strict array/hash checking, that is ensure that no extra
545 keys/indexes are present.
546
547 EVENT BUILDER
548 Note: None of these are exported by default, you need to request them.
549
550 Check that we got an event of a specified type:
551
552 my $check = event 'Ok';
553
554 Check for details about the event:
555
556 my $check = event Ok => sub {
557 # Check for a failure
558 call pass => 0;
559
560 # Effective pass after TODO/SKIP are accounted for.
561 call effective_pass => 1;
562
563 # Check the diagnostics
564 call diag => [ match qr/Failed test foo/ ];
565
566 # Check the file the event reports to
567 prop file => 'foo.t';
568
569 # Check the line number the event reports o
570 prop line => '42';
571
572 # You can check the todo/skip values as well:
573 prop skip => 'broken';
574 prop todo => 'fixme';
575
576 # Thread-id and process-id where event was generated
577 prop tid => 123;
578 prop pid => 123;
579 };
580
581 You can also provide a fully qualified event package with the '+'
582 prefix:
583
584 my $check = event '+My::Event' => sub { ... }
585
586 $check = event $TYPE;
587 $check = event $TYPE => sub { ... };
588 This works just like an object builder. In addition to supporting
589 everything the object check supports, you also have to specify the
590 event type, and many extra meta-properties are available.
591
592 Extra properties are:
593
594 'file'
595 File name to which the event reports (for use in diagnostics).
596
597 'line'
598 Line number to which the event reports (for use in
599 diagnostics).
600
601 'package'
602 Package to which the event reports (for use in diagnostics).
603
604 'subname'
605 Sub that was called to generate the event (example: ok()).
606
607 'skip'
608 Set to the skip value if the result was generated by skipping
609 tests.
610
611 'todo'
612 Set to the todo value if TODO was set when the event was
613 generated.
614
615 'trace'
616 The 'at file foo.t line 42' string that will be used in
617 diagnostics.
618
619 'tid'
620 Thread id in which the event was generated.
621
622 'pid'
623 PRocess id in which the event was generated.
624
626 The source code repository for Test::Stream can be found at
627 http://github.com/Test-More/Test-Stream/.
628
630 Chad Granum <exodist@cpan.org>
631
633 Chad Granum <exodist@cpan.org>
634
636 Copyright 2015 Chad Granum <exodist7@gmail.com>.
637
638 This program is free software; you can redistribute it and/or modify it
639 under the same terms as Perl itself.
640
641 See http://dev.perl.org/licenses/
642
643
644
645perl v5.38.0 2023-07-21 Test::Stream::Plugin::Compare(3)