blib/lib/PAGI/Test/Client.pm

filter: Statementstmt 94.3% 348 / 369 Branchbran 78.4% 135 / 172 Conditioncond 60.7% 51 / 84 MC/DCmcdc 28.8% 13 / 45 Subroutinesub 97.6% 41 / 42 Podpod 100% 18 / 18 totaltotal 83.0% 606 / 730 CC 137 SCAR 23.3
CC
137
Cov
85%
sse
19.5
websocket
18.7
_set_header
17.1
CRAP 10.3
« blib/lib/PAGI/Request/BodyStream.pm ↑ Summary blib/lib/PAGI/Middleware/HTTPSRedirect.pm »
1 package PAGI::Test::Client;
2 13 $PAGI::Test::Client::VERSION = '0.002002';
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 82 ▶sub new {
Subroutine new: called CC=5 SCAR=16.1
Pod documented
14 82 my ($class, %args) = @_;
15  
16 82 ▶ croak "app is required" unless $args{app};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"app"} 0 82 82
17  
18 return bless {
19 app => PAGI::Utils::to_app($args{app}),
20 headers => $args{headers} // {},
21 cookies => {},
22 lifespan => $args{lifespan} // 0,
23 82 ▶ raise_app_exceptions => $args{raise_app_exceptions} // 0,
Condition100%6/6
$args{"headers"} // {}
l!l
379
$args{"lifespan"} // 0
l!l
973
$args{"raise_app_exceptions"} // 0
l!l
478
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 1 ▶sub cookies {
Subroutine cookies: called CC=1 SCAR=0.0
Pod documented
38 1 my ($self) = @_;
39 1 return $self->{cookies};
40 }
41  
42 1 ▶sub cookie {
Subroutine cookie: called CC=1 SCAR=0.0
Pod documented
43 1 my ($self, $name) = @_;
44 1 return $self->{cookies}{$name};
45 }
46  
47 1 ▶sub set_cookie {
Subroutine set_cookie: called CC=1 SCAR=0.0
Pod documented
48 1 my ($self, $name, $value) = @_;
49 1 $self->{cookies}{$name} = $value;
50 1 return $self;
51 }
52  
53 1 ▶sub clear_cookies {
Subroutine clear_cookies: called CC=1 SCAR=0.0
Pod documented
54 1 my ($self) = @_;
55 1 $self->{cookies} = {};
56 1 return $self;
57 }
58  
59 75 ▶sub _request {
Subroutine _request: called CC=13 SCAR=25.8
60 75 my ($self, $method, $path, %opts) = @_;
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 75 ▶sub _build_scope {
Subroutine _build_scope: called CC=7 SCAR=19.5
168 75 my ($self, $method, $path, $opts) = @_;
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 59 ▶sub _build_response {
Subroutine _build_response: called CC=15 SCAR=27.5
214 59 my ($self, $events) = @_;
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 64 ▶sub _response_body_bytes {
Subroutine _response_body_bytes: called CC=7 SCAR=19.7
259 64 my ($self, $event) = @_;
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 2 ▶sub _read_file_bytes {
Subroutine _read_file_bytes: called CC=4 SCAR=14.2
283 2 my ($path, $offset, $length) = @_;
284  
285 2 ▶ open my $fh, '<:raw', $path
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $path or croak("Cannot open file response '${path}': $!") 2 0 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
Condition60%3/5
$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
10
MC/DC0%0/2
$offset && (seek($fh, $offset, 0) || croak("Cannot seek file response '${path}': $!"))
$offset seek $fh, $offset, 0
Truth table33%1/3
A && B
A= $offsetB= seek $fh, $offset, 0
ABresult
0X0
100
111
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 3 ▶sub _read_fh_bytes {
Subroutine _read_fh_bytes: called CC=3 SCAR=11.2
299 3 my ($fh, $offset, $length) = @_;
300  
301 3 ▶ seek($fh, $offset, 0)
Branch: 1 branch
BranchTrueFalseTotal
if $offset 1 2 3
Condition60%3/5
$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
10
MC/DC0%0/2
$offset && (seek($fh, $offset, 0) || croak("Cannot seek filehandle response: $!"))
$offset seek $fh, $offset, 0
Truth table33%1/3
A && B
A= $offsetB= seek $fh, $offset, 0
ABresult
0X0
100
111
302 or croak "Cannot seek filehandle response: $!"
303 if $offset;
304  
305 3 return _slurp_fh_bytes($fh, $length);
306 }
307  
308 5 ▶sub _slurp_fh_bytes {
Subroutine _slurp_fh_bytes: called CC=7 SCAR=19.5
309 5 my ($fh, $length) = @_;
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 14 ▶sub websocket {
Subroutine websocket: called CC=17 SCAR=29.3
Pod documented
334 14 my ($self, $path, @rest) = @_;
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 12 ▶sub sse {
Subroutine sse: called CC=17 SCAR=29.7
Pod documented
418 12 my ($self, $path, @rest) = @_;
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 9 ▶sub start {
Subroutine start: called CC=5 SCAR=16.3
Pod documented
509 9 my ($self) = @_;
510 9 ▶ return $self if $self->{started};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"started"} 0 9 9
511 9 ▶ return $self unless $self->{lifespan};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lifespan"} 0 9 9
512  
513 9 $self->{state} = {};
514  
515 my $scope = {
516 type => 'lifespan',
517 pagi => { version => '0.2', spec_version => '0.2' },
518 state => $self->{state},
519 9 };
520  
521 9 my $phase = 'startup';
522 9 my $pending_future;
523  
524 17 ▶ my $receive = async sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
525 17 ▶ if ($phase eq 'startup') {
Branch: 1 branch
BranchTrueFalseTotal
if ($phase eq "startup") 9 8 17
526 9 $phase = 'running';
527 9 return { type => 'lifespan.startup' };
528 }
529 # Wait for shutdown
530 8 $pending_future = Future->new;
531 8 return await $pending_future;
532 9 };
533  
534 # Resolves when the app signals startup: done on lifespan.startup.complete,
535 # failed (with the app's message) on lifespan.startup.failed.
536 9 my $startup = Future->new;
537 16 ▶ my $send = async sub {
Subroutine __ANON__: called CC=7 SCAR=20.2
538 16 my ($event) = @_;
539 16 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
160
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
540 16 ▶ if ($type eq 'lifespan.startup.complete') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'lifespan.startup.complete') { } 8 8 16
elsif ($type eq 'lifespan.startup.failed') { } 1 7 8
541 8 ▶ $startup->done unless $startup->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $startup->is_ready 8 0 8
542 }
543 elsif ($type eq 'lifespan.startup.failed') {
544 1 ▶ $startup->fail($event->{message} // "lifespan startup failed\n")
Branch: 1 branch
BranchTrueFalseTotal
unless $startup->is_ready 1 0 1
Condition50%1/2
$event->{"message"} // "lifespan startup failed\n"
l!l
10
MC/DC0%0/1
$event->{"message"} // "lifespan startup failed\n"
$event->{"message"}
Truth table50%1/2
A
A= $event->{"message"}
Aresult
11
00
545 unless $startup->is_ready;
546 }
547 9 };
548  
549 9 $self->{lifespan_pending} = \$pending_future;
550 9 $self->{lifespan_future} = $self->{app}->($scope, $receive, $send);
551  
552 9 ▶ if ($startup->is_ready) {
Branch: 2 branches
BranchTrueFalseTotal
if ($startup->is_ready) { } 8 1 9
elsif ($self->{'lifespan_future'}->is_ready) { } 0 1 1
553 # A synchronous startup hook has already signaled by the time app()
554 # returned. Rethrow a synchronous lifespan.startup.failed; otherwise
555 # this is a no-op. No event loop is involved in this common path.
556 8 $startup->get;
557 }
558 elsif ($self->{lifespan_future}->is_ready) {
559 # The app unwound without signaling startup at all. Surface its own
560 # exception if it failed, otherwise report the protocol violation
561 # rather than waiting for a signal that will never come.
562 0 $self->{lifespan_future}->get;
563 0 croak "PAGI lifespan app returned without sending "
564 . "lifespan.startup.complete or lifespan.startup.failed";
565 }
566 else {
567 # The startup hook suspended on real off-loop I/O. Drive the event
568 # loop until it signals, the same way _request drives a request with
569 # ->get, instead of busy-waiting a deadline that never advances the
570 # loop. Off-loop I/O is only possible when Future::IO is present, so
571 # require it lazily here (it is a recommended, not required, prereq).
572 1 require Future::IO;
573 1 my $timeout = 5;
574 1 ▶ my $drive = async sub {
Subroutine __ANON__: called CC=1 SCAR=0.4
575 await Future->wait_any(
576 $startup,
577 0 ▶ Future::IO->sleep($timeout)->then(sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
578 0 Future->fail(
579 "PAGI lifespan startup did not complete within ${timeout} seconds\n"
580 );
581 1 }),
582 );
583 1 };
584 # ->get drives the loop and rethrows on lifespan.startup.failed or the
585 # backstop timeout; on success $startup is now done.
586 1 $drive->()->get;
587 }
588  
589 8 $self->{started} = 1;
590 8 return $self;
591 }
592  
593 8 ▶sub stop {
Subroutine stop: called CC=5 SCAR=17.1
Pod documented
594 8 my ($self) = @_;
595 8 ▶ return $self unless $self->{started};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"started"} 0 8 8
596 8 ▶ return $self unless $self->{lifespan};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lifespan"} 0 8 8
597  
598 # Resolve the pending future with shutdown event
599 8 ▶ if ($self->{lifespan_pending} && ${$self->{lifespan_pending}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"lifespan_pending"} and ${$self->{"lifespan_pending"};}) 8 0 8
Condition33%1/3
$self->{"lifespan_pending"} and ${$self->{"lifespan_pending"};}
!ll&&!rl&&r
008
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
600 8 ${$self->{lifespan_pending}}->done({ type => 'lifespan.shutdown' });
601 }
602  
603 8 $self->{started} = 0;
604 8 return $self;
605 }
606  
607 3 ▶sub state { shift->{state} // {} }
Subroutine state: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
+(shift())->{"state"} // {}
l!l
30
MC/DC0%0/1
+(shift())->{"state"} // {}
+(shift())->{"state"}
Truth table50%1/2
A
A= +(shift())->{"state"}
Aresult
11
00
608  
609 3 ▶sub run {
Subroutine run: called CC=2 SCAR=7.0
Pod documented
610 3 my ($class, $app, $callback) = @_;
611  
612 3 my $client = $class->new(app => $app, lifespan => 1);
613 3 $client->start;
614  
615 3 eval { $callback->($client) };
616 3 my $err = $@;
617  
618 3 $client->stop;
619 3 ▶ die $err if $err;
Branch: 1 branch
BranchTrueFalseTotal
if $err 0 3 3
620 }
621  
622 50 ▶sub _url_encode {
Subroutine _url_encode: called CC=1 SCAR=0.0
623 50 my ($str) = @_;
624 50 $str =~ s/([^A-Za-z0-9_\-.])/sprintf("%%%02X", ord($1))/eg;
625 50 return $str;
626 }
627  
628 # Normalize various input formats to arrayref of [key, value] pairs.
629 # Supports:
630 # - Hash with scalar values: { key => 'value' }
631 # Set a header on a headers structure (hashref or arrayref of pairs).
632 # If $replace is true, replaces existing value. Otherwise only sets if not present.
633 22 ▶sub _set_header {
Subroutine _set_header: called CC=11 SCAR=28.4
634 22 my ($headers_ref, $name, $value, $replace) = @_;
635 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
636  
637 22 ▶ if (!defined $$headers_ref) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $$headers_ref) 9 13 22
638 9 $$headers_ref = { $name => $value };
639 9 return;
640 }
641  
642 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
643 9 ▶ if ($replace) {
Branch: 1 branch
BranchTrueFalseTotal
if ($replace) { } 9 0 9
644 9 $$headers_ref->{$name} = $value;
645 } else {
646 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
647 }
648 } elsif (ref($$headers_ref) eq 'ARRAY') {
649 # Check if header already exists (case-insensitive)
650 4 my $found_idx;
651 4 for my $i (0 .. $#{$$headers_ref}) {
652 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
653 0 $found_idx = $i;
654 0 last;
655 }
656 }
657 4 ▶ if (defined $found_idx) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $found_idx) { } 0 4 4
658 0 ▶ $$headers_ref->[$found_idx][1] = $value if $replace;
Branch: 1 branch
BranchTrueFalseTotal
if $replace 0 0 0
659 } else {
660 4 push @{$$headers_ref}, [$name, $value];
661 }
662 }
663 }
664  
665 # - Hash with arrayref values: { key => ['v1', 'v2'] }
666 # - Arrayref of pairs: [['key', 'v1'], ['key', 'v2']]
667 # Returns arrayref of [key, value] pairs.
668 192 ▶sub _normalize_pairs {
Subroutine _normalize_pairs: called CC=11 SCAR=24.0
669 192 my ($input) = @_;
670 192 ▶ return [] unless defined $input;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $input 57 135 192
671  
672 # Arrayref of pairs: [['key', 'val'], ['key', 'val2']]
673 135 ▶ if (ref($input) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input eq "ARRAY") 6 129 135
674 # Validate it looks like pairs
675 6 for my $pair (@$input) {
676 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
677 unless ref($pair) eq 'ARRAY' && @$pair == 2;
678 }
679 5 return $input;
680 }
681  
682 # Hash (with scalar or arrayref values)
683 129 ▶ if (ref($input) eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $input eq "HASH") 128 1 129
684 128 my @pairs;
685 128 for my $key (sort keys %$input) {
686 43 my $val = $input->{$key};
687 43 ▶ if (ref($val) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $val eq 'ARRAY') { } 10 33 43
688 # Multiple values for this key
689 10 push @pairs, [$key, $_] for @$val;
690 } else {
691 # Single value
692 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
693 }
694 }
695 128 return \@pairs;
696 }
697  
698 1 croak "Expected hashref or arrayref of pairs, got " . ref($input);
699 }
700  
701 # Build headers array, merging defaults with request-specific headers.
702 # Request headers replace client defaults by key (case-insensitive).
703 75 ▶sub _build_headers {
Subroutine _build_headers: called CC=6 SCAR=17.9
704 75 my ($self, $request_headers) = @_;
705  
706 75 my @headers;
707  
708 # Default headers
709 75 push @headers, ['host', 'testserver'];
710  
711 # Normalize client default headers
712 75 my $default_pairs = _normalize_pairs($self->{headers});
713  
714 # Normalize request-specific headers
715 75 my $request_pairs = _normalize_pairs($request_headers);
716  
717 # Build set of keys to replace (lowercase)
718 73 my %replace_keys;
719 73 for my $pair (@$request_pairs) {
720 35 $replace_keys{lc($pair->[0])} = 1;
721 }
722  
723 # Add client defaults (skip if being replaced)
724 73 for my $pair (@$default_pairs) {
725 push @headers, [lc($pair->[0]), $pair->[1]]
726 6 ▶ unless $replace_keys{lc($pair->[0])};
Branch: 1 branch
BranchTrueFalseTotal
unless $replace_keys{lc $pair->[0]} 3 3 6
727 }
728  
729 # Add request-specific headers
730 73 for my $pair (@$request_pairs) {
731 35 push @headers, [lc($pair->[0]), $pair->[1]];
732 }
733  
734 # Add cookies
735 73 ▶ if (keys %{$self->{cookies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"cookies"};}) 2 71 73
736 2 my $cookie = join('; ', map { "$_=$self->{cookies}{$_}" } sort keys %{$self->{cookies}});
737 2 push @headers, ['cookie', $cookie];
738 }
739  
740 73 return \@headers;
741 }
742  
743 13 1;
744  
745 __END__
« blib/lib/PAGI/Request/BodyStream.pm ↑ Summary blib/lib/PAGI/Middleware/HTTPSRedirect.pm »