blib/lib/PAGI/Test/Client.pm

filter: Statementstmt 94.9% 340 / 358 Branchbran 78.3% 130 / 166 Conditioncond 58.8% 50 / 85 MC/DCmcdc 27.6% 13 / 47 Subroutinesub 100% 40 / 40 Podpod 100% 18 / 18 totaltotal 82.7% 591 / 714 CC 133 SCAR 23.4
CC
133
Cov
85%
sse
19.5
websocket
18.7
_set_header
17.1
CRAP 10.4
« blib/lib/PAGI/Request/BodyStream.pm ↑ Summary blib/lib/PAGI/App/Redirect.pm »
1 package PAGI::Test::Client;
2 13 $PAGI::Test::Client::VERSION = '0.002001';
3 13 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 13 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 13 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 13 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 13 ▶use PAGI::Test::ConnectionState;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 13 ▶use PAGI::Test::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 13 ▶use PAGI::Utils ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12  
13 sub new {
14 80 ▶ my ($class, %args) = @_;
Subroutine new: called CC=5 SCAR=16.1
Pod documented
15  
16 80 ▶ croak "app is required" unless $args{app};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"app"} 0 80 80
17  
18 return bless {
19 app => PAGI::Utils::to_app($args{app}),
20 headers => $args{headers} // {},
21 cookies => {},
22 lifespan => $args{lifespan} // 0,
23 80 ▶ raise_app_exceptions => $args{raise_app_exceptions} // 0,
Condition100%6/6
$args{"headers"} // {}
l!l
377
$args{"lifespan"} // 0
l!l
773
$args{"raise_app_exceptions"} // 0
l!l
476
MC/DC100%1/1
$args{"headers"} // {}
$args{"headers"}
MC/DC100%1/1
$args{"lifespan"} // 0
$args{"lifespan"}
MC/DC100%1/1
$args{"raise_app_exceptions"} // 0
$args{"raise_app_exceptions"}
Truth table100%2/2
A
A= $args{"headers"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"lifespan"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"raise_app_exceptions"}
Aresult
11
00
24 started => 0,
25 }, $class;
26 }
27  
28 54 ▶sub get { shift->_request('GET', @_) }
Subroutine get: called CC=1 SCAR=0.0
Pod documented
29 2 ▶sub head { shift->_request('HEAD', @_) }
Subroutine head: called CC=1 SCAR=0.0
Pod documented
30 1 ▶sub delete { shift->_request('DELETE', @_) }
Subroutine delete: called CC=1 SCAR=0.0
Pod documented
31 12 ▶sub post { shift->_request('POST', @_) }
Subroutine post: called CC=1 SCAR=0.0
Pod documented
32 2 ▶sub put { shift->_request('PUT', @_) }
Subroutine put: called CC=1 SCAR=0.0
Pod documented
33 2 ▶sub patch { shift->_request('PATCH', @_) }
Subroutine patch: called CC=1 SCAR=0.0
Pod documented
34 2 ▶sub options { shift->_request('OPTIONS', @_) }
Subroutine options: called CC=1 SCAR=0.0
Pod documented
35  
36 # Cookie management
37 sub cookies {
38 1 ▶ my ($self) = @_;
Subroutine cookies: called CC=1 SCAR=0.0
Pod documented
39 1 return $self->{cookies};
40 }
41  
42 sub cookie {
43 1 ▶ my ($self, $name) = @_;
Subroutine cookie: called CC=1 SCAR=0.0
Pod documented
44 1 return $self->{cookies}{$name};
45 }
46  
47 sub set_cookie {
48 1 ▶ my ($self, $name, $value) = @_;
Subroutine set_cookie: called CC=1 SCAR=0.0
Pod documented
49 1 $self->{cookies}{$name} = $value;
50 1 return $self;
51 }
52  
53 sub clear_cookies {
54 1 ▶ my ($self) = @_;
Subroutine clear_cookies: called CC=1 SCAR=0.0
Pod documented
55 1 $self->{cookies} = {};
56 1 return $self;
57 }
58  
59 sub _request {
60 75 ▶ my ($self, $method, $path, %opts) = @_;
Subroutine _request: called CC=13 SCAR=25.8
61  
62 75 ▶ $path //= '/';
Condition50%1/2
$path //= "/"
l!l
750
MC/DC0%0/1
$path //= "/"
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
63  
64 # Handle json option
65 75 ▶ if (exists $opts{json}) {
Branch: 3 branches
BranchTrueFalseTotal
if (exists $opts{'json'}) { } 5 70 75
elsif (exists $opts{'form'}) { } 6 64 70
elsif (defined $opts{'body'}) { } 0 64 64
66 5 require JSON::MaybeXS;
67 5 $opts{body} = JSON::MaybeXS::encode_json($opts{json});
68 5 _set_header(\$opts{headers}, 'Content-Type', 'application/json', 0);
69 5 _set_header(\$opts{headers}, 'Content-Length', length($opts{body}), 1);
70 }
71 # Handle form option (supports multi-value)
72 elsif (exists $opts{form}) {
73 6 my $pairs = _normalize_pairs($opts{form});
74 6 my @encoded;
75 6 for my $pair (@$pairs) {
76 14 my $key = _url_encode($pair->[0]);
77 14 ▶ my $val = _url_encode($pair->[1] // '');
Condition50%1/2
$pair->[1] // ""
l!l
140
MC/DC0%0/1
$pair->[1] // ""
$pair->[1]
Truth table50%1/2
A
A= $pair->[1]
Aresult
11
00
78 14 push @encoded, "$key=$val";
79 }
80 6 $opts{body} = join('&', @encoded);
81 6 _set_header(\$opts{headers}, 'Content-Type', 'application/x-www-form-urlencoded', 0);
82 6 _set_header(\$opts{headers}, 'Content-Length', length($opts{body}), 1);
83 }
84 # Add Content-Length for raw body if not already set
85 elsif (defined $opts{body}) {
86 0 _set_header(\$opts{headers}, 'Content-Length', length($opts{body}), 0);
87 }
88  
89 # Build scope
90 75 my $scope = $self->_build_scope($method, $path, \%opts);
91  
92 # Build receive (returns request body)
93 73 ▶ my $body = $opts{body} // '';
Condition100%2/2
$opts{"body"} // ""
l!l
1162
MC/DC100%1/1
$opts{"body"} // ""
$opts{"body"}
Truth table100%2/2
A
A= $opts{"body"}
Aresult
11
00
94 73 my $receive_called = 0;
95 21 ▶ my $receive = async sub {
Subroutine __ANON__: called CC=2 SCAR=7.4
96 21 ▶ if (!$receive_called) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($receive_called) 21 0 21
97 21 $receive_called = 1;
98 21 return { type => 'http.request', body => $body, more => 0 };
99 }
100 0 return { type => 'http.disconnect' };
101 73 };
102  
103 # Build send (captures response)
104 73 my @events;
105 121 ▶ my $send = async sub {
Subroutine __ANON__: called CC=9 SCAR=22.1
106 121 my ($event) = @_;
107 121 my %captured = %$event;
108  
109 121 ▶ if (my $conn = $scope->{'pagi.connection'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn = $scope->{"pagi.connection"}) 121 0 121
110 $conn->_mark_response_started
111 121 ▶ if ($captured{type} // '') eq 'http.response.start';
Branch: 1 branch
BranchTrueFalseTotal
if ($captured{"type"} // "") eq "http.response.start" 61 60 121
Condition50%1/2
$captured{"type"} // ""
l!l
1210
MC/DC0%0/1
$captured{"type"} // ""
$captured{"type"}
Truth table50%1/2
A
A= $captured{"type"}
Aresult
11
00
112 }
113  
114 121 ▶ if (($captured{type} // '') eq 'http.response.body') {
Branch: 1 branch
BranchTrueFalseTotal
if (($captured{"type"} // "") eq "http.response.body") 60 61 121
Condition50%1/2
$captured{"type"} // ""
l!l
1210
MC/DC0%0/1
$captured{"type"} // ""
$captured{"type"}
Truth table50%1/2
A
A= $captured{"type"}
Aresult
11
00
115 60 ▶ if ($method eq 'HEAD') {
Branch: 2 branches
BranchTrueFalseTotal
if ($method eq 'HEAD') { } 1 59 60
elsif (exists $captured{'fh'} or exists $captured{'file'}) { } 5 54 59
116 1 $captured{body} = '';
117 1 delete @captured{qw(fh file offset length)};
118 }
119 ▶ elsif (exists $captured{fh} || exists $captured{file}) {
Condition100%3/3
exists $captured{"fh"} or exists $captured{"file"}
l!l&&r!l&&!r
3254
MC/DC100%2/2
exists $captured{"fh"} or exists $captured{"file"}
exists $captured{"fh"} exists $captured{"file"}
Truth table100%3/3
A or B
A= exists $captured{"fh"}B= exists $captured{"file"}
ABresult
1X1
011
000
120 5 $captured{body} = $self->_response_body_bytes(\%captured);
121 5 delete @captured{qw(fh file offset length)};
122 }
123 }
124  
125 121 push @events, \%captured;
126 73 };
127  
128 # Call app (with exception handling like real server)
129 73 my $exception;
130 73 eval {
131 73 $self->{app}->($scope, $receive, $send)->get;
132 };
133 73 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 13 60 73
134 13 $exception = $@;
135 13 ▶ if ($self->{raise_app_exceptions}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"raise_app_exceptions"}) 1 12 13
136 1 die $exception;
137 }
138 # Mimic server behavior: return 500 response
139 12 ▶ if (my $conn = $scope->{'pagi.connection'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn = $scope->{"pagi.connection"}) 12 0 12
140 12 $conn->_mark_response_started; # the 500 IS a response
141 12 $conn->_mark_disconnected('server_error');# abnormal end — not on_complete
142 }
143 12 return PAGI::Test::Response->new(
144 status => 500,
145 headers => [['content-type', 'text/plain']],
146 body => 'Internal Server Error',
147 exception => $exception,
148 );
149 }
150  
151 # Check for incomplete response (common async mistake)
152 60 my $has_response_start = grep { $_->{type} eq 'http.response.start' } @events;
153 60 ▶ unless ($has_response_start) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_response_start) 1 59 60
154 1 die "App returned without sending response. "
155 . "Did you forget to 'await' your \$send calls? "
156 . "See PAGI::Tutorial section on async patterns.\n";
157 }
158  
159 59 ▶ if (my $conn = $scope->{'pagi.connection'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn = $scope->{"pagi.connection"}) 59 0 59
160 59 $conn->_mark_complete;
161 }
162  
163 # Parse response from captured events
164 59 return $self->_build_response(\@events);
165 }
166  
167 sub _build_scope {
168 75 ▶ my ($self, $method, $path, $opts) = @_;
Subroutine _build_scope: called CC=7 SCAR=19.5
169  
170 # Parse query string from path
171 75 my $query_string = '';
172 75 ▶ if ($path =~ s/\?(.*)$//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ s/\?(.*)$//) 2 73 75
173 2 $query_string = $1;
174 }
175  
176 # Add query params if provided (appended to path query string)
177 75 ▶ if ($opts->{query}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"query"}) 6 69 75
178 6 my $pairs = _normalize_pairs($opts->{query});
179 6 my @encoded;
180 6 for my $pair (@$pairs) {
181 11 my $key = _url_encode($pair->[0]);
182 11 ▶ my $val = _url_encode($pair->[1] // '');
Condition50%1/2
$pair->[1] // ""
l!l
110
MC/DC0%0/1
$pair->[1] // ""
$pair->[1]
Truth table50%1/2
A
A= $pair->[1]
Aresult
11
00
183 11 push @encoded, "$key=$val";
184 }
185 6 my $new_params = join('&', @encoded);
186 6 ▶ $query_string = $query_string ? "$query_string&$new_params" : $new_params;
Branch: 1 branch
BranchTrueFalseTotal
$query_string ? : 2 4 6
187 }
188  
189 # Build headers using helper
190 75 my $headers = $self->_build_headers($opts->{headers});
191  
192 73 my $scope = {
193 type => 'http',
194 pagi => { version => '0.2', spec_version => '0.2' },
195 http_version => '1.1',
196 method => $method,
197 scheme => 'http',
198 path => $path,
199 query_string => $query_string,
200 root_path => '',
201 headers => $headers,
202 client => ['127.0.0.1', 12345],
203 server => ['testserver', 80],
204 'pagi.connection' => PAGI::Test::ConnectionState->new,
205 };
206  
207 # Add state if lifespan is enabled
208 73 ▶ $scope->{state} = $self->{state} if $self->{state};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"state"} 10 63 73
209  
210 73 return $scope;
211 }
212  
213 sub _build_response {
214 59 ▶ my ($self, $events) = @_;
Subroutine _build_response: called CC=15 SCAR=27.5
215  
216 59 my $status = 200;
217 59 my @headers;
218 59 my $body = '';
219 59 my $response_started = 0;
220 59 my $body_complete = 0;
221  
222 59 for my $event (@$events) {
223 120 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
1200
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
224  
225 120 ▶ if ($type eq 'http.response.start') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'http.response.start') { } 60 60 120
elsif ($type eq 'http.response.body') { } 60 0 60
226 60 ▶ next if $response_started;
Branch: 1 branch
BranchTrueFalseTotal
if $response_started 1 59 60
227 59 $response_started = 1;
228 59 ▶ $status = $event->{status} // 200;
Condition50%1/2
$event->{"status"} // 200
l!l
590
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
229 59 ▶ @headers = @{$event->{headers} // []};
Condition50%1/2
$event->{"headers"} // []
l!l
590
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
230 }
231 elsif ($type eq 'http.response.body') {
232 60 ▶ next unless $response_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $response_started 0 60 60
233 60 ▶ next if $body_complete;
Branch: 1 branch
BranchTrueFalseTotal
if $body_complete 1 59 60
234  
235 59 $body .= $self->_response_body_bytes($event);
236  
237 59 ▶ my $more = $event->{more} // 0;
Condition100%2/2
$event->{"more"} // 0
l!l
3524
MC/DC100%1/1
$event->{"more"} // 0
$event->{"more"}
Truth table100%2/2
A
A= $event->{"more"}
Aresult
11
00
238 59 ▶ $body_complete = 1 unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 59 0 59
239 }
240 }
241  
242 # Extract Set-Cookie headers and store cookies
243 59 for my $h (@headers) {
244 61 ▶ if (lc($h->[0]) eq 'set-cookie') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "set-cookie") 1 60 61
245 1 ▶ if ($h->[1] =~ /^([^=]+)=([^;]*)/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h->[1] =~ /^([^=]+)=([^;]*)/) 1 0 1
246 1 $self->{cookies}{$1} = $2;
247 }
248 }
249 }
250  
251 59 return PAGI::Test::Response->new(
252 status => $status,
253 headers => \@headers,
254 body => $body,
255 );
256 }
257  
258 sub _response_body_bytes {
259 64 ▶ my ($self, $event) = @_;
Subroutine _response_body_bytes: called CC=7 SCAR=19.7
260  
261 64 ▶ return $event->{body} // '' if exists $event->{body};
Branch: 1 branch
BranchTrueFalseTotal
if exists $event->{"body"} 59 5 64
Condition50%1/2
$event->{"body"} // ""
l!l
590
MC/DC0%0/1
$event->{"body"} // ""
$event->{"body"}
Truth table50%1/2
A
A= $event->{"body"}
Aresult
11
00
262  
263 5 ▶ if (exists $event->{file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $event->{"file"}) 2 3 5
264 return _read_file_bytes(
265 $event->{file},
266 $event->{offset} // 0,
267 $event->{length},
268 2 ▶ );
Condition100%2/2
$event->{"offset"} // 0
l!l
11
MC/DC100%1/1
$event->{"offset"} // 0
$event->{"offset"}
Truth table100%2/2
A
A= $event->{"offset"}
Aresult
11
00
269 }
270  
271 3 ▶ if (exists $event->{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $event->{"fh"}) 3 0 3
272 return _read_fh_bytes(
273 $event->{fh},
274 $event->{offset} // 0,
275 $event->{length},
276 3 ▶ );
Condition100%2/2
$event->{"offset"} // 0
l!l
12
MC/DC100%1/1
$event->{"offset"} // 0
$event->{"offset"}
Truth table100%2/2
A
A= $event->{"offset"}
Aresult
11
00
277 }
278  
279 0 return '';
280 }
281  
282 sub _read_file_bytes {
283 2 ▶ my ($path, $offset, $length) = @_;
Subroutine _read_file_bytes: called CC=4 SCAR=14.5
284  
285 2 ▶ open my $fh, '<:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or croak("Cannot open file response '${path}': $!") 0 2 2
286 or croak "Cannot open file response '$path': $!";
287  
288 2 ▶ seek($fh, $offset, 0)
Branch: 1 branch
BranchTrueFalseTotal
if $offset 1 1 2
Condition50%3/6
$offset && (seek($fh, $offset, 0) || croak("Cannot seek file response '${path}': $!"))
!ll&&!rl&&r
110
seek $fh, $offset, 0 or croak("Cannot seek file response '${path}': $!")
l!l&&r!l&&!r
100
MC/DC0%0/3
$offset && (seek($fh, $offset, 0) || croak("Cannot seek file response '${path}': $!"))
$offset seek $fh, $offset, 0 croak("Cannot seek file response '${path}': $!")
Truth table0%0/4
A && B or C
A= $offsetB= seek $fh, $offset, 0C= croak("Cannot seek file response '${path}': $!")
ABCresult
0XX0
1000
11X1
1011
289 or croak "Cannot seek file response '$path': $!"
290 if $offset;
291  
292 2 my $content = _slurp_fh_bytes($fh, $length);
293 2 close $fh;
294  
295 2 return $content;
296 }
297  
298 sub _read_fh_bytes {
299 3 ▶ my ($fh, $offset, $length) = @_;
Subroutine _read_fh_bytes: called CC=3 SCAR=11.6
300  
301 3 ▶ seek($fh, $offset, 0)
Branch: 1 branch
BranchTrueFalseTotal
if $offset 1 2 3
Condition50%3/6
$offset && (seek($fh, $offset, 0) || croak("Cannot seek filehandle response: $!"))
!ll&&!rl&&r
210
seek $fh, $offset, 0 or croak("Cannot seek filehandle response: $!")
l!l&&r!l&&!r
100
MC/DC0%0/3
$offset && (seek($fh, $offset, 0) || croak("Cannot seek filehandle response: $!"))
$offset seek $fh, $offset, 0 croak("Cannot seek filehandle response: $!")
Truth table0%0/4
A && B or C
A= $offsetB= seek $fh, $offset, 0C= croak("Cannot seek filehandle response: $!")
ABCresult
0XX0
1000
11X1
1011
302 or croak "Cannot seek filehandle response: $!"
303 if $offset;
304  
305 3 return _slurp_fh_bytes($fh, $length);
306 }
307  
308 sub _slurp_fh_bytes {
309 5 ▶ my ($fh, $length) = @_;
Subroutine _slurp_fh_bytes: called CC=7 SCAR=19.5
310  
311 5 my $content = '';
312 5 my $remaining = $length;
313  
314 5 while (1) {
315 10 my $to_read = 65536;
316 10 ▶ if (defined $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining) 4 6 10
317 4 ▶ last if $remaining <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining <= 0 2 2 4
318 2 ▶ $to_read = $remaining if $remaining < $to_read;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining < $to_read 2 0 2
319 }
320  
321 8 my $bytes_read = read($fh, my $chunk, $to_read);
322 8 ▶ croak "Cannot read response body from filehandle: $!"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 0 8 8
323 unless defined $bytes_read;
324 8 ▶ last if $bytes_read == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes_read == 0 3 5 8
325  
326 5 $content .= $chunk;
327 5 ▶ $remaining -= $bytes_read if defined $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if defined $remaining 2 3 5
328 }
329  
330 5 return $content;
331 }
332  
333 sub websocket {
334 14 ▶ my ($self, $path, @rest) = @_;
Subroutine websocket: called CC=17 SCAR=29.3
Pod documented
335  
336 14 require PAGI::Test::WebSocket;
337  
338 # Handle both: websocket($path, $callback) and websocket($path, %opts)
339 # and websocket($path, %opts, $callback)
340 14 my ($callback, %opts);
341 14 ▶ if (@rest == 1 && ref($rest[0]) eq 'CODE') {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest == 1 and ref $rest[0] eq 'CODE') { } 8 6 14
elsif (@rest % 2 == 0) { } 4 2 6
elsif (@rest % 2 == 1 and ref $rest[-1] eq 'CODE') { } 2 0 2
Condition66%2/3
@rest == 1 and ref $rest[0] eq "CODE"
!ll&&!rl&&r
608
MC/DC50%1/2
@rest == 1 and ref $rest[0] eq "CODE"
@rest == 1 ref $rest[0] eq "CODE"
Truth table66%2/3
A and B
A= @rest == 1B= ref $rest[0] eq "CODE"
ABresult
0X0
100
111
342 8 $callback = $rest[0];
343 } elsif (@rest % 2 == 0) {
344 4 %opts = @rest;
345 ▶ } elsif (@rest % 2 == 1 && ref($rest[-1]) eq 'CODE') {
Condition33%1/3
@rest % 2 == 1 and ref $rest[-1] eq "CODE"
!ll&&!rl&&r
002
MC/DC0%0/2
@rest % 2 == 1 and ref $rest[-1] eq "CODE"
@rest % 2 == 1 ref $rest[-1] eq "CODE"
Truth table33%1/3
A and B
A= @rest % 2 == 1B= ref $rest[-1] eq "CODE"
ABresult
0X0
100
111
346 2 $callback = pop @rest;
347 2 %opts = @rest;
348 }
349  
350 14 ▶ $path //= '/';
Condition50%1/2
$path //= "/"
l!l
140
MC/DC0%0/1
$path //= "/"
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
351  
352 # Parse query string from path
353 14 my $query_string = '';
354 14 ▶ if ($path =~ s/\?(.*)$//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ s/\?(.*)$//) 1 13 14
355 1 $query_string = $1;
356 }
357  
358 # Build headers
359 14 my @headers = (['host', 'testserver']);
360  
361 # Add client default headers (normalized)
362 14 my $default_pairs = _normalize_pairs($self->{headers});
363 14 for my $pair (@$default_pairs) {
364 0 push @headers, [lc($pair->[0]), $pair->[1]];
365 }
366  
367 # Add request-specific headers (normalized, replace by key)
368 14 ▶ if ($opts{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"headers"}) 2 12 14
369 2 my $request_pairs = _normalize_pairs($opts{headers});
370 2 my %replace_keys = map { lc($_->[0]) => 1 } @$request_pairs;
371  
372 # Filter out replaced headers from existing
373 2 @headers = grep { !$replace_keys{$_->[0]} } @headers;
374  
375 # Add request headers
376 2 for my $pair (@$request_pairs) {
377 3 push @headers, [lc($pair->[0]), $pair->[1]];
378 }
379 }
380  
381 # Add cookies
382 14 ▶ if (keys %{$self->{cookies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"cookies"};}) 0 14 14
383 0 my $cookie = join('; ', map { "$_=$self->{cookies}{$_}" } sort keys %{$self->{cookies}});
384 0 push @headers, ['cookie', $cookie];
385 }
386  
387 my $scope = {
388 type => 'websocket',
389 pagi => { version => '0.2', spec_version => '0.2' },
390 http_version => '1.1',
391 scheme => 'ws',
392 path => $path,
393 query_string => $query_string,
394 root_path => '',
395 headers => \@headers,
396 client => ['127.0.0.1', 12345],
397 server => ['testserver', 80],
398 14 ▶ subprotocols => $opts{subprotocols} // [],
Condition50%1/2
$opts{"subprotocols"} // []
l!l
014
MC/DC0%0/1
$opts{"subprotocols"} // []
$opts{"subprotocols"}
Truth table50%1/2
A
A= $opts{"subprotocols"}
Aresult
11
00
399 };
400  
401 14 ▶ $scope->{state} = $self->{state} if $self->{state};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"state"} 1 13 14
402  
403 14 my $ws = PAGI::Test::WebSocket->new(app => $self->{app}, scope => $scope);
404 14 $ws->_start;
405  
406 14 ▶ if ($callback) {
Branch: 1 branch
BranchTrueFalseTotal
if ($callback) 10 4 14
407 10 eval { $callback->($ws) };
408 10 my $err = $@;
409 10 ▶ $ws->close unless $ws->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $ws->is_closed 8 2 10
410 10 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 10 10
411 10 return;
412 }
413  
414 4 return $ws;
415 }
416  
417 sub sse {
418 12 ▶ my ($self, $path, @rest) = @_;
Subroutine sse: called CC=17 SCAR=29.7
Pod documented
419  
420 12 require PAGI::Test::SSE;
421  
422 # Handle both: sse($path, $callback) and sse($path, %opts)
423 # and sse($path, %opts, $callback)
424 12 my ($callback, %opts);
425 12 ▶ if (@rest == 1 && ref($rest[0]) eq 'CODE') {
Branch: 3 branches
BranchTrueFalseTotal
if (@rest == 1 and ref $rest[0] eq 'CODE') { } 6 6 12
elsif (@rest % 2 == 0) { } 1 5 6
elsif (@rest % 2 == 1 and ref $rest[-1] eq 'CODE') { } 5 0 5
Condition66%2/3
@rest == 1 and ref $rest[0] eq "CODE"
!ll&&!rl&&r
606
MC/DC50%1/2
@rest == 1 and ref $rest[0] eq "CODE"
@rest == 1 ref $rest[0] eq "CODE"
Truth table66%2/3
A and B
A= @rest == 1B= ref $rest[0] eq "CODE"
ABresult
0X0
100
111
426 6 $callback = $rest[0];
427 } elsif (@rest % 2 == 0) {
428 1 %opts = @rest;
429 ▶ } elsif (@rest % 2 == 1 && ref($rest[-1]) eq 'CODE') {
Condition33%1/3
@rest % 2 == 1 and ref $rest[-1] eq "CODE"
!ll&&!rl&&r
005
MC/DC0%0/2
@rest % 2 == 1 and ref $rest[-1] eq "CODE"
@rest % 2 == 1 ref $rest[-1] eq "CODE"
Truth table33%1/3
A and B
A= @rest % 2 == 1B= ref $rest[-1] eq "CODE"
ABresult
0X0
100
111
430 5 $callback = pop @rest;
431 5 %opts = @rest;
432 }
433  
434 12 ▶ $path //= '/';
Condition50%1/2
$path //= "/"
l!l
120
MC/DC0%0/1
$path //= "/"
$path
Truth table50%1/2
A
A= $path
Aresult
11
00
435  
436 # Parse query string from path
437 12 my $query_string = '';
438 12 ▶ if ($path =~ s/\?(.*)$//) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ s/\?(.*)$//) 0 12 12
439 0 $query_string = $1;
440 }
441  
442 # Build headers (SSE requires Accept: text/event-stream)
443 12 my @headers = (
444 ['host', 'testserver'],
445 ['accept', 'text/event-stream'],
446 );
447  
448 # Add client default headers (normalized)
449 12 my $default_pairs = _normalize_pairs($self->{headers});
450 12 for my $pair (@$default_pairs) {
451 0 push @headers, [lc($pair->[0]), $pair->[1]];
452 }
453  
454 # Add request-specific headers (normalized, replace by key)
455 12 ▶ if ($opts{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"headers"}) 2 10 12
456 2 my $request_pairs = _normalize_pairs($opts{headers});
457 2 my %replace_keys = map { lc($_->[0]) => 1 } @$request_pairs;
458  
459 # Filter out replaced headers from existing
460 2 @headers = grep { !$replace_keys{$_->[0]} } @headers;
461  
462 # Add request headers
463 2 for my $pair (@$request_pairs) {
464 3 push @headers, [lc($pair->[0]), $pair->[1]];
465 }
466 }
467  
468 # Add cookies
469 12 ▶ if (keys %{$self->{cookies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"cookies"};}) 0 12 12
470 0 my $cookie = join('; ', map { "$_=$self->{cookies}{$_}" } sort keys %{$self->{cookies}});
471 0 push @headers, ['cookie', $cookie];
472 }
473  
474 # SSE supports all HTTP methods (GET is default, but POST/PUT work with
475 # modern libraries like fetch-event-source used by htmx4, datastar, etc.)
476 12 ▶ my $method = uc($opts{method} // 'GET');
Condition100%2/2
$opts{"method"} // "GET"
l!l
39
MC/DC100%1/1
$opts{"method"} // "GET"
$opts{"method"}
Truth table100%2/2
A
A= $opts{"method"}
Aresult
11
00
477  
478 12 my $scope = {
479 type => 'sse',
480 pagi => { version => '0.2', spec_version => '0.2' },
481 http_version => '1.1',
482 method => $method,
483 scheme => 'http',
484 path => $path,
485 query_string => $query_string,
486 root_path => '',
487 headers => \@headers,
488 client => ['127.0.0.1', 12345],
489 server => ['testserver', 80],
490 };
491  
492 12 ▶ $scope->{state} = $self->{state} if $self->{state};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"state"} 1 11 12
493  
494 12 my $sse = PAGI::Test::SSE->new(app => $self->{app}, scope => $scope);
495 12 $sse->_start;
496  
497 12 ▶ if ($callback) {
Branch: 1 branch
BranchTrueFalseTotal
if ($callback) 11 1 12
498 11 eval { $callback->($sse) };
499 11 my $err = $@;
500 11 ▶ $sse->close unless $sse->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $sse->is_closed 11 0 11
501 11 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 11 11
502 11 return;
503 }
504  
505 1 return $sse;
506 }
507  
508 sub start {
509 7 ▶ my ($self) = @_;
Subroutine start: called CC=5 SCAR=16.2
Pod documented
510 7 ▶ return $self if $self->{started};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"started"} 0 7 7
511 7 ▶ return $self unless $self->{lifespan};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lifespan"} 0 7 7
512  
513 7 $self->{state} = {};
514  
515 my $scope = {
516 type => 'lifespan',
517 pagi => { version => '0.2', spec_version => '0.2' },
518 state => $self->{state},
519 7 };
520  
521 7 my $phase = 'startup';
522 7 my $pending_future;
523  
524 14 ▶ my $receive = async sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
525 14 ▶ if ($phase eq 'startup') {
Branch: 1 branch
BranchTrueFalseTotal
if ($phase eq "startup") 7 7 14
526 7 $phase = 'running';
527 7 return { type => 'lifespan.startup' };
528 }
529 # Wait for shutdown
530 7 $pending_future = Future->new;
531 7 return await $pending_future;
532 7 };
533  
534 7 my $startup_complete = 0;
535 14 ▶ my $send = async sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
536 14 my ($event) = @_;
537 14 ▶ if ($event->{type} eq 'lifespan.startup.complete') {
Branch: 2 branches
BranchTrueFalseTotal
if ($event->{'type'} eq 'lifespan.startup.complete') { } 7 7 14
elsif ($event->{'type'} eq 'lifespan.shutdown.complete') { } 7 0 7
538 7 $startup_complete = 1;
539 }
540 elsif ($event->{type} eq 'lifespan.shutdown.complete') {
541 # Done
542 }
543 7 };
544  
545 7 $self->{lifespan_pending} = \$pending_future;
546 7 $self->{lifespan_future} = $self->{app}->($scope, $receive, $send);
547  
548 # Pump until startup complete
549 7 my $deadline = time + 5;
550 7 ▶ while (!$startup_complete && time < $deadline) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $startup_complete and time < $deadline) 0 7 7
Condition33%1/3
not $startup_complete and time < $deadline
!ll&&!rl&&r
700
MC/DC0%0/2
not $startup_complete and time < $deadline
not $startup_complete time < $deadline
Truth table33%1/3
not(A) and B
A= not $startup_completeB= time < $deadline
ABresult
0X0
100
111
551 # Just yield - the async code runs synchronously in our setup
552 }
553  
554 7 $self->{started} = 1;
555 7 return $self;
556 }
557  
558 sub stop {
559 7 ▶ my ($self) = @_;
Subroutine stop: called CC=5 SCAR=17.1
Pod documented
560 7 ▶ return $self unless $self->{started};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"started"} 0 7 7
561 7 ▶ return $self unless $self->{lifespan};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lifespan"} 0 7 7
562  
563 # Resolve the pending future with shutdown event
564 7 ▶ if ($self->{lifespan_pending} && ${$self->{lifespan_pending}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lifespan_pending"} and ${$self->{"lifespan_pending"};}) 7 0 7
Condition33%1/3
$self->{"lifespan_pending"} and ${$self->{"lifespan_pending"};}
!ll&&!rl&&r
007
MC/DC0%0/2
$self->{"lifespan_pending"} and ${$self->{"lifespan_pending"};}
$self->{"lifespan_pending"} ${$self->{"lifespan_pending"};}
Truth table33%1/3
A and B
A= $self->{"lifespan_pending"}B= ${$self->{"lifespan_pending"};}
ABresult
0X0
100
111
565 7 ${$self->{lifespan_pending}}->done({ type => 'lifespan.shutdown' });
566 }
567  
568 7 $self->{started} = 0;
569 7 return $self;
570 }
571  
572 2 ▶sub state { shift->{state} // {} }
Subroutine state: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
+(shift())->{"state"} // {}
l!l
20
MC/DC0%0/1
+(shift())->{"state"} // {}
+(shift())->{"state"}
Truth table50%1/2
A
A= +(shift())->{"state"}
Aresult
11
00
573  
574 sub run {
575 3 ▶ my ($class, $app, $callback) = @_;
Subroutine run: called CC=2 SCAR=7.0
Pod documented
576  
577 3 my $client = $class->new(app => $app, lifespan => 1);
578 3 $client->start;
579  
580 3 eval { $callback->($client) };
581 3 my $err = $@;
582  
583 3 $client->stop;
584 3 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 3 3
585 }
586  
587 sub _url_encode {
588 50 ▶ my ($str) = @_;
Subroutine _url_encode: called CC=1 SCAR=0.0
589 50 $str =~ s/([^A-Za-z0-9_\-.])/sprintf("%%%02X", ord($1))/eg;
590 50 return $str;
591 }
592  
593 # Normalize various input formats to arrayref of [key, value] pairs.
594 # Supports:
595 # - Hash with scalar values: { key => 'value' }
596 # Set a header on a headers structure (hashref or arrayref of pairs).
597 # If $replace is true, replaces existing value. Otherwise only sets if not present.
598 sub _set_header {
599 22 ▶ my ($headers_ref, $name, $value, $replace) = @_;
Subroutine _set_header: called CC=11 SCAR=28.4
600 22 ▶ $replace //= 0;
Condition50%1/2
$replace //= 0
l!l
220
MC/DC0%0/1
$replace //= 0
$replace
Truth table50%1/2
A
A= $replace
Aresult
11
00
601  
602 22 ▶ if (!defined $$headers_ref) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $$headers_ref) 9 13 22
603 9 $$headers_ref = { $name => $value };
604 9 return;
605 }
606  
607 13 ▶ if (ref($$headers_ref) eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $$headers_ref eq 'HASH') { } 9 4 13
elsif (ref $$headers_ref eq 'ARRAY') { } 4 0 4
608 9 ▶ if ($replace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($replace) { } 9 0 9
609 9 $$headers_ref->{$name} = $value;
610 } else {
611 0 ▶ $$headers_ref->{$name} //= $value;
Condition0%0/3
$$headers_ref->{$name} //= $value
l!l&&r!l&&!r
000
MC/DC0%0/2
$$headers_ref->{$name} //= $value
$$headers_ref->{$name} $value
Truth table0%0/3
A //= B
A= $$headers_ref->{$name}B= $value
ABresult
1X1
011
000
612 }
613 } elsif (ref($$headers_ref) eq 'ARRAY') {
614 # Check if header already exists (case-insensitive)
615 4 my $found_idx;
616 4 for my $i (0 .. $#{$$headers_ref}) {
617 8 ▶ if (lc($$headers_ref->[$i][0]) eq lc($name)) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $$headers_ref->[$i][0] eq lc $name) 0 8 8
618 0 $found_idx = $i;
619 0 last;
620 }
621 }
622 4 ▶ if (defined $found_idx) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $found_idx) { } 0 4 4
623 0 ▶ $$headers_ref->[$found_idx][1] = $value if $replace;
Branch: 1 branch
BranchTrueFalseTotal
if $replace 0 0 0
624 } else {
625 4 push @{$$headers_ref}, [$name, $value];
626 }
627 }
628 }
629  
630 # - Hash with arrayref values: { key => ['v1', 'v2'] }
631 # - Arrayref of pairs: [['key', 'v1'], ['key', 'v2']]
632 # Returns arrayref of [key, value] pairs.
633 sub _normalize_pairs {
634 192 ▶ my ($input) = @_;
Subroutine _normalize_pairs: called CC=11 SCAR=24.0
635 192 ▶ return [] unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 57 135 192
636  
637 # Arrayref of pairs: [['key', 'val'], ['key', 'val2']]
638 135 ▶ if (ref($input) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input eq "ARRAY") 6 129 135
639 # Validate it looks like pairs
640 6 for my $pair (@$input) {
641 17 ▶ croak "Expected arrayref of [key, value] pairs"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $pair eq "ARRAY" and @$pair == 2 1 16 17
Condition66%2/3
ref $pair eq "ARRAY" and @$pair == 2
!ll&&!rl&&r
0116
MC/DC50%1/2
ref $pair eq "ARRAY" and @$pair == 2
ref $pair eq "ARRAY" @$pair == 2
Truth table66%2/3
A and B
A= ref $pair eq "ARRAY"B= @$pair == 2
ABresult
0X0
100
111
642 unless ref($pair) eq 'ARRAY' && @$pair == 2;
643 }
644 5 return $input;
645 }
646  
647 # Hash (with scalar or arrayref values)
648 129 ▶ if (ref($input) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input eq "HASH") 128 1 129
649 128 my @pairs;
650 128 for my $key (sort keys %$input) {
651 43 my $val = $input->{$key};
652 43 ▶ if (ref($val) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq 'ARRAY') { } 10 33 43
653 # Multiple values for this key
654 10 push @pairs, [$key, $_] for @$val;
655 } else {
656 # Single value
657 33 ▶ push @pairs, [$key, $val // ''];
Condition50%1/2
$val // ""
l!l
330
MC/DC0%0/1
$val // ""
$val
Truth table50%1/2
A
A= $val
Aresult
11
00
658 }
659 }
660 128 return \@pairs;
661 }
662  
663 1 croak "Expected hashref or arrayref of pairs, got " . ref($input);
664 }
665  
666 # Build headers array, merging defaults with request-specific headers.
667 # Request headers replace client defaults by key (case-insensitive).
668 sub _build_headers {
669 75 ▶ my ($self, $request_headers) = @_;
Subroutine _build_headers: called CC=6 SCAR=17.9
670  
671 75 my @headers;
672  
673 # Default headers
674 75 push @headers, ['host', 'testserver'];
675  
676 # Normalize client default headers
677 75 my $default_pairs = _normalize_pairs($self->{headers});
678  
679 # Normalize request-specific headers
680 75 my $request_pairs = _normalize_pairs($request_headers);
681  
682 # Build set of keys to replace (lowercase)
683 73 my %replace_keys;
684 73 for my $pair (@$request_pairs) {
685 35 $replace_keys{lc($pair->[0])} = 1;
686 }
687  
688 # Add client defaults (skip if being replaced)
689 73 for my $pair (@$default_pairs) {
690 push @headers, [lc($pair->[0]), $pair->[1]]
691 6 ▶ unless $replace_keys{lc($pair->[0])};
Branch: 1 branch
BranchTrueFalseTotal
unless $replace_keys{lc $pair->[0]} 3 3 6
692 }
693  
694 # Add request-specific headers
695 73 for my $pair (@$request_pairs) {
696 35 push @headers, [lc($pair->[0]), $pair->[1]];
697 }
698  
699 # Add cookies
700 73 ▶ if (keys %{$self->{cookies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"cookies"};}) 2 71 73
701 2 my $cookie = join('; ', map { "$_=$self->{cookies}{$_}" } sort keys %{$self->{cookies}});
702 2 push @headers, ['cookie', $cookie];
703 }
704  
705 73 return \@headers;
706 }
707  
708 13 1;
709  
710 __END__
« blib/lib/PAGI/Request/BodyStream.pm ↑ Summary blib/lib/PAGI/App/Redirect.pm »