1Test2::Manual::Tooling:U:sFeorrmCaotntterri(b3u)ted PerlTeDsotc2u:m:eMnatnautailo:n:Tooling::Formatter(3)
2
3
4
6 Test2::Manual::Tooling::Formatter - How to write a custom formatter, in
7 our case a JSONL formatter.
8
10 This tutorial explains a minimal formatter that outputs each event as a
11 json string on its own line. A true formatter will probably be
12 significantly more complicated, but this will give you the basics
13 needed to get started.
14
16 package Test2::Formatter::MyFormatter;
17 use strict;
18 use warnings;
19
20 use JSON::MaybeXS qw/encode_json/;
21
22 use base qw/Test2::Formatter/;
23
24 sub new { bless {}, shift }
25
26 sub encoding {};
27
28 sub write {
29 my ($self, $e, $num, $f) = @_;
30 $f ||= $e->facet_data;
31
32 print encode_json($f), "\n";
33 }
34
35 1;
36
38 use base qw/Test2::Formatter/;
39 All formatters should inherit from Test2::Formatter.
40
41 sub new { bless {}, shift }
42 Formatters need to be instantiable objects, this is a minimal
43 "new()" method.
44
45 sub encoding {};
46 For this example we leave this sub empty. In general you should
47 implement this sub to make sure you honor situations where the
48 encoding is set. Test2::V0 itself will try to set the encoding to
49 UTF8.
50
51 sub write { ... }
52 The "write()" method is the most important, each event is sent
53 here.
54
55 my ($self, $e, $num, $f) = @_;
56 The "write()" method receives 3 or 4 arguments, the fourth is
57 optional.
58
59 $self
60 The formatter itself.
61
62 $e The event being written
63
64 $num
65 The most recent assertion number. If the event being processed
66 is an assertion then this will have been bumped by 1 since the
67 last call to write. For non assertions this number is set to
68 the most recent assertion.
69
70 $f This MAY be a hashref containing all the facet data from the
71 event. More often then not this will be undefined. This is only
72 set if the facet data was needed by the hub, and it usually is
73 not.
74
75 $f ||= $e->facet_data;
76 We want to dump the event facet data. This will set $f to the facet
77 data unless we already have the facet data.
78
79 print encode_json($f), "\n";
80 This line prints the JSON encoded facet data, and a newline.
81
83 Test2::Manual - Primary index of the manual.
84
86 The source code repository for Test2-Manual can be found at
87 https://github.com/Test-More/Test2-Suite/.
88
90 Chad Granum <exodist@cpan.org>
91
93 Chad Granum <exodist@cpan.org>
94
96 Copyright 2018 Chad Granum <exodist@cpan.org>.
97
98 This program is free software; you can redistribute it and/or modify it
99 under the same terms as Perl itself.
100
101 See http://dev.perl.org/licenses/
102
103
104
105perl v5.34.0 2021-11-1T6est2::Manual::Tooling::Formatter(3)