Tester.pm

filter: Statementstmt 86.4% 255 / 295 Branchbran 55.3% 52 / 94 Conditioncond 37.9% 11 / 29 MC/DCmcdc 0.0% 0 / 17 Subroutinesub 93.7% 60 / 64 Podpod 70.5% 12 / 17 totaltotal 75.5% 390 / 516 CC 70 SCAR 19.7
CC
70
Cov
76%
request
25.3
_get_jwt_config
20.7
download_uri_for
15.3
CRAP 7.2
« Tester/UA/Async.pm ↑ Summary Tester/Role/SentenceCollection.pm »
1 package JMAP::Tester 0.113;
2 # ABSTRACT: a JMAP client made for testing JMAP servers
3  
4 2 ▶use v5.20.0;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 2 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 2 ▶use experimental 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 2 ▶use Crypt::Misc qw(decode_b64u encode_b64u);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶use Crypt::Mac::HMAC qw(hmac_b64u);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶use Encode qw(encode_utf8);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶use HTTP::Request;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 2 ▶use JMAP::Tester::Abort 'abort';
Subroutine BEGIN: called CC=1 SCAR=0.0
17 2 ▶use JMAP::Tester::Logger::Null;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶use JMAP::Tester::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶use JMAP::Tester::Result::Auth;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶use JMAP::Tester::Result::Download;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 2 ▶use JMAP::Tester::Result::Failure;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 2 ▶use JMAP::Tester::Result::Logout;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 2 ▶use JMAP::Tester::Result::Upload;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 2 ▶use Module::Runtime ();
Subroutine BEGIN: called CC=1 SCAR=0.0
25 2 ▶use Params::Util qw(_HASH0 _ARRAY0);
Subroutine BEGIN: called CC=1 SCAR=0.0
26 2 ▶use Safe::Isa;
Subroutine BEGIN: called CC=1 SCAR=0.0
27 2 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
28 2 ▶use URI::QueryParam;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 2 ▶use URI::Escape qw(uri_escape);
Subroutine BEGIN: called CC=1 SCAR=0.0
30  
31 2 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
32  
33 #pod =head1 OVERVIEW
34 #pod
35 #pod B<Achtung!> This library is in its really early days, so use it with that in
36 #pod mind.
37 #pod
38 #pod JMAP::Tester is for testing JMAP servers. Okay? Okay!
39 #pod
40 #pod JMAP::Tester calls the whole thing you get back from a JMAP server a "response"
41 #pod if it's an HTTP 200. Every JSON Array (of three entries -- go read the spec if
42 #pod you need to!) is called a L<Sentence|JMAP::Tester::Response::Sentence>. Runs
43 #pod of Sentences with the same client id are called
44 #pod L<Paragraphs|JMAP::Tester::Response::Paragraph>.
45 #pod
46 #pod You use the test client like this:
47 #pod
48 #pod my $jtest = JMAP::Tester->new({
49 #pod api_uri => 'https://jmap.local/account/123',
50 #pod });
51 #pod
52 #pod my $response = $jtest->request([
53 #pod [ 'Mailbox/get' => {} ],
54 #pod [ 'Email/changes' => { sinceState => "123" } ],
55 #pod ]);
56 #pod
57 #pod # This returns two Paragraph objects if there are exactly two paragraphs.
58 #pod # Otherwise, it throws an exception.
59 #pod my ($mbx_p, $msg_p) = $response->assert_n_paragraphs(2);
60 #pod
61 #pod # These get the single Sentence of each paragraph, asserting that there is
62 #pod # exactly one Sentence in each Paragraph, and that it's of the given type.
63 #pod my $mbx = $mbx_p->single('Mailbox/get');
64 #pod my $msg = $msg_p->single('Email/changes');
65 #pod
66 #pod is( @{ $mbx->arguments->{list} }, 10, "we expect 10 mailboxes");
67 #pod ok( ! $msg->arguments->{hasMoreChanges}, "we got all the msg updates needed");
68 #pod
69 #pod By default, all the structures returned have been passed through
70 #pod L<JSON::Typist>, so you may want to strip their type data before using normal
71 #pod Perl code on them. You can do that with:
72 #pod
73 #pod my $struct = $response->as_triples; # gets the complete JSON data
74 #pod $jtest->strip_json_types( $struct ); # strips all the JSON::Typist types
75 #pod
76 #pod Or more simply:
77 #pod
78 #pod my $struct = $response->as_stripped_triples;
79 #pod
80 #pod There is also L<JMAP::Tester::Response/"as_stripped_pairs">.
81 #pod
82 #pod =cut
83  
84 #pod =attr should_return_futures
85 #pod
86 #pod If true, this indicates that the various network-accessing methods should
87 #pod return L<Future> objects rather than immediate results.
88 #pod
89 #pod =cut
90  
91 2 has should_return_futures => (
92 is => 'ro',
93 default => 0,
94 );
95  
96 # When something doesn't work — not an individual method call, but the whole
97 # HTTP call, somehow — then the future will fail, and the failure might be a
98 # JMAP tester failure object, meaning we semi-expected it, or it might be some
99 # other crazy failure, meaning we had no way of seeing it coming.
100 #
101 # We use Future->fail because that way we can use ->else in chains to only act
102 # on successful HTTP calls. At the end, it's fine if you're expecting a future
103 # and can know that a failed future is a fail and a done future is okay. In the
104 # old calling convention, though, you expect to get a success/fail object as
105 # long as you got an HTTP response. Otherwise, you'd get an exception.
106 #
107 # $Failsafe emulates that. Just before we return from a future-returning
108 # method, and if the client is not set to return futures, we do this:
109 #
110 # * successful futures return their payload, the Result object
111 # * failed futures that contain a JMAP tester Failure return the failure
112 # * other failed futures die, like they would if you called $failed_future->get
113 12 ▶my $Failsafe = sub {
Subroutine __ANON__: called CC=1 SCAR=0.1
114 2 ▶ $_[0]->else_with_f(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
115 2 my ($f, $fail) = @_;
116 2 ▶ return $fail->$_isa('JMAP::Tester::Result::Failure') ? Future->done($fail)
Branch: 1 branch
BranchTrueFalseTotal
$fail->$JMAP::Tester::_isa('JMAP::Tester::Result::Failure') ? : 2 0 2
117 : $f;
118 12 });
119 2 };
120  
121 #pod =attr json_pretty
122 #pod
123 #pod This is a boolean which, if true, will cause the JMAP::Tester object to
124 #pod canonicalize and pretty-print generated JSON.
125 #pod
126 #pod =cut
127  
128 2 has json_pretty => (
129 is => 'ro',
130 default => 0,
131 );
132  
133 #pod =attr json_codec
134 #pod
135 #pod This is an object that implements the JSON API, roughly meaning that it
136 #pod provides C<encode> and C<decode> methods. You probably won't need to use
137 #pod anything but the default version outside of exceptional cases.
138 #pod
139 #pod =cut
140  
141 has json_codec => (
142 is => 'bare',
143 reader => '_json_codec',
144 lazy => 1,
145 handles => {
146 json_decode => 'decode',
147 },
148 4 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
149 4 my ($self) = @_;
150  
151 4 require JSON::XS;
152 4 my $json = JSON::XS->new->utf8->convert_blessed;
153  
154 4 ▶ if ($self->json_pretty) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->json_pretty) 0 4 4
155 0 $json = $json->pretty->canonical;
156 }
157 4 return $json;
158 },
159 2 );
160  
161 4 ▶sub json_encode ($self, $data) {
Subroutine json_encode: called CC=2 SCAR=6.9
Pod undocumented
162 4 ▶ if ($data->$_isa('JMAP::Tester::JSONLiteral')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data->$JMAP::Tester::_isa("JMAP::Tester::JSONLiteral")) 1 3 4
163 1 return $data->bytes;
164 }
165  
166 3 $self->_json_codec->encode($data);
167 }
168  
169 #pod =attr use_json_typists
170 #pod
171 #pod This attribute governs the conversion of JSON data into typed objects, using
172 #pod L<JSON::Typist>. This attribute is true by default.
173 #pod
174 #pod =cut
175  
176 2 has use_json_typist => (
177 is => 'ro',
178 default => 1,
179 );
180  
181 has _json_typist => (
182 is => 'ro',
183 handles => {
184 strip_json_types => 'strip_types',
185 },
186 5 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
187 5 require JSON::Typist;
188 5 return JSON::Typist->new;
189 },
190 2 );
191  
192 9 ▶sub apply_json_types ($self, $data) {
Subroutine apply_json_types: called CC=2 SCAR=6.9
Pod undocumented
193 9 ▶ return $data unless $self->use_json_typist;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->use_json_typist 1 8 9
194 8 return $self->_json_typist->apply_types($data);
195 }
196  
197 2 for my $type (qw(api authentication download upload)) {
198 8 has "$type\_uri" => (
199 is => 'rw',
200 predicate => "has_$type\_uri",
201 clearer => "clear_$type\_uri",
202 );
203 }
204  
205 has ua => (
206 is => 'ro',
207 5 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
208 5 require JMAP::Tester::UA::LWP;
209 5 JMAP::Tester::UA::LWP->new;
210 },
211 2 );
212  
213 #pod =attr ident
214 #pod
215 #pod This is a (preferably short) string that can be used to identify this
216 #pod JMAP::Tester object. It's used in request logging, so that client telemetry
217 #pod can be correlated to a specific client object. If no ident is given, an ident
218 #pod will be generated, but it is not guaranteed to be unique.
219 #pod
220 #pod =cut
221  
222 has ident => (
223 is => 'ro',
224 5 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
225 5 my ($self) = @_;
226 5 state $ident_counter = 0;
227 5 return "jmap-tester-" . (++$ident_counter);
228 }
229 2 );
230  
231 #pod =attr default_using
232 #pod
233 #pod This is an arrayref of strings that specify which capabilities the client
234 #pod wishes to use. (See L<https://jmap.io/spec-core.html#the-request-object>
235 #pod for more info). By default, JMAP::Tester will not send a 'using' parameter.
236 #pod
237 #pod =cut
238  
239 2 has default_using => (
240 is => 'rw',
241 predicate => '_has_default_using',
242 );
243  
244 #pod =attr default_arguments
245 #pod
246 #pod This is a hashref of arguments to be put into each method call. It's
247 #pod especially useful for setting a default C<accountId>. Values given in methods
248 #pod passed to C<request> will override defaults. If the value is a reference to
249 #pod C<undef>, then no value will be passed for that key.
250 #pod
251 #pod In other words, in this situation:
252 #pod
253 #pod my $tester = JMAP::Tester->new({
254 #pod ...,
255 #pod default_arguments => { a => 1, b => 2, c => 3 },
256 #pod });
257 #pod
258 #pod $tester->request([
259 #pod [ eatPies => { a => 100, b => \undef } ],
260 #pod ]);
261 #pod
262 #pod The request will effectively be:
263 #pod
264 #pod [ [ "eatPies", { "a": 100, "c": 3 }, "a" ] ]
265 #pod
266 #pod =cut
267  
268 has default_arguments => (
269 is => 'rw',
270 5 ▶ default => sub { {} },
Subroutine __ANON__: called CC=1 SCAR=0.0
271 2 );
272  
273 #pod =attr accounts
274 #pod
275 #pod This method will return a list of pairs mapping accountIds to accounts
276 #pod as provided by the client session object if any have been configured.
277 #pod
278 #pod =cut
279  
280 2 has _accounts => (
281 is => 'rw',
282 init_arg => undef,
283 predicate => '_has_accounts',
284 );
285  
286 1 ▶sub accounts ($self) {
Subroutine accounts: called CC=2 SCAR=7.1
Pod documented
287 1 ▶ return unless $self->_has_accounts;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_has_accounts 0 1 1
288 1 return %{ $self->_accounts }
289 }
290  
291 #pod =method primary_account_for
292 #pod
293 #pod my $account_id = $tester->primary_account_for($using);
294 #pod
295 #pod This returns the primary accountId to be used for the given capability, or
296 #pod undef if none is available. This is only useful if the tester has been
297 #pod configured from a client session.
298 #pod
299 #pod =cut
300  
301 2 has _primary_accounts => (
302 is => 'rw',
303 init_arg => undef,
304 predicate => '_has_primary_accounts',
305 );
306  
307 4 ▶sub primary_account_for ($self, $using) {
Subroutine primary_account_for: called CC=2 SCAR=7.2
Pod documented
308 4 ▶ return unless $self->_has_primary_accounts;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_has_primary_accounts 0 4 4
309 4 return $self->_primary_accounts->{ $using };
310 }
311  
312 #pod =method request
313 #pod
314 #pod my $result = $jtest->request([
315 #pod [ methodOne => { ... } ],
316 #pod [ methodTwo => { ... } ],
317 #pod ]);
318 #pod
319 #pod This method accepts either an arrayref of method calls or a hashref with a
320 #pod C<methodCalls> key. It sends the calls to the JMAP server and returns a
321 #pod result.
322 #pod
323 #pod For each method call, if there's a third element (a I<client id>) then it's
324 #pod left as-is. If no client id is given, one is generated. You can mix explicit
325 #pod and autogenerated client ids. They will never conflict.
326 #pod
327 #pod The arguments to methods are JSON-encoded with a L<JSON::Typist>-aware encoder,
328 #pod so JSON::Typist types can be used to ensure string or number types in the
329 #pod generated JSON. If an argument is a reference to C<undef>, it will be removed
330 #pod before the method call is made. This lets you override a default by omission.
331 #pod
332 #pod The return value is an object that does the L<JMAP::Tester::Result> role,
333 #pod meaning it's got an C<is_success> method that returns true or false. For now,
334 #pod at least, failures are L<JMAP::Tester::Result::Failure> objects. More refined
335 #pod failure objects may exist in the future. Successful requests return
336 #pod L<JMAP::Tester::Response> objects.
337 #pod
338 #pod Before the JMAP request is made, each triple is passed to a method called
339 #pod C<munge_method_triple>, which can tweak the method however it likes.
340 #pod
341 #pod This method respects the C<should_return_futures> attributes of the
342 #pod JMAP::Tester object, and in futures mode will return a future that will resolve
343 #pod to the Result.
344 #pod
345 #pod =cut
346  
347 4 ▶sub request ($self, $input_request) {
Subroutine request: called CC=17 SCAR=32.3
Pod documented
348 4 ▶ Carp::confess("can't perform request: no api_uri configured")
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_api_uri 0 4 4
349 unless $self->has_api_uri;
350  
351 4 state $ident = 'a';
352 4 my %seen;
353 my @suffixed;
354  
355 4 my %default_args = %{ $self->default_arguments };
356  
357 4 my $request;
358  
359 4 ▶ if ($input_request->$_isa('JMAP::Tester::JSONLiteral')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($input_request->$JMAP::Tester::_isa('JMAP::Tester::JSONLiteral')) { } 1 3 4
360 # We'll be "encoding" (read: not really encoding) this directly, with no
361 # munging of the content, no creation of call ids, etc.
362 1 $request = $input_request;
363 } else {
364 3 ▶ $request = _ARRAY0($input_request)
Branch: 1 branch
BranchTrueFalseTotal
&_ARRAY0($input_request) ? : 3 0 3
365 ? { methodCalls => $input_request }
366 : { %$input_request };
367  
368 3 for my $call (@{ $request->{methodCalls} }) {
369 3 my $copy = [ @$call ];
370 3 ▶ if (defined $copy->[2]) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $copy->[2]) { } 0 3 3
371 0 $seen{$call->[2]}++;
372 } else {
373 3 my $next;
374 3 ▶ do { $next = $ident++ } until ! $seen{$ident}++;
Branch: 1 branch
BranchTrueFalseTotal
not $seen{$ident}++ or do { do { $next = $ident++ } } 3 0 3
375 3 $copy->[2] = $next;
376 }
377  
378 my %arg = (
379 %default_args,
380 3 ▶ %{ $copy->[1] // {} },
Condition50%1/2
$copy->[1] // {}
l!l
30
MC/DC0%0/1
$copy->[1] // {}
$copy->[1]
Truth table50%1/2
A
A= $copy->[1]
Aresult
11
00
381 );
382  
383 3 for my $key (keys %arg) {
384 3 ▶ if ( ref $arg{$key}
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arg{$key} and ref $arg{$key} eq "SCALAR" and not defined ${$arg{$key};}) 0 3 3
Condition50%3/6
ref $arg{$key} and ref $arg{$key} eq "SCALAR" and not defined ${$arg{$key};}
!ll&&!rl&&r
300
ref $arg{$key} and ref $arg{$key} eq "SCALAR"
!ll&&!rl&&r
210
MC/DC0%0/3
ref $arg{$key} and ref $arg{$key} eq "SCALAR" and not defined ${$arg{$key};}
ref $arg{$key} ref $arg{$key} eq "SCALAR" not defined ${$arg{$key};}
Truth table50%2/4
A and B and not(C)
A= ref $arg{$key}B= ref $arg{$key} eq "SCALAR"C= not defined ${$arg{$key};}
ABCresult
0XX0
10X0
1100
1111
385 && ref $arg{$key} eq 'SCALAR'
386 0 && ! defined ${ $arg{$key} }
387 ) {
388 0 delete $arg{$key};
389 }
390 }
391  
392 3 $copy->[1] = \%arg;
393  
394 # Originally, I had a second argument, \%stash, which was the same for the
395 # whole ->request, so you could store data between munges. Removed, for
396 # now, as YAGNI. -- rjbs, 2019-03-04
397 3 $self->munge_method_triple($copy);
398  
399 3 push @suffixed, $copy;
400 }
401  
402 3 $request->{methodCalls} = \@suffixed;
403  
404 $request = $request->{methodCalls}
405 3 ▶ if $ENV{JMAP_TESTER_NO_WRAPPER} && _ARRAY0($input_request);
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"JMAP_TESTER_NO_WRAPPER"} and &_ARRAY0($input_request) 0 3 3
Condition33%1/3
$ENV{"JMAP_TESTER_NO_WRAPPER"} and &_ARRAY0($input_request)
!ll&&!rl&&r
300
MC/DC0%0/2
$ENV{"JMAP_TESTER_NO_WRAPPER"} and &_ARRAY0($input_request)
$ENV{"JMAP_TESTER_NO_WRAPPER"} &_ARRAY0($input_request)
Truth table33%1/3
A and B
A= $ENV{"JMAP_TESTER_NO_WRAPPER"}B= &_ARRAY0($input_request)
ABresult
0X0
100
111
406  
407 3 ▶ if ($self->_has_default_using && ! exists $request->{using}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_default_using and not exists $request->{"using"}) 0 3 3
Condition33%1/3
$self->_has_default_using and not exists $request->{"using"}
!ll&&!rl&&r
300
MC/DC0%0/2
$self->_has_default_using and not exists $request->{"using"}
$self->_has_default_using not exists $request->{"using"}
Truth table33%1/3
A and not(B)
A= $self->_has_default_usingB= not exists $request->{"using"}
ABresult
0X0
100
111
408 0 $request->{using} = $self->default_using;
409 }
410 }
411  
412 4 my $json = $self->json_encode($request);
413  
414 4 my $post = HTTP::Request->new(
415 POST => $self->api_uri,
416 [
417 'Content-Type' => 'application/json',
418 $self->_maybe_auth_header,
419 ],
420 $json,
421 );
422  
423 4 my $res_f = $self->ua->request($self, $post, jmap => {
424 jmap_array => \@suffixed,
425 json => $json,
426 });
427  
428 4 ▶ my $future = $res_f->then(sub {
Subroutine __ANON__: called CC=2 SCAR=8.4
429 4 my ($res) = @_;
430  
431 4 ▶ unless ($res->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->is_success) 0 4 4
432 0 $self->_logger->log_jmap_response($self, { http_response => $res });
433 0 return Future->fail(
434 JMAP::Tester::Result::Failure->new({
435 http_response => $res,
436 diagnostic_dumper => $self->default_diagnostic_dumper,
437 })
438 );
439 }
440  
441 4 return Future->done($self->_jresponse_from_hresponse($res));
442 4 });
443  
444 4 ▶ return $self->should_return_futures ? $future : $future->$Failsafe->get;
Branch: 1 branch
BranchTrueFalseTotal
$self->should_return_futures ? : 0 4 4
445 }
446  
447 3 ▶sub munge_method_triple {}
Subroutine munge_method_triple: called CC=1 SCAR=0.0
Pod undocumented
448  
449 8 ▶sub response_class { 'JMAP::Tester::Response' }
Subroutine response_class: called CC=1 SCAR=0.0
Pod undocumented
450  
451 8 ▶sub _jresponse_from_hresponse ($self, $http_res) {
Subroutine _jresponse_from_hresponse: called CC=3 SCAR=11.1
452 # TODO check that it's really application/json!
453 8 my $json = $http_res->decoded_content;
454  
455 8 my $data = $self->apply_json_types( $self->json_decode( $json ) );
456  
457 8 my ($items, $props);
458 8 ▶ if (_HASH0($data)) {
Branch: 2 branches
BranchTrueFalseTotal
if (&_HASH0($data)) { } 7 1 8
elsif (&_ARRAY0($data)) { } 1 0 1
459 7 $props = $data;
460 7 $items = $props->{methodResponses};
461 } elsif (_ARRAY0($data)) {
462 1 $props = {};
463 1 $items = $data;
464 } else {
465 0 abort("illegal response to JMAP request: $data");
466 }
467  
468 8 $self->_logger->log_jmap_response(
469 $self,
470 {
471 jmap_array => $items,
472 json => $json,
473 http_response => $http_res,
474 }
475 );
476  
477 8 return $self->response_class->new({
478 items => $items,
479 http_response => $http_res,
480 wrapper_properties => $props,
481 diagnostic_dumper => $self->default_diagnostic_dumper,
482 });
483 }
484  
485 has _logger => (
486 is => 'ro',
487 5 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=18.1
488 5 ▶ if ($ENV{JMAP_TESTER_LOGGER}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ENV{"JMAP_TESTER_LOGGER"}) 0 5 5
489 0 my ($class, $filename) = split /:/, $ENV{JMAP_TESTER_LOGGER};
490 0 $class = "JMAP::Tester::Logger::$class";
491 0 Module::Runtime::require_module($class);
492  
493 0 ▶ return $class->new({
Condition0%0/2
$filename // "jmap-tester-{T}-{PID}.log"
l!l
00
MC/DC0%0/1
$filename // "jmap-tester-{T}-{PID}.log"
$filename
Truth table0%0/2
A
A= $filename
Aresult
11
00
494 writer => $filename // 'jmap-tester-{T}-{PID}.log'
495 });
496 }
497  
498 5 JMAP::Tester::Logger::Null->new({ writer => \undef });
499 },
500 2 );
501  
502 #pod =method upload
503 #pod
504 #pod my $result = $tester->upload(\%arg);
505 #pod
506 #pod Required arguments are:
507 #pod
508 #pod accountId - the account for which we're uploading (no default)
509 #pod type - the content-type we want to provide to the server
510 #pod blob - the data to upload. Must be a reference to a string
511 #pod
512 #pod This uploads the given blob.
513 #pod
514 #pod The return value will either be a L<failure
515 #pod object|JMAP::Tester::Result::Failure> or an L<upload
516 #pod result|JMAP::Tester::Result::Upload>.
517 #pod
518 #pod This method respects the C<should_return_futures> attributes of the
519 #pod JMAP::Tester object, and in futures mode will return a future that will resolve
520 #pod to the Result.
521 #pod
522 #pod =cut
523  
524 1 ▶sub upload ($self, $arg) {
Subroutine upload: called CC=6 SCAR=18.4
Pod documented
525 # TODO: support blob as handle or sub -- rjbs, 2016-11-17
526  
527 1 my $uri = $self->upload_uri;
528  
529 1 ▶ Carp::confess("can't upload without upload_uri")
Branch: 1 branch
BranchTrueFalseTotal
unless $uri 0 1 1
530 unless $uri;
531  
532 1 for my $param (qw(accountId type blob)) {
533 3 my $value = $arg->{ $param };
534  
535 3 ▶ Carp::confess("missing required parameter $param")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 3 3
536 unless defined $value;
537  
538 3 ▶ if ($param eq 'accountId') {
Branch: 1 branch
BranchTrueFalseTotal
if ($param eq "accountId") 1 2 3
539 1 $uri =~ s/\{$param\}/$value/g;
540 }
541 }
542  
543 my $post = HTTP::Request->new(
544 POST => $uri,
545 [
546 'Content-Type' => $arg->{type},
547 $self->_maybe_auth_header,
548 ],
549 1 ${ $arg->{blob} },
550 );
551  
552 1 my $res_f = $self->ua->request($self, $post, 'upload');
553  
554 1 ▶ my $future = $res_f->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.5
555 1 my ($res) = @_;
556  
557 1 ▶ unless ($res->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->is_success) 0 1 1
558 0 $self->_logger->log_upload_response($self, { http_response => $res });
559 0 return Future->fail(
560 JMAP::Tester::Result::Failure->new({
561 http_response => $res,
562 diagnostic_dumper => $self->default_diagnostic_dumper,
563 })
564 );
565 }
566  
567 1 my $json = $res->decoded_content;
568 1 my $blob = $self->apply_json_types( $self->json_decode( $json ) );
569  
570 1 $self->_logger->log_upload_response(
571 $self,
572 {
573 json => $json,
574 blob_struct => $blob,
575 http_response => $res,
576 }
577 );
578  
579 1 return Future->done(
580 JMAP::Tester::Result::Upload->new({
581 http_response => $res,
582 payload => $blob,
583 diagnostic_dumper => $self->default_diagnostic_dumper,
584 })
585 );
586 1 });
587  
588 1 ▶ return $self->should_return_futures ? $future : $future->$Failsafe->get;
Branch: 1 branch
BranchTrueFalseTotal
$self->should_return_futures ? : 0 1 1
589 }
590  
591 #pod =method download
592 #pod
593 #pod my $result = $tester->download(\%uri_arg, \%other_arg);
594 #pod
595 #pod The first hashref provides values that go into the download URI:
596 #pod
597 #pod blobId - the blob to download (no default)
598 #pod accountId - the account for which we're downloading (no default)
599 #pod type - the content-type we want the server to provide back (no default)
600 #pod name - the name we want the server to provide back (default: "download")
601 #pod
602 #pod If the download URI template has a C<blobId>, C<accountId>, or C<type>
603 #pod placeholder but no argument for that is given to C<download>, an exception
604 #pod will be thrown.
605 #pod
606 #pod The second hashref, which is optional, provides other arguments to the method.
607 #pod Right now, there is only one, B<which will go away>. The argument is only here
608 #pod for legacy purposes, specifically for the Cyrus IMAP project, and may be
609 #pod removed B<at any time>.
610 #pod
611 #pod accept - the value of the Accept header to use when downloading
612 #pod
613 #pod The return value will either be a L<failure
614 #pod object|JMAP::Tester::Result::Failure> or an L<upload
615 #pod result|JMAP::Tester::Result::Download>.
616 #pod
617 #pod This method respects the C<should_return_futures> attributes of the
618 #pod JMAP::Tester object, and in futures mode will return a future that will resolve
619 #pod to the Result.
620 #pod
621 #pod =cut
622  
623 2 my %DL_DEFAULT = (name => 'download');
624  
625 0 ▶sub _jwt_sub_param_from_uri ($self, $to_sign) {
Subroutine _jwt_sub_param_from_uri: not called CC=1 SCAR=6.9
626 0 "$to_sign";
627 }
628  
629 1 ▶sub download_uri_for ($self, $arg) {
Subroutine download_uri_for: called CC=8 SCAR=27.3
Pod undocumented
630 1 ▶ Carp::confess("can't compute download URI without configured download_uri")
Branch: 1 branch
BranchTrueFalseTotal
unless my $uri = $self->download_uri 0 1 1
631 unless my $uri = $self->download_uri;
632  
633 1 for my $param (qw(blobId accountId name type)) {
634 4 ▶ next unless $uri =~ /\{$param\}/;
Branch: 1 branch
BranchTrueFalseTotal
unless $uri =~ /\{$param\}/u 0 4 4
635 4 ▶ my $value = $arg->{ $param } // $DL_DEFAULT{ $param };
Condition33%1/3
$arg->{$param} // $DL_DEFAULT{$param}
l!l&&r!l&&!r
400
MC/DC0%0/2
$arg->{$param} // $DL_DEFAULT{$param}
$arg->{$param} $DL_DEFAULT{$param}
Truth table33%1/3
A // B
A= $arg->{$param}B= $DL_DEFAULT{$param}
ABresult
1X1
011
000
636  
637 4 ▶ Carp::confess("missing required template parameter $param")
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 4 4
638 unless defined $value;
639  
640 4 ▶ if ($param eq 'name') {
Branch: 1 branch
BranchTrueFalseTotal
if ($param eq "name") 1 3 4
641 1 $value = uri_escape($value);
642 }
643  
644 4 $uri =~ s/\{$param\}/$value/g;
645 }
646  
647 1 ▶ if (my $jwtc = $self->_get_jwt_config) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $jwtc = $self->_get_jwt_config) 0 1 1
648 0 my $to_get = URI->new($uri);
649 0 my $to_sign = $to_get->clone->canonical;
650  
651 0 $to_sign->query(undef);
652  
653 0 my $header = encode_b64u( $self->json_encode({
654 alg => 'HS256',
655 typ => 'JWT',
656 }) );
657  
658 0 my $iat = time;
659 0 $iat = $iat - ($iat % 3600);
660  
661 my $payload = encode_b64u( $self->json_encode({
662 iss => $jwtc->{signingId},
663 0 iat => $iat,
664 sub => $self->_jwt_sub_param_from_uri($to_sign),
665 }) );
666  
667 my $signature = hmac_b64u(
668 'SHA256',
669 0 decode_b64u($jwtc->{signingKey}),
670 "$header.$payload",
671 );
672  
673 0 $to_get->query_param(access_token => "$header.$payload.$signature");
674 0 $uri = "$to_get";
675 }
676  
677 1 return $uri;
678 }
679  
680 1 ▶sub download ($self, $uri_arg, $arg = undef) {
Subroutine download: called CC=5 SCAR=16.8
Pod documented
681 1 ▶ $arg //= {};
Condition50%1/2
$arg //= {}
l!l
01
MC/DC0%0/1
$arg //= {}
$arg
Truth table50%1/2
A
A= $arg
Aresult
11
00
682  
683 1 my $uri = $self->download_uri_for($uri_arg);
684  
685 my $get = HTTP::Request->new(
686 GET => $uri,
687 [
688 $self->_maybe_auth_header,
689 1 ▶ ($arg->{accept} ? (Accept => $arg->{accept}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$arg->{'accept'} ? : 0 1 1
690 ],
691 );
692  
693 1 my $res_f = $self->ua->request($self, $get, 'download');
694  
695 1 ▶ my $future = $res_f->then(sub {
Subroutine __ANON__: called CC=2 SCAR=7.4
696 1 my ($res) = @_;
697  
698 1 $self->_logger->log_download_response($self, { http_response => $res });
699  
700 1 ▶ unless ($res->is_success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->is_success) 0 1 1
701 0 return Future->fail(
702 JMAP::Tester::Result::Failure->new({
703 http_response => $res,
704 diagnostic_dumper => $self->default_diagnostic_dumper,
705 })
706 );
707 }
708  
709 1 return Future->done(
710 JMAP::Tester::Result::Download->new({
711 http_response => $res,
712 diagnostic_dumper => $self->default_diagnostic_dumper,
713 })
714 );
715 1 });
716  
717 1 ▶ return $self->should_return_futures ? $future : $future->$Failsafe->get;
Branch: 1 branch
BranchTrueFalseTotal
$self->should_return_futures ? : 0 1 1
718 }
719  
720 9 ▶sub _maybe_auth_header ($self) {
Subroutine _maybe_auth_header: called CC=2 SCAR=7.6
721 9 ▶ return ($self->_access_token
Branch: 1 branch
BranchTrueFalseTotal
$self->_access_token ? : 0 9 9
722 ? (Authorization => "Bearer " . $self->_access_token)
723 : ());
724 }
725  
726 2 has _jwt_config => (
727 is => 'rw',
728 init_arg => undef,
729 );
730  
731 0 ▶sub _now_timestamp {
Subroutine _now_timestamp: not called CC=1 SCAR=6.9
732 # 0 1 2 3 4 5
733 0 my ($sec, $min, $hour, $mday, $mon, $year) = gmtime;
734 0 return sprintf '%04u-%02u-%02uT%02u:%02u:%02uZ',
735 $year + 1900, $mon + 1, $mday,
736 $hour, $min, $sec;
737 }
738  
739 1 ▶sub _get_jwt_config ($self) {
Subroutine _get_jwt_config: called CC=5 SCAR=30.3
740 1 ▶ return unless my $jwtc = $self->_jwt_config;
Branch: 1 branch
BranchTrueFalseTotal
unless my $jwtc = $self->_jwt_config 1 0 1
741 0 ▶ return $jwtc unless $jwtc->{signingKeyValidUntil};
Branch: 1 branch
BranchTrueFalseTotal
unless $jwtc->{"signingKeyValidUntil"} 0 0 0
742 0 ▶ return $jwtc if $jwtc->{signingKeyValidUntil} gt $self->_now_timestamp;
Branch: 1 branch
BranchTrueFalseTotal
if $jwtc->{"signingKeyValidUntil"} gt $self->_now_timestamp 0 0 0
743  
744 0 $self->update_client_session;
745 0 ▶ return unless $jwtc = $self->_jwt_config;
Branch: 1 branch
BranchTrueFalseTotal
unless $jwtc = $self->_jwt_config 0 0 0
746 0 return $jwtc;
747 }
748  
749 2 has _access_token => (
750 is => 'rw',
751 init_arg => undef,
752 );
753  
754 #pod =method get_client_session
755 #pod
756 #pod $tester->get_client_session;
757 #pod $tester->get_client_session($auth_uri);
758 #pod
759 #pod This method fetches the content at the authentication endpoint.
760 #pod
761 #pod This method respects the C<should_return_futures> attributes of the
762 #pod JMAP::Tester object, and in futures mode will return a future that will resolve
763 #pod to the L<JMAP::Tester::Result::Auth> object.
764 #pod
765 #pod =cut
766  
767 3 ▶sub _get_client_session_future ($self, $auth_uri = undef) {
Subroutine _get_client_session_future: called CC=3 SCAR=11.0
768 3 ▶ $auth_uri //= $self->authentication_uri;
Condition66%2/3
$auth_uri //= $self->authentication_uri
l!l&&r!l&&!r
120
MC/DC0%0/2
$auth_uri //= $self->authentication_uri
$auth_uri $self->authentication_uri
Truth table66%2/3
A //= B
A= $auth_uriB= $self->authentication_uri
ABresult
1X1
011
000
769  
770 3 my $auth_req = HTTP::Request->new(
771 GET => $auth_uri,
772 [
773 $self->_maybe_auth_header,
774 'Accept' => 'application/json',
775 ],
776 );
777  
778 3 ▶ my $future = $self->ua->request($self, $auth_req, 'auth')->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
779 3 my ($res) = @_;
780  
781 3 ▶ unless ($res->code == 200) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->code == 200) 1 2 3
782 1 return Future->fail(
783 JMAP::Tester::Result::Failure->new({
784 ident => 'failure to get updated authentication data',
785 http_response => $res,
786 diagnostic_dumper => $self->default_diagnostic_dumper,
787 })
788 );
789 }
790  
791 2 my $client_session = $self->json_decode( $res->decoded_content );
792  
793 2 my $auth = JMAP::Tester::Result::Auth->new({
794 http_response => $res,
795 client_session => $client_session,
796 diagnostic_dumper => $self->default_diagnostic_dumper,
797 });
798  
799 2 return Future->done($auth);
800 3 });
801 }
802  
803 2 ▶sub get_client_session ($self, $auth_uri = undef) {
Subroutine get_client_session: called CC=3 SCAR=11.2
Pod documented
804 2 my $future = $self->_get_client_session_future($auth_uri);
805 2 ▶ return $self->should_return_futures ? $future : $future->$Failsafe->get;
Branch: 1 branch
BranchTrueFalseTotal
$self->should_return_futures ? : 0 2 2
806 }
807  
808 #pod =method update_client_session
809 #pod
810 #pod $tester->update_client_session;
811 #pod $tester->update_client_session($auth_uri);
812 #pod
813 #pod This method fetches the content at the authentication endpoint and uses it to
814 #pod configure the tester's target URIs and signing keys.
815 #pod
816 #pod This method respects the C<should_return_futures> attributes of the
817 #pod JMAP::Tester object, and in futures mode will return a future that will resolve
818 #pod to the Result.
819 #pod
820 #pod =cut
821  
822 1 ▶sub update_client_session ($self, $auth_uri = undef) {
Subroutine update_client_session: called CC=3 SCAR=11.0
Pod documented
823 1 ▶ my $future = $self->_get_client_session_future($auth_uri)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
824 1 my ($auth) = @_;
825  
826 1 $self->configure_from_client_session($auth->client_session);
827  
828 1 return Future->done($auth);
829 1 });
830  
831 1 ▶ return $self->should_return_futures ? $future : $future->$Failsafe->get;
Branch: 1 branch
BranchTrueFalseTotal
$self->should_return_futures ? : 0 1 1
832 }
833  
834 #pod =method configure_from_client_session
835 #pod
836 #pod $tester->configure_from_client_session($client_session);
837 #pod
838 #pod Given a client session object (like those stored in an Auth result), this
839 #pod reconfigures the testers access token, signing keys, URIs, and so forth. This
840 #pod method is used internally when logging in.
841 #pod
842 #pod =cut
843  
844 1 ▶sub configure_from_client_session ($self, $client_session) {
Subroutine configure_from_client_session: called CC=5 SCAR=18.0
Pod documented
845 # It's not crazy to think that we'd also try to pull the primary accountId
846 # out of the accounts in the auth struct, but I don't think there's a lot to
847 # gain by doing that yet. Maybe later we'd use it to set the default
848 # X-JMAP-AccountId or other things, but I think there are too many open
849 # questions. I'm leaving it out on purpose for now. -- rjbs, 2016-11-18
850  
851 # This is no longer fatal because you might be an anonymous session that
852 # needs to call this to fetch an updated signing key. -- rjbs, 2017-03-23
853 # abort("no accessToken in client session object")
854 # unless $client_session->{accessToken};
855  
856 1 $self->_access_token($client_session->{accessToken});
857  
858 1 ▶ if ($client_session->{signingId} && $client_session->{signingKey}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_session->{'signingId'} and $client_session->{'signingKey'}) { } 0 1 1
Condition33%1/3
$client_session->{"signingId"} and $client_session->{"signingKey"}
!ll&&!rl&&r
100
MC/DC0%0/2
$client_session->{"signingId"} and $client_session->{"signingKey"}
$client_session->{"signingId"} $client_session->{"signingKey"}
Truth table33%1/3
A and B
A= $client_session->{"signingId"}B= $client_session->{"signingKey"}
ABresult
0X0
100
111
859 $self->_jwt_config({
860 signingId => $client_session->{signingId},
861 signingKey => $client_session->{signingKey},
862 signingKeyValidUntil => $client_session->{signingKeyValidUntil},
863 0 });
864 } else {
865 1 $self->_jwt_config(undef);
866 }
867  
868 1 for my $type (qw(api download upload)) {
869 3 ▶ if (defined (my $uri = $client_session->{"${type}Url"})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $uri = $$client_session{"${type}Url"})) { } 3 0 3
870 3 my $setter = "$type\_uri";
871 3 $self->$setter($uri);
872 } else {
873 0 my $clearer = "clear_$type\_uri";
874 0 $self->$clearer;
875 }
876 }
877  
878 1 $self->_primary_accounts($client_session->{primaryAccounts});
879 1 $self->_accounts($client_session->{accounts});
880  
881 1 return;
882 }
883  
884 #pod =method logout
885 #pod
886 #pod $tester->logout;
887 #pod
888 #pod This method attempts to log out from the server by sending a C<DELETE> request
889 #pod to the authentication URI.
890 #pod
891 #pod This method respects the C<should_return_futures> attributes of the
892 #pod JMAP::Tester object, and in futures mode will return a future that will resolve
893 #pod to the Result.
894 #pod
895 #pod =cut
896  
897 2 ▶sub logout ($self) {
Subroutine logout: called CC=3 SCAR=11.1
Pod documented
898 # This is fatal, not a failure return, because it reflects the user screwing
899 # up, not a possible JMAP-related condition. -- rjbs, 2017-02-10
900 2 ▶ Carp::confess("can't logout: no authentication_uri configured")
Branch: 1 branch
BranchTrueFalseTotal
unless $self->has_authentication_uri 0 2 2
901 unless $self->has_authentication_uri;
902  
903 2 my $req = HTTP::Request->new(
904 DELETE => $self->authentication_uri,
905 [
906 'Content-Type' => 'application/json; charset=utf-8',
907 'Accept' => 'application/json',
908 ],
909 );
910  
911 2 ▶ my $future = $self->ua->request($self, $req, 'auth')->then(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
912 2 my ($res) = @_;
913  
914 2 ▶ if ($res->code == 204) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->code == 204) 1 1 2
915 1 $self->_access_token(undef);
916  
917 1 return Future->done(
918 JMAP::Tester::Result::Logout->new({
919 http_response => $res,
920 diagnostic_dumper => $self->default_diagnostic_dumper,
921 })
922 );
923 }
924  
925 1 return Future->fail(
926 JMAP::Tester::Result::Failure->new({
927 ident => "failed to log out",
928 http_response => $res,
929 diagnostic_dumper => $self->default_diagnostic_dumper,
930 })
931 );
932 2 });
933  
934 2 ▶ return $self->should_return_futures ? $future : $future->$Failsafe->get;
Branch: 1 branch
BranchTrueFalseTotal
$self->should_return_futures ? : 0 2 2
935 }
936  
937 #pod =method http_request
938 #pod
939 #pod my $response = $jtest->http_request($http_request);
940 #pod
941 #pod Sometimes, you may need to make an HTTP request with your existing web
942 #pod connection. This might be to interact with a custom authentication mechanism,
943 #pod to access custom endpoints, or just to make very, very specifically crafted
944 #pod requests. For this reasons, C<http_request> exists.
945 #pod
946 #pod Pass this method an L<HTTP::Request> and it will use the tester's UA object to
947 #pod make the request.
948 #pod
949 #pod This method respects the C<should_return_futures> attributes of the
950 #pod JMAP::Tester object, and in futures mode will return a future that will resolve
951 #pod to the L<HTTP::Response>.
952 #pod
953 #pod =cut
954  
955 1 ▶sub http_request ($self, $http_request) {
Subroutine http_request: called CC=2 SCAR=7.0
Pod documented
956 1 ▶ my $future = $self->ua->request($self, $http_request, 'misc')->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
957 1 my ($res) = @_;
958 1 $self->_logger->log_misc_response($self, { http_response => $res });
959 1 return Future->done($res);
960 1 });
961  
962 1 ▶ return $self->should_return_futures ? $future : $future->$Failsafe->get;
Branch: 1 branch
BranchTrueFalseTotal
$self->should_return_futures ? : 0 1 1
963 }
964  
965 #pod =method http_get
966 #pod
967 #pod my $response = $jtest->http_get($url, $headers);
968 #pod
969 #pod This method is just sugar for calling C<http_request> to make a GET request for
970 #pod the given URL. C<$headers> is an optional arrayref of headers.
971 #pod
972 #pod =cut
973  
974 1 ▶sub http_get ($self, $url, $headers = undef) {
Subroutine http_get: called CC=3 SCAR=11.2
Pod documented
975 1 ▶ my $req = HTTP::Request->new(
Branch: 1 branch
BranchTrueFalseTotal
defined $headers ? : 0 1 1
976 GET => $url,
977 (defined $headers ? $headers : ()),
978 );
979 1 return $self->http_request($req);
980 }
981  
982 #pod =method http_post
983 #pod
984 #pod my $response = $jtest->http_post($url, $body, $headers);
985 #pod
986 #pod This method is just sugar for calling C<http_request> to make a POST request
987 #pod for the given URL. C<$headers> is an arrayref of headers and C<$body> is the
988 #pod byte string to be passed as the body.
989 #pod
990 #pod =cut
991  
992 0 ▶sub http_post ($self, $url, $body, $headers = undef) {
Subroutine http_post: not called CC=3 SCAR=24.8
Pod documented
993 0 ▶ my $req = HTTP::Request->new(
Condition0%0/2
$headers // []
l!l
00
MC/DC0%0/1
$headers // []
$headers
Truth table0%0/2
A
A= $headers
Aresult
11
00
994 POST => $url,
995 $headers // [],
996 $body,
997 );
998  
999 0 return $self->http_request($req);
1000 }
1001  
1002 has default_diagnostic_dumper => (
1003 is => 'ro',
1004 5 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.2
1005 5 require JSON::MaybeXS;
1006 5 state $json = JSON::MaybeXS->new->utf8->convert_blessed->pretty->canonical;
1007 0 ▶ sub ($value) { $json->encode($value); }
Subroutine __ANON__: not called CC=1 SCAR=6.9
1008 5 },
1009 2 );
1010  
1011 2 1;
1012  
1013 __END__
« Tester/UA/Async.pm ↑ Summary Tester/Role/SentenceCollection.pm »