This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade Test-Simple from version 1.302101 to 1.302103
[perl5.git] / cpan / Test-Simple / lib / Test2 / Event.pm
1 package Test2::Event;
2 use strict;
3 use warnings;
4
5 our $VERSION = '1.302103';
6
7 use Test2::Util::HashBase qw/trace -amnesty/;
8 use Test2::Util::ExternalMeta qw/meta get_meta set_meta delete_meta/;
9 use Test2::Util qw(pkg_to_file);
10
11 use Test2::EventFacet::About();
12 use Test2::EventFacet::Amnesty();
13 use Test2::EventFacet::Assert();
14 use Test2::EventFacet::Control();
15 use Test2::EventFacet::Error();
16 use Test2::EventFacet::Info();
17 use Test2::EventFacet::Meta();
18 use Test2::EventFacet::Parent();
19 use Test2::EventFacet::Plan();
20 use Test2::EventFacet::Trace();
21
22 my @FACET_TYPES = qw{
23     Test2::EventFacet::About
24     Test2::EventFacet::Amnesty
25     Test2::EventFacet::Assert
26     Test2::EventFacet::Control
27     Test2::EventFacet::Error
28     Test2::EventFacet::Info
29     Test2::EventFacet::Meta
30     Test2::EventFacet::Parent
31     Test2::EventFacet::Plan
32     Test2::EventFacet::Trace
33 };
34
35 sub FACET_TYPES() { @FACET_TYPES }
36
37 # Legacy tools will expect this to be loaded now
38 require Test2::Util::Trace;
39
40
41 sub causes_fail      { 0 }
42 sub increments_count { 0 }
43 sub diagnostics      { 0 }
44 sub no_display       { 0 }
45 sub subtest_id       { undef }
46
47 sub callback { }
48
49 sub terminate { () }
50 sub global    { () }
51 sub sets_plan { () }
52
53 sub summary { ref($_[0]) }
54
55 sub related {
56     my $self = shift;
57     my ($event) = @_;
58
59     my $tracea = $self->trace  or return undef;
60     my $traceb = $event->trace or return undef;
61
62     my $siga = $tracea->signature or return undef;
63     my $sigb = $traceb->signature or return undef;
64
65     return 1 if $siga eq $sigb;
66     return 0;
67 }
68
69 sub add_amnesty {
70     my $self = shift;
71
72     for my $am (@_) {
73         $am = {%$am} if ref($am) ne 'ARRAY';
74         $am = Test2::EventFacet::Amnesty->new($am);
75
76         push @{$self->{+AMNESTY}} => $am;
77     }
78 }
79
80 sub common_facet_data {
81     my $self = shift;
82
83     my %out;
84
85     $out{about} = {package => ref($self) || undef};
86
87     if (my $trace = $self->trace) {
88         $out{trace} = { %$trace };
89     }
90
91     $out{amnesty} = [map {{ %{$_} }} @{$self->{+AMNESTY}}]
92         if $self->{+AMNESTY};
93
94     my $key = Test2::Util::ExternalMeta::META_KEY();
95     if (my $hash = $self->{$key}) {
96         $out{meta} = {%$hash};
97     }
98
99     return \%out;
100 }
101
102 sub facet_data {
103     my $self = shift;
104
105     my $out = $self->common_facet_data;
106
107     $out->{about}->{details}    = $self->summary    || undef;
108     $out->{about}->{no_display} = $self->no_display || undef;
109
110     # Might be undef, we want to preserve that
111     my $terminate = $self->terminate;
112     $out->{control} = {
113         global    => $self->global    || 0,
114         terminate => $terminate,
115         has_callback => $self->can('callback') == \&callback ? 0 : 1,
116     };
117
118     $out->{assert} = {
119         no_debug => 1,                     # Legacy behavior
120         pass     => $self->causes_fail ? 0 : 1,
121         details  => $self->summary,
122     } if $self->increments_count;
123
124     $out->{parent} = {hid => $self->subtest_id} if $self->subtest_id;
125
126     if (my @plan = $self->sets_plan) {
127         $out->{plan} = {};
128
129         $out->{plan}->{count}   = $plan[0] if defined $plan[0];
130         $out->{plan}->{details} = $plan[2] if defined $plan[2];
131
132         if ($plan[1]) {
133             $out->{plan}->{skip} = 1 if $plan[1] eq 'SKIP';
134             $out->{plan}->{none} = 1 if $plan[1] eq 'NO PLAN';
135         }
136
137         $out->{control}->{terminate} ||= 0 if $out->{plan}->{skip};
138     }
139
140     if ($self->causes_fail && !$out->{assert}) {
141         $out->{errors} = [
142             {
143                 tag     => 'FAIL',
144                 fail    => 1,
145                 details => $self->summary,
146             }
147         ];
148     }
149
150     my %IGNORE = (trace => 1, about => 1, control => 1);
151     my $do_info = !grep { !$IGNORE{$_} } keys %$out;
152
153     if ($do_info && !$self->no_display && $self->diagnostics) {
154         $out->{info} = [
155             {
156                 tag     => 'DIAG',
157                 debug   => 1,
158                 details => $self->summary,
159             }
160         ];
161     }
162
163     return $out;
164 }
165
166 sub facets {
167     my $self = shift;
168     my $data = $self->facet_data;
169     my %out;
170
171     for my $type (FACET_TYPES()) {
172         my $key = $type->facet_key;
173         next unless $data->{$key};
174
175         if ($type->is_list) {
176             $out{$key} = [map { $type->new($_) } @{$data->{$key}}];
177         }
178         else {
179             $out{$key} = $type->new($data->{$key});
180         }
181     }
182
183     return \%out;
184 }
185
186 sub nested {
187     Carp::cluck("Use of Test2::Event->nested() is deprecated, use Test2::Event->trace->nested instead")
188         if $ENV{AUTHOR_TESTING};
189
190     $_[0]->{+TRACE}->{nested};
191 }
192
193 sub in_subtest {
194     Carp::cluck("Use of Test2::Event->in_subtest() is deprecated, use Test2::Event->trace->hid instead")
195         if $ENV{AUTHOR_TESTING};
196
197     # Return undef if we are not nested, Legacy did not return the hid if nestign was 0.
198     return undef unless $_[0]->{+TRACE}->{nested};
199
200     $_[0]->{+TRACE}->{hid};
201 }
202
203 1;
204
205 __END__
206
207 =pod
208
209 =encoding UTF-8
210
211 =head1 NAME
212
213 Test2::Event - Base class for events
214
215 =head1 DESCRIPTION
216
217 Base class for all event objects that get passed through
218 L<Test2>.
219
220 =head1 SYNOPSIS
221
222     package Test2::Event::MyEvent;
223     use strict;
224     use warnings;
225
226     # This will make our class an event subclass (required)
227     use base 'Test2::Event';
228
229     # Add some accessors (optional)
230     # You are not obligated to use HashBase, you can use any object tool you
231     # want, or roll your own accessors.
232     use Test2::Util::HashBase qw/foo bar baz/;
233
234     # Use this if you want the legacy API to be written for you, for this to
235     # work you will need to implement a facet_data() method.
236     use Test2::Util::Facets2Legacy;
237
238     # Chance to initialize some defaults
239     sub init {
240         my $self = shift;
241         # no other args in @_
242
243         $self->set_foo('xxx') unless defined $self->foo;
244
245         ...
246     }
247
248     # This is the new way for events to convey data to the Test2 system
249     sub facet_data {
250         my $self = shift;
251
252         # Get common facets such as 'about', 'trace' 'amnesty', and 'meta'
253         my $facet_data = $self->common_facet_data();
254
255         # Are you making an assertion?
256         $facet_data->{assert} = {pass => 1, details => 'my assertion'};
257         ...
258
259         return $facet_data;
260     }
261
262     1;
263
264 =head1 METHODS
265
266 =head2 GENERAL
267
268 =over 4
269
270 =item $trace = $e->trace
271
272 Get a snapshot of the L<Test2::EventFacet::Trace> as it was when this event was
273 generated
274
275 =item $bool_or_undef = $e->related($e2)
276
277 Check if 2 events are related. In this case related means their traces share a
278 signature meaning they were created with the same context (or at the very least
279 by contexts which share an id, which is the same thing unless someone is doing
280 something very bad).
281
282 This can be used to reliably link multiple events created by the same tool. For
283 instance a failing test like C<ok(0, "fail"> will generate 2 events, one being
284 a L<Test2::Event::Ok>, the other being a L<Test2::Event::Diag>, both of these
285 events are related having been created under the same context and by the same
286 initial tool (though multiple tools may have been nested under the initial
287 one).
288
289 This will return C<undef> if the relationship cannot be checked, which happens
290 if either event has an incomplete or missing trace. This will return C<0> if
291 the traces are complete, but do not match. C<1> will be returned if there is a
292 match.
293
294 =item $e->add_amnesty({tag => $TAG, details => $DETAILS});
295
296 This can be used to add amnesty to this event. Amnesty only effects failing
297 assertions in most cases, but some formatters may display them for passing
298 assertions, or even non-assertions as well.
299
300 Amnesty will prevent a failed assertion from causing the overall test to fail.
301 In other words it marks a failure as expected and allowed.
302
303 B<Note:> This is how 'TODO' is implemented under the hood. TODO is essentially
304 amnesty with the 'TODO' tag. The details are the reason for the TODO.
305
306 =back
307
308 =head2 NEW API
309
310 =over 4
311
312 =item $hashref = $e->common_facet_data();
313
314 This can be used by subclasses to generate a starting facet data hashref. This
315 will populate the hashref with the trace, meta, amnesty, and about facets.
316 These facets are nearly always produced the same way for all events.
317
318 =item $hashref = $e->facet_data()
319
320 If you do not override this then the default implementation will attempt to
321 generate facets from the legacy API. This generation is limited only to what
322 the legacy API can provide. It is recommended that you override this method and
323 write out explicit facet data.
324
325 =item $hashref = $e->facets()
326
327 This takes the hashref from C<facet_data()> and blesses each facet into the
328 proper C<Test2::EventFacet::*> subclass.
329
330 =back
331
332 =head3 WHAT ARE FACETS?
333
334 Facets are how events convey their purpose to the Test2 internals and
335 formatters. An event without facets will have no intentional effect on the
336 overall test state, and will not be displayed at all by most formatters, except
337 perhaps to say that an event of an unknown type was seen.
338
339 Facets are produced by the C<facet_data()> subroutine, which you should
340 nearly-always override. C<facet_data()> is expected to return a hashref where
341 each key is the facet type, and the value is either a hashref with the data for
342 that facet, or an array of hashref's. Some facets must be defined as single
343 hashrefs, some must be defined as an array of hashrefs, No facets allow both.
344
345 C<facet_data()> B<MUST NOT> bless the data it returns, the main hashref, and
346 nested facet hashref's B<MUST> be bare, though items contained within each
347 facet may be blessed. The data returned by this method B<should> also be copies
348 of the internal data in order to prevent accidental state modification.
349
350 C<facets()> takes the data from C<facet_data()> and blesses it into the
351 C<Test2::EventFacet::*> packages. This is rarely used however, the EventFacet
352 packages are primarily for convenience and documentation. The EventFacet
353 classes are not used at all internally, instead the raw data is used.
354
355 Here is a list of facet types by package. The packages are not used internally,
356 but are where the documentation for each type is kept.
357
358 B<Note:> Every single facet type has the C<'details'> field. This field is
359 always intended for human consumption, and when provided, should explain the
360 'why' for the facet. All other fields are facet specific.
361
362 =over 4
363
364 =item about => {...}
365
366 L<Test2::EventFacet::About>
367
368 This contains information about the event itself such as the event package
369 name. The C<details> field for this facet is an overall summary of the event.
370
371 =item assert => {...}
372
373 L<Test2::EventFacet::Assert>
374
375 This facet is used if an assertion was made. The C<details> field of this facet
376 is the description of the assertion.
377
378 =item control => {...}
379
380 L<Test2::EventFacet::Control>
381
382 This facet is used to tell the L<Test2::Event::Hub> about special actions the
383 event causes. Things like halting all testing, terminating the current test,
384 etc. In this facet the C<details> field explains why any special action was
385 taken.
386
387 B<Note:> This is how bail-out is implemented.
388
389 =item meta => {...}
390
391 L<Test2::EventFacet::Meta>
392
393 The meta facet contains all the meta-data attached to the event. In this case
394 the C<details> field has no special meaning, but may be present if something
395 sets the 'details' meta-key on the event.
396
397 =item parent => {...}
398
399 L<Test2::EventFacet::Parent>
400
401 This facet contains nested events and similar details for subtests. In this
402 facet the C<details> field will typically be the name of the subtest.
403
404 =item plan => {...}
405
406 L<Test2::EventFacet::Plan>
407
408 This facet tells the system that a plan has been set. The C<details> field of
409 this is usually left empty, but when present explains why the plan is what it
410 is, this is most useful if the plan is to skip-all.
411
412 =item trace => {...}
413
414 L<Test2::EventFacet::Trace>
415
416 This facet contains information related to when and where the event was
417 generated. This is how the test file and line number of a failure is known.
418 This facet can also help you to tell if tests are related.
419
420 In this facet the C<details> field overrides the "failed at test_file.t line
421 42." message provided on assertion failure.
422
423 =item amnesty => [{...}, ...]
424
425 L<Test2::EventFacet::Amnesty>
426
427 The amnesty facet is a list instead of a single item, this is important as
428 amnesty can come from multiple places at once.
429
430 For each instance of amnesty the C<details> field explains why amnesty was
431 granted.
432
433 B<Note:> Outside of formatters amnesty only acts to forgive a failing
434 assertion.
435
436 =item errors => [{...}, ...]
437
438 L<Test2::EventFacet::Error>
439
440 The errors facet is a list instead of a single item, any number of errors can
441 be listed. In this facet C<details> describes the error, or may contain the raw
442 error message itself (such as an exception). In perl exception may be blessed
443 objects, as such the raw data for this facet may contain nested items which are
444 blessed.
445
446 Not all errors are considered fatal, there is a C<fail> field that must be set
447 for an error to cause the test to fail.
448
449 B<Note:> This facet is unique in that the field name is 'errors' while the
450 package is 'Error'. This is because this is the only facet type that is both a
451 list, and has a name where the plural is not the same as the singular. This may
452 cause some confusion, but I feel it will be less confusing than the
453 alternative.
454
455 =item info => [{...}, ...]
456
457 L<Test2::EventFacet::Info>
458
459 The 'info' facet is a list instead of a single item, any quantity of extra
460 information can be attached to an event. Some information may be critical
461 diagnostics, others may be simply commentary in nature, this is determined by
462 the C<debug> flag.
463
464 For this facet the C<details> flag is the info itself. This info may be a
465 string, or it may be a data structure to display. This is one of the few facet
466 types that may contain blessed items.
467
468 =back
469
470 =head2 LEGACY API
471
472 =over 4
473
474 =item $bool = $e->causes_fail
475
476 Returns true if this event should result in a test failure. In general this
477 should be false.
478
479 =item $bool = $e->increments_count
480
481 Should be true if this event should result in a test count increment.
482
483 =item $e->callback($hub)
484
485 If your event needs to have extra effects on the L<Test2::Hub> you can override
486 this method.
487
488 This is called B<BEFORE> your event is passed to the formatter.
489
490 =item $num = $e->nested
491
492 If this event is nested inside of other events, this should be the depth of
493 nesting. (This is mainly for subtests)
494
495 =item $bool = $e->global
496
497 Set this to true if your event is global, that is ALL threads and processes
498 should see it no matter when or where it is generated. This is not a common
499 thing to want, it is used by bail-out and skip_all to end testing.
500
501 =item $code = $e->terminate
502
503 This is called B<AFTER> your event has been passed to the formatter. This
504 should normally return undef, only change this if your event should cause the
505 test to exit immediately.
506
507 If you want this event to cause the test to exit you should return the exit
508 code here. Exit code of 0 means exit success, any other integer means exit with
509 failure.
510
511 This is used by L<Test2::Event::Plan> to exit 0 when the plan is
512 'skip_all'. This is also used by L<Test2::Event:Bail> to force the test
513 to exit with a failure.
514
515 This is called after the event has been sent to the formatter in order to
516 ensure the event is seen and understood.
517
518 =item $msg = $e->summary
519
520 This is intended to be a human readable summary of the event. This should
521 ideally only be one line long, but you can use multiple lines if necessary. This
522 is intended for human consumption. You do not need to make it easy for machines
523 to understand.
524
525 The default is to simply return the event package name.
526
527 =item ($count, $directive, $reason) = $e->sets_plan()
528
529 Check if this event sets the testing plan. It will return an empty list if it
530 does not. If it does set the plan it will return a list of 1 to 3 items in
531 order: Expected Test Count, Test Directive, Reason for directive.
532
533 =item $bool = $e->diagnostics
534
535 True if the event contains diagnostics info. This is useful because a
536 non-verbose harness may choose to hide events that are not in this category.
537 Some formatters may choose to send these to STDERR instead of STDOUT to ensure
538 they are seen.
539
540 =item $bool = $e->no_display
541
542 False by default. This will return true on events that should not be displayed
543 by formatters.
544
545 =item $id = $e->in_subtest
546
547 If the event is inside a subtest this should have the subtest ID.
548
549 =item $id = $e->subtest_id
550
551 If the event is a final subtest event, this should contain the subtest ID.
552
553 =back
554
555 =head1 THIRD PARTY META-DATA
556
557 This object consumes L<Test2::Util::ExternalMeta> which provides a consistent
558 way for you to attach meta-data to instances of this class. This is useful for
559 tools, plugins, and other extensions.
560
561 =head1 SOURCE
562
563 The source code repository for Test2 can be found at
564 F<http://github.com/Test-More/test-more/>.
565
566 =head1 MAINTAINERS
567
568 =over 4
569
570 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
571
572 =back
573
574 =head1 AUTHORS
575
576 =over 4
577
578 =item Chad Granum E<lt>exodist@cpan.orgE<gt>
579
580 =back
581
582 =head1 COPYRIGHT
583
584 Copyright 2017 Chad Granum E<lt>exodist@cpan.orgE<gt>.
585
586 This program is free software; you can redistribute it and/or
587 modify it under the same terms as Perl itself.
588
589 See F<http://dev.perl.org/licenses/>
590
591 =cut