lib/Selenium/Client.pm

filter: Statementstmt 27.7% 73 / 263 Branchbran 0.0% 0 / 122 Conditioncond 0.0% 0 / 62 MC/DCmcdc 0.0% 0 / 35 Subroutinesub 53.8% 21 / 39 Podpod 100% 2 / 2 totaltotal 18.3% 96 / 523 CC 100 SCAR 57.8
CC
100
Cov
16%
_request
992.0
new
380.0
DESTROY
272.0
CRAP 322.7
↑ Summary lib/Selenium/Specification.pm »
1 package Selenium::Client;
2 1 $Selenium::Client::VERSION = '1.06';
3 # ABSTRACT: Module for communicating with WC3 standard selenium servers
4  
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 1 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use v5.28.0; # Before 5.006, v5.10.0 would not be understood.
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 1 ▶no warnings 'experimental';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use feature qw/signatures/;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 1 ▶use JSON::MaybeXS();
Subroutine BEGIN: called CC=1 SCAR=0.0
15 1 ▶use HTTP::Tiny();
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Carp qw{confess cluck};
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use File::Path qw{make_path};
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use File::HomeDir();
Subroutine BEGIN: called CC=1 SCAR=0.0
19 1 ▶use File::Slurper();
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use File::Spec();
Subroutine BEGIN: called CC=1 SCAR=0.0
21 1 ▶use Sub::Install();
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use Net::EmptyPort();
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶use Capture::Tiny qw{capture_merged};
Subroutine BEGIN: called CC=1 SCAR=0.0
24 1 ▶use Unicode::Normalize qw{NFC};
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 1 ▶use Selenium::Specification;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28  
29 ▶sub new($class,%options) {
Subroutine new: not called CC=19 SCAR=59.4
Pod documented
30 0 ▶ $options{version} //= 'stable';
Condition0%0/2
$options{"version"} //= "stable"
l!l
00
MC/DC0%0/1
$options{"version"} //= "stable"
$options{"version"}
Truth table0%0/2
A
A= $options{"version"}
Aresult
11
00
31 0 ▶ $options{port} //= 4444;
Condition0%0/2
$options{"port"} //= 4444
l!l
00
MC/DC0%0/1
$options{"port"} //= 4444
$options{"port"}
Truth table0%0/2
A
A= $options{"port"}
Aresult
11
00
32  
33 #XXX geckodriver doesn't bind to localhost lol
34 0 ▶ $options{host} //= '127.0.0.1';
Condition0%0/2
$options{"host"} //= "127.0.0.1"
l!l
00
MC/DC0%0/1
$options{"host"} //= "127.0.0.1"
$options{"host"}
Truth table0%0/2
A
A= $options{"host"}
Aresult
11
00
35 0 ▶ $options{host} = '127.0.0.1' if $options{host} eq 'localhost';
Branch: 1 branch
BranchTrueFalseTotal
if $options{"host"} eq "localhost" 0 0 0
36  
37 0 ▶ $options{nofetch} //= 1;
Condition0%0/2
$options{"nofetch"} //= 1
l!l
00
MC/DC0%0/1
$options{"nofetch"} //= 1
$options{"nofetch"}
Truth table0%0/2
A
A= $options{"nofetch"}
Aresult
11
00
38 0 ▶ $options{scheme} //= 'http';
Condition0%0/2
$options{"scheme"} //= "http"
l!l
00
MC/DC0%0/1
$options{"scheme"} //= "http"
$options{"scheme"}
Truth table0%0/2
A
A= $options{"scheme"}
Aresult
11
00
39 0 ▶ $options{prefix} //= '';
Condition0%0/2
$options{"prefix"} //= ""
l!l
00
MC/DC0%0/1
$options{"prefix"} //= ""
$options{"prefix"}
Truth table0%0/2
A
A= $options{"prefix"}
Aresult
11
00
40 0 ▶ $options{ua} //= HTTP::Tiny->new();
Condition0%0/3
$options{"ua"} //= "HTTP::Tiny"->new
l!l&&r!l&&!r
000
MC/DC0%0/2
$options{"ua"} //= "HTTP::Tiny"->new
$options{"ua"} "HTTP::Tiny"->new
Truth table0%0/3
A //= B
A= $options{"ua"}B= "HTTP::Tiny"->new
ABresult
1X1
011
000
41 0 ▶ $options{client_dir} //= File::HomeDir::my_home()."/.selenium";
Condition0%0/2
$options{"client_dir"} //= File::HomeDir::my_home() . '/.selenium'
l!l
00
MC/DC0%0/1
$options{"client_dir"} //= File::HomeDir::my_home() . '/.selenium'
$options{"client_dir"}
Truth table0%0/2
A
A= $options{"client_dir"}
Aresult
11
00
42 0 ▶ $options{driver} //= "SeleniumHQ::Jar";
Condition0%0/2
$options{"driver"} //= "SeleniumHQ::Jar"
l!l
00
MC/DC0%0/1
$options{"driver"} //= "SeleniumHQ::Jar"
$options{"driver"}
Truth table0%0/2
A
A= $options{"driver"}
Aresult
11
00
43 0 ▶ $options{post_callbacks} //= [];
Condition0%0/2
$options{"post_callbacks"} //= []
l!l
00
MC/DC0%0/1
$options{"post_callbacks"} //= []
$options{"post_callbacks"}
Truth table0%0/2
A
A= $options{"post_callbacks"}
Aresult
11
00
44 0 ▶ $options{auto_close} //= 1;
Condition0%0/2
$options{"auto_close"} //= 1
l!l
00
MC/DC0%0/1
$options{"auto_close"} //= 1
$options{"auto_close"}
Truth table0%0/2
A
A= $options{"auto_close"}
Aresult
11
00
45 0 ▶ $options{browser} //= '';
Condition0%0/2
$options{"browser"} //= ""
l!l
00
MC/DC0%0/1
$options{"browser"} //= ""
$options{"browser"}
Truth table0%0/2
A
A= $options{"browser"}
Aresult
11
00
46 0 ▶ $options{headless} //= 1;
Condition0%0/2
$options{"headless"} //= 1
l!l
00
MC/DC0%0/1
$options{"headless"} //= 1
$options{"headless"}
Truth table0%0/2
A
A= $options{"headless"}
Aresult
11
00
47 0 ▶ $options{normalize} //= 1;
Condition0%0/2
$options{"normalize"} //= 1
l!l
00
MC/DC0%0/1
$options{"normalize"} //= 1
$options{"normalize"}
Truth table0%0/2
A
A= $options{"normalize"}
Aresult
11
00
48 0 ▶ $options{fatal} //= 1;
Condition0%0/2
$options{"fatal"} //= 1
l!l
00
MC/DC0%0/1
$options{"fatal"} //= 1
$options{"fatal"}
Truth table0%0/2
A
A= $options{"fatal"}
Aresult
11
00
49 # Use the hardcoded JSON version of the stable spec in Selenium::Specification's DATA section.
50 0 ▶ $options{hardcode} //= 1;
Condition0%0/2
$options{"hardcode"} //= 1
l!l
00
MC/DC0%0/1
$options{"hardcode"} //= 1
$options{"hardcode"}
Truth table0%0/2
A
A= $options{"hardcode"}
Aresult
11
00
51  
52 #create client_dir and log-dir
53 0 my $dir = File::Spec->catdir( $options{client_dir},"perl-client" );
54 0 make_path($dir);
55 #Grab the spec
56 0 $options{spec}= Selenium::Specification::read($options{client_dir},$options{version},$options{nofetch}, $options{hardcode});
57  
58 0 my $self = bless(\%options, $class);
59 0 $self->{sessions} = [];
60  
61 0 $self->_build_subs();
62 0 ▶ $self->_spawn() if $options{host} eq '127.0.0.1';
Branch: 1 branch
BranchTrueFalseTotal
if $options{"host"} eq "127.0.0.1" 0 0 0
63 0 return $self;
64 }
65  
66  
67 0 ▶sub catalog($self,$printed=0) {
Subroutine catalog: not called CC=4 SCAR=30.0
Pod documented
68 0 ▶ return $self->{spec} unless $printed;
Branch: 1 branch
BranchTrueFalseTotal
unless $printed 0 0 0
69 0 foreach my $method (keys(%{$self->{spec}})) {
70 0 print "$method: $self->{spec}{$method}{href}\n";
71 }
72 0 return $self->{spec};
73 }
74  
75 ▶my %browser_opts = (
Subroutine __ANON__: not called CC=2 SCAR=17.9
76 firefox => {
77 name => 'moz:firefoxOptions',
78 headless => sub ($c) {
79 0 ▶ $c->{args} //= [];
Condition0%0/2
$c->{"args"} //= []
l!l
00
MC/DC0%0/1
$c->{"args"} //= []
$c->{"args"}
Truth table0%0/2
A
A= $c->{"args"}
Aresult
11
00
80 0 push(@{$c->{args}}, '-headless');
81 },
82 },
83 ▶ chrome => {
Subroutine __ANON__: not called CC=2 SCAR=17.9
84 name => 'goog:chromeOptions',
85 headless => sub ($c) {
86 0 ▶ $c->{args} //= [];
Condition0%0/2
$c->{"args"} //= []
l!l
00
MC/DC0%0/1
$c->{"args"} //= []
$c->{"args"}
Truth table0%0/2
A
A= $c->{"args"}
Aresult
11
00
87 0 push(@{$c->{args}}, 'headless');
88 },
89 },
90 ▶ MicrosoftEdge => {
Subroutine __ANON__: not called CC=2 SCAR=17.9
91 name =>'ms:EdgeOptions',
92 headless => sub ($c) {
93 0 ▶ $c->{args} //= [];
Condition0%0/2
$c->{"args"} //= []
l!l
00
MC/DC0%0/1
$c->{"args"} //= []
$c->{"args"}
Truth table0%0/2
A
A= $c->{"args"}
Aresult
11
00
94 0 push(@{$c->{args}}, 'headless');
95 },
96 },
97 1 );
98  
99 ▶sub _build_caps($self,%options) {
Subroutine _build_caps: not called CC=7 SCAR=40.3
100 0 ▶ $options{browser} = $self->{browser} if $self->{browser};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"browser"} 0 0 0
101 0 ▶ $options{headless} = $self->{headless} if $self->{headless};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"headless"} 0 0 0
102  
103 my $c = {
104 browserName => $options{browser},
105 0 };
106 0 my $browser = $browser_opts{$options{browser}};
107  
108 0 ▶ if ($browser) {
Branch: 1 branch
BranchTrueFalseTotal
if ($browser) 0 0 0
109 0 my $browseropts = {};
110 0 foreach my $k (keys %$browser) {
111 0 ▶ next if $k eq 'name';
Branch: 1 branch
BranchTrueFalseTotal
if $k eq "name" 0 0 0
112 0 ▶ $browser->{$k}->($browseropts) if $options{$k};
Branch: 1 branch
BranchTrueFalseTotal
if $options{$k} 0 0 0
113 }
114 0 $c->{$browser->{name}} = $browseropts;
115 }
116  
117 return (
118 0 capabilities => {
119 alwaysMatch => $c,
120 },
121 );
122 }
123  
124 ▶sub _build_subs($self) {
Subroutine _build_subs: not called CC=3 SCAR=24.8
125 0 foreach my $sub (keys(%{$self->{spec}})) {
126 Sub::Install::install_sub(
127 {
128 code => sub {
129 0 ▶ my $self = shift;
Subroutine __ANON__: not called CC=1 SCAR=6.9
130 0 return $self->_request($sub,@_);
131 },
132 0 ▶ as => $sub,
Branch: 1 branch
BranchTrueFalseTotal
unless "Selenium::Client"->can($sub) 0 0 0
133 into => "Selenium::Client",
134 }
135 ) unless "Selenium::Client"->can($sub);
136 }
137 }
138  
139 #Check if server already up and spawn if no
140 ▶sub _spawn($self) {
Subroutine _spawn: not called CC=3 SCAR=24.8
141 0 ▶ return $self->Status() if Net::EmptyPort::wait_port( $self->{port}, 1 );
Branch: 1 branch
BranchTrueFalseTotal
if Net::EmptyPort::wait_port($self->{"port"}, 1) 0 0 0
142  
143 # Pick a random port for the new server
144 0 $self->{port} = Net::EmptyPort::empty_port();
145  
146 0 my $driver_file = "Selenium/Driver/$self->{driver}.pm";
147 0 $driver_file =~ s/::/\//g;
148 0 ▶ eval { require $driver_file } or confess "Could not load $driver_file, check your PERL5LIB: $@";
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require $driver_file } } or confess("Could not load $driver_file, check your PERL5LIB: $@") 0 0 0
149 0 my $driver = "Selenium::Driver::$self->{driver}";
150  
151 0 $driver->build_spawn_opts($self);
152 0 return $self->_do_spawn();
153 }
154  
155 ▶sub _do_spawn($self) {
Subroutine _do_spawn: not called CC=7 SCAR=40.3
156  
157 #XXX on windows we will *never* terminate if we are listening for *anything*
158 #XXX so we have to just bg & ignore, unfortunately (also have to system())
159 0 ▶ if (_is_windows()) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_windows()) 0 0 0
160 0 $self->{pid} = qq/$self->{driver}:$self->{port}/;
161 0 my @cmdprefix = ("start /MIN", qq{"$self->{pid}"});
162  
163 # Selenium JAR controls it's own logging because Java
164 0 my @cmdsuffix;
165 0 ▶ @cmdsuffix = ('>', $self->{log_file}, '2>&1') unless $self->{driver_class} eq 'Selenium::Driver::SeleniumHQ::Jar';
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"driver_class"} eq "Selenium::Driver::SeleniumHQ::Jar" 0 0 0
166  
167 0 my $cmdstring = join(' ', @cmdprefix, @{$self->{command}}, @cmdsuffix );
168 0 ▶ print "$cmdstring\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
169 0 system($cmdstring);
170 0 return $self->_wait();
171 }
172  
173 0 ▶ print "@{$self->{command}}\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
174 0 ▶ my $pid = fork // confess("Could not fork");
Condition0%0/3
fork // confess("Could not fork")
l!l&&r!l&&!r
000
MC/DC0%0/2
fork // confess("Could not fork")
fork confess("Could not fork")
Truth table0%0/3
A // B
A= forkB= confess("Could not fork")
ABresult
1X1
011
000
175 0 ▶ if ($pid) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid) 0 0 0
176 0 $self->{pid} = $pid;
177 0 return $self->_wait();
178 }
179 0 open(my $fh, '>>', $self->{log_file});
180 0 ▶ capture_merged { exec(@{$self->{command}}) } stdout => $fh;
Subroutine __ANON__: not called CC=1 SCAR=6.9
181 }
182  
183 ▶sub _wait ($self) {
Subroutine _wait: not called CC=4 SCAR=30.0
184 0 ▶ print "Waiting for port to come up..." if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
185 0 ▶ Net::EmptyPort::wait_port( $self->{port}, 30 )
Branch: 1 branch
BranchTrueFalseTotal
Net::EmptyPort::wait_port($self->{"port"}, 30) or confess(qq[Server never came up on port $self->{"port"} after 30s!]) 0 0 0
186 or confess("Server never came up on port $self->{port} after 30s!");
187 0 ▶ print "done\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
188 0 return $self->Status();
189 }
190  
191 ▶sub DESTROY($self) {
Subroutine DESTROY: not called CC=16 SCAR=56.1
192 0 ▶ return unless $self->{auto_close};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"auto_close"} 0 0 0
193  
194 0 local $?; # Avoid affecting the exit status
195  
196 0 ▶ print "Shutting down active sessions...\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
197 #murder all sessions we spawned so that die() cleans up properly
198 0 ▶ if ($self->{ua} && @{$self->{sessions}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"ua"} and @{$self->{"sessions"};}) 0 0 0
Condition0%0/3
$self->{"ua"} and @{$self->{"sessions"};}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"ua"} and @{$self->{"sessions"};}
$self->{"ua"} @{$self->{"sessions"};}
Truth table0%0/3
A and B
A= $self->{"ua"}B= @{$self->{"sessions"};}
ABresult
0X0
100
111
199 0 foreach my $session (@{$self->{sessions}}) {
200 # An attempt was made. The session *might* already be dead.
201 0 eval { $self->DeleteSession( sessionid => $session ) };
202 }
203 }
204  
205 #Kill the server if we spawned one
206 0 ▶ return unless $self->{pid};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"pid"} 0 0 0
207 0 ▶ print "Attempting to kill server process...\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
208  
209 0 ▶ if (_is_windows()) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_windows()) 0 0 0
210 0 my $killer = qq[taskkill /FI "WINDOWTITLE eq $self->{pid}"];
211 0 ▶ print "$killer\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
212 #$killer .= ' > nul 2&>1' unless $self->{debug};
213 0 system($killer);
214 0 return 1;
215 }
216  
217 0 my $sig = 'TERM';
218 0 kill $sig, $self->{pid};
219  
220 0 ▶ print "Issued SIG$sig to $self->{pid}, waiting...\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
221  
222 # 0 is always WCONTINUED, 1 is always WNOHANG, and POSIX is an expensive import
223 # When 0 is returned, the process is still active, so it needs more persuasion
224 0 foreach (0..3) {
225 0 ▶ return unless waitpid( $self->{pid}, 1) == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless waitpid($self->{"pid"}, 1) == 0 0 0 0
226 0 sleep 1;
227 }
228  
229 # Advanced persuasion
230 0 ▶ print "Forcibly terminating selenium server process...\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
231 0 kill('TERM', $self->{pid});
232  
233 #XXX unfortunately I can't just do a SIGALRM, because blocking system calls can't be intercepted on win32
234 0 foreach (0..$self->{timeout}) {
235 0 ▶ return unless waitpid( $self->{pid}, 1 ) == 0;
Branch: 1 branch
BranchTrueFalseTotal
unless waitpid($self->{"pid"}, 1) == 0 0 0 0
236 0 sleep 1;
237 }
238 0 warn "Could not shut down selenium server!";
239 0 return;
240 }
241  
242 sub _is_windows {
243 0 ▶ return grep { $^O eq $_ } qw{msys MSWin32};
Subroutine _is_windows: not called CC=1 SCAR=6.9
244 }
245  
246 #XXX some of the methods require content being null, some require it to be an obj with no params LOL
247 1 our @bad_methods = qw{AcceptAlert DismissAlert Back Forward Refresh ElementClick MaximizeWindow MinimizeWindow FullscreenWindow SwitchToParentFrame ElementClear};
248  
249 #Exempt some calls from return processing
250 1 our @no_process = qw{Status GetWindowRect GetElementRect GetAllCookies};
251  
252 ▶sub _request($self, $method, %params) {
Subroutine _request: not called CC=31 SCAR=69.0
253 0 my $subject = $self->{spec}->{$method};
254  
255 #TODO handle compressed output from server
256 0 my %options = (
257 headers => {
258 'Content-Type' => 'application/json; charset=utf-8',
259 'Accept' => 'application/json; charset=utf-8',
260 'Accept-Encoding' => 'identity',
261 },
262 );
263 0 ▶ $options{content} = '{}' if grep { $_ eq $method } @bad_methods;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ eq $method;} @Selenium::Client::bad_methods 0 0 0
264  
265 0 my $url = "$self->{scheme}://$self->{host}:$self->{port}$subject->{uri}";
266  
267 # Remove parameters to inject into child objects
268 0 ▶ my $inject_key = exists $params{inject} ? delete $params{inject} : undef;
Branch: 1 branch
BranchTrueFalseTotal
exists $params{'inject'} ? : 0 0 0
269 0 ▶ my $inject_value = $inject_key ? $params{$inject_key} : '';
Branch: 1 branch
BranchTrueFalseTotal
$inject_key ? : 0 0 0
270 0 my $inject;
271 0 ▶ $inject = { to_inject => { $inject_key => $inject_value } } if $inject_key && $inject_value;
Branch: 1 branch
BranchTrueFalseTotal
if $inject_key and $inject_value 0 0 0
Condition0%0/3
$inject_key and $inject_value
!ll&&!rl&&r
000
MC/DC0%0/2
$inject_key and $inject_value
$inject_key $inject_value
Truth table0%0/3
A and B
A= $inject_keyB= $inject_value
ABresult
0X0
100
111
272  
273 # Keep sessions for passing to grandchildren
274 0 ▶ $inject->{to_inject}{sessionid} = $params{sessionid} if exists $params{sessionid};
Branch: 1 branch
BranchTrueFalseTotal
if exists $params{"sessionid"} 0 0 0
275  
276 #If we have no extra params, and this is getSession, simplify
277 0 ▶ %params = $self->_build_caps() if $method eq 'NewSession' && !%params;
Branch: 1 branch
BranchTrueFalseTotal
if $method eq "NewSession" and not %params 0 0 0
Condition0%0/3
$method eq "NewSession" and not %params
!ll&&!rl&&r
000
MC/DC0%0/2
$method eq "NewSession" and not %params
$method eq "NewSession" not %params
Truth table0%0/3
A and not(B)
A= $method eq "NewSession"B= not %params
ABresult
0X0
100
111
278  
279 0 foreach my $param (keys(%params)) {
280 0 ▶ confess "$param is required for $method" unless exists $params{$param};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $params{$param} 0 0 0
281 0 ▶ delete $params{$param} if $url =~ s/{\Q$param\E}/$params{$param}/g;
Branch: 1 branch
BranchTrueFalseTotal
if $url =~ s/{\Q$param\E}/$params{$param}/gu 0 0 0
282 }
283  
284 0 ▶ if (%params) {
Branch: 1 branch
BranchTrueFalseTotal
if (%params) 0 0 0
285 0 $options{content} = JSON::MaybeXS::encode_json(\%params);
286 0 $options{headers}{'Content-Length'} = length($options{content});
287 }
288  
289 0 ▶ print "$subject->{method} $url\n" if $self->{debug};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 0 0 0
290 0 ▶ print "Body: $options{content}\n" if $self->{debug} && exists $options{content};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} and exists $options{"content"} 0 0 0
Condition0%0/3
$self->{"debug"} and exists $options{"content"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"debug"} and exists $options{"content"}
$self->{"debug"} exists $options{"content"}
Truth table0%0/3
A and B
A= $self->{"debug"}B= exists $options{"content"}
ABresult
0X0
100
111
291  
292 0 my $res = $self->{ua}->request($subject->{method}, $url, \%options);
293  
294 0 my @cbret;
295 0 foreach my $cb (@{$self->{post_callbacks}}) {
296 0 ▶ if ($cb && ref $cb eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ($cb and ref $cb eq "CODE") 0 0 0
Condition0%0/3
$cb and ref $cb eq "CODE"
!ll&&!rl&&r
000
MC/DC0%0/2
$cb and ref $cb eq "CODE"
$cb ref $cb eq "CODE"
Truth table0%0/3
A and B
A= $cbB= ref $cb eq "CODE"
ABresult
0X0
100
111
297 0 @options{qw{url method}} = ($url,$subject->{method});
298 0 ▶ $options{content} = \%params if %params;
Branch: 1 branch
BranchTrueFalseTotal
if %params 0 0 0
299 0 my $ret = $cb->($self, $res, \%options);
300 0 ▶ push(@cbret,$ret) if $ret;
Branch: 1 branch
BranchTrueFalseTotal
if $ret 0 0 0
301 }
302 0 ▶ return $cbret[0] if @cbret == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @cbret == 1 0 0 0
303 0 ▶ return @cbret if @cbret;
Branch: 1 branch
BranchTrueFalseTotal
if @cbret 0 0 0
304 }
305  
306 0 ▶ print "$res->{status} : $res->{content}\n" if $self->{debug} && ref $res eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} and ref $res eq "HASH" 0 0 0
Condition0%0/3
$self->{"debug"} and ref $res eq "HASH"
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"debug"} and ref $res eq "HASH"
$self->{"debug"} ref $res eq "HASH"
Truth table0%0/3
A and B
A= $self->{"debug"}B= ref $res eq "HASH"
ABresult
0X0
100
111
307  
308 # all the selenium servers are UTF-8
309 0 my $normal = $res->{content};
310 0 ▶ $normal = NFC( $normal ) if $self->{normalize};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"normalize"} 0 0 0
311 0 my $decoded_content = eval { JSON::MaybeXS->new()->utf8()->decode( $normal ) };
312  
313 0 ▶ if ($self->{fatal}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'fatal'}) { } 0 0 0
314 0 ▶ confess "$res->{reason} :\n Consult $subject->{href}\nRaw Error:\n$res->{content}\n" unless $res->{success};
Branch: 1 branch
BranchTrueFalseTotal
unless $res->{"success"} 0 0 0
315 } else {
316 0 ▶ cluck "$res->{reason} :\n Consult $subject->{href}\nRaw Error:\n$res->{content}\n" unless $res->{success};
Branch: 1 branch
BranchTrueFalseTotal
unless $res->{"success"} 0 0 0
317 }
318  
319 0 ▶ if (grep { $method eq $_ } @no_process) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$method eq $_;} @Selenium::Client::no_process) 0 0 0
320 0 ▶ return @{$decoded_content->{value}} if ref $decoded_content->{value} eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $decoded_content->{"value"} eq "ARRAY" 0 0 0
321 0 return $decoded_content->{value};
322 }
323 0 return $self->_objectify($decoded_content,$inject);
324 }
325  
326 our %classes = (
327 capabilities => { class => 'Selenium::Capabilities' },
328 sessionId => {
329 class => 'Selenium::Session',
330 destroy_callback => sub {
331 0 ▶ my $self = shift;
Subroutine __ANON__: not called CC=2 SCAR=17.9
332 0 ▶ $self->DeleteSession() unless $self->{deleted};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"deleted"} 0 0 0
333 },
334 callback => sub {
335 0 ▶ my ($self,$call) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
336 0 ▶ $self->{deleted} = 1 if $call eq 'DeleteSession';
Branch: 1 branch
BranchTrueFalseTotal
if $call eq "DeleteSession" 0 0 0
337 },
338 },
339 # Whoever thought this parameter name was a good idea...
340 1 'element-6066-11e4-a52e-4f735466cecf' => {
341 class => 'Selenium::Element',
342 },
343 );
344  
345 ▶sub _objectify($self,$result,$inject) {
Subroutine _objectify: not called CC=10 SCAR=47.0
346 0 my $subject = $result->{value};
347 0 ▶ return $subject unless grep { ref $subject eq $_ } qw{ARRAY HASH};
Branch: 1 branch
BranchTrueFalseTotal
unless grep {ref $subject eq $_;} "ARRAY", "HASH" 0 0 0
348 0 ▶ $subject = [$subject] unless ref $subject eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $subject eq "ARRAY" 0 0 0
349  
350 0 my @objs;
351 0 foreach my $to_objectify (@$subject) {
352 # If we have just data return it
353 0 ▶ return @$subject if ref $to_objectify ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $to_objectify ne "HASH" 0 0 0
354  
355 0 my @objects = keys(%$to_objectify);
356 0 foreach my $object (@objects) {
357 0 my $has_class = exists $classes{$object};
358  
359 0 ▶ my $base_object = $inject // {};
Condition0%0/2
$inject // {}
l!l
00
MC/DC0%0/1
$inject // {}
$inject
Truth table0%0/2
A
A= $inject
Aresult
11
00
360 0 $base_object->{lc($object)} = $to_objectify->{$object};
361 0 $base_object->{sortField} = lc($object);
362  
363 my $to_push = $has_class ?
364 0 ▶ $classes{$object}{class}->new($self, $base_object ) :
Branch: 1 branch
BranchTrueFalseTotal
$has_class ? : 0 0 0
365 $to_objectify;
366 0 $to_push->{sortField} = lc($object);
367 # Save sessions for destructor
368 0 ▶ push(@{$self->{sessions}}, $to_push->{sessionid}) if ref $to_push eq 'Selenium::Session';
Branch: 1 branch
BranchTrueFalseTotal
if ref $to_push eq "Selenium::Session" 0 0 0
369 0 push(@objs,$to_push);
370 }
371 }
372 0 @objs = sort { $a->{sortField} cmp $b->{sortField} } @objs;
373 0 ▶ return $objs[0] if @objs == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @objs == 1 0 0 0
374 0 return @objs;
375 }
376  
377 1 1;
378  
379  
380 package Selenium::Capabilities;
381 1 $Selenium::Capabilities::VERSION = '1.06';
382 1 ▶use parent qw{Selenium::Subclass};
Subroutine BEGIN: called CC=1 SCAR=0.0
383 1 1;
384 package Selenium::Session;
385 1 $Selenium::Session::VERSION = '1.06';
386 1 ▶use parent qw{Selenium::Subclass};
Subroutine BEGIN: called CC=1 SCAR=0.0
387 1 1;
388 package Selenium::Element;
389 1 $Selenium::Element::VERSION = '1.06';
390 1 ▶use parent qw{Selenium::Subclass};
Subroutine BEGIN: called CC=1 SCAR=0.0
391 1 1;
392  
393 __END__
394  
395 =pod
396  
397 =encoding UTF-8
398  
399 =head1 NAME
400  
401 Selenium::Client - Module for communicating with WC3 standard selenium servers
402  
403 =head1 VERSION
404  
405 version 1.06
406  
407 =head1 CONSTRUCTOR
408  
409 =head2 new(%options) = Selenium::Client
410  
411 Either connects to a driver at the specified host and port, or spawns one locally.
412  
413 Spawns a server on a random port in the event the host is "localhost" (or 127.0.0.1) and nothing is reachable on the provided port.
414  
415 Returns a Selenium::Client object with all WC3 methods exposed.
416  
417 To view all available methods and their documentation, the catalog() method is provided.
418  
419 Remote Server options:
420  
421 =over 4
422  
423 =item C<version> ENUM (stable,draft,unstable) - WC3 Spec to use.
424  
425 Default: stable
426  
427 =item C<host> STRING - hostname of your server.
428  
429 Default: localhost
430  
431 =item C<prefix> STRING - any prefix needed to communicate with the server, such as /wd, /hub, /wd/hub, or /grid
432  
433 Default: ''
434  
435 =item C<port> INTEGER - Port which the server is listening on.
436  
437 Default: 4444
438 Note: when spawning, this will be ignored and a random port chosen instead.
439  
440 =item C<scheme> ENUM (http,https) - HTTP scheme to use
441  
442 Default: http
443  
444 =item C<nofetch> BOOL - Do not check for a newer copy of the WC3 specifications on startup if we already have them available.
445  
446 Default: 1
447  
448 =item C<client_dir> STRING - Where to store specs and other files downloaded when spawning servers.
449  
450 Default: ~/.selenium
451  
452 =item C<debug> BOOLEAN - Whether to print out various debugging output.
453  
454 Default: false
455  
456 =item C<auto_close> BOOLEAN - Automatically close spawned selenium servers and sessions.
457  
458 Only turn this off when you are debugging.
459  
460 Default: true
461  
462 =item C<normalize> BOOLEAN - Automatically normalize UTF-8 output using Normal Form C (NFC).
463  
464 If another normal form is preferred, you should turn this off and directly use L<Unicode::Normalize>.
465  
466 Default: true
467  
468 =item C<post_callbacks> ARRAY[CODE] - Executed after each request to the selenium server.
469  
470 Callbacks are passed $self, an HTTP::Tiny response hashref and the request hashref.
471 Use this to implement custom error handlers, testing harness modifications etc.
472  
473 Return a truthy value to immediately exit the request subroutine after all cbs are executed.
474 Truthy values (if any are returned) are returned in order encountered.
475  
476 =item C<fatal> BOOLEAN - Whether or not to die on errors from the selenium server.
477  
478 Default: true
479  
480 Useful to turn off when using post_callbacks as error handlers.
481  
482 =back
483  
484 When using remote servers, you should take extra care that they automatically clean up after themselves.
485 We cannot guarantee the state of said servers after interacting with them.
486  
487 Spawn Options:
488  
489 =over 4
490  
491 =item C<driver> STRING - Plug-in module used to spawn drivers when needed.
492  
493 Included are 'Auto', 'SeleniumHQ::Jar', 'Gecko', 'Chrome', 'Edge'
494 Default: Auto
495  
496 The 'Auto' Driver will pick whichever direct driver looks like it will work for your chosen browser.
497 If we can't find one, we'll fall back to SeleniumHQ::Jar.
498  
499 =item C<browser> STRING - desired browser. Used by the 'Auto' Driver.
500  
501 Default: Blank
502  
503 =item C<headless> BOOL - Whether to run the browser headless. Ignored by 'Safari' Driver.
504  
505 Default: True
506  
507 =item C<driver_version> STRING - Version of your driver software you wish to download and run.
508  
509 Blank and Partial versions will return the latest sub-version available.
510 Only relevant to Drivers which auto-download (currently only SeleniumHQ::Jar).
511  
512 Default: Blank
513  
514 =back
515  
516 Driver modules should be in the Selenium::Driver namespace.
517 They may implement additional parameters which can be passed into the options hash.
518  
519 =head1 METHODS
520  
521 =head2 Most of the methods are dynamic based on the selenium spec
522  
523 This means that the Selenium::Client class can directly call all selenium methods.
524 We provide a variety of subclasses as sugar around this:
525  
526 Selenium::Session
527 Selenium::Capabilities
528 Selenium::Element
529  
530 Which will simplify correctly passing arguments in the case of sessions and elements.
531 However, this does not change the fact that you still must take great care.
532 We do no validation whatsoever of the inputs, and the selenium server likes to hang when you give it an invalid input.
533 So take great care and understand this is what "script hung and died" means -- you passed the function an unrecognized argument.
534  
535 This is because Selenium::Specification cannot (yet!) parse the inputs and outputs for each endpoint at this time.
536 As such we can't just filter against the relevant prototype.
537  
538 In any case, all subs will look like this, for example:
539  
540 $client->Method( key => value, key1 => value1, ...) = (@return_per_key)
541  
542 The options passed in are basically JSON serialized and passed directly as a POST body (or included into the relevant URL).
543 We return a list of items which are a hashref per item in the result (some of them blessed).
544 For example, NewSession will return a Selenium::Capabilities and Selenium::Session object.
545 The order in which they are returned will be ordered alphabetically.
546  
547 =head2 Passing Capabilities to NewSession()
548  
549 By default, we will pass a set of capabilities that satisfy the options passed to new().
550  
551 If you want *other* capabilities, pass them directly to NewSession as documented in the WC3 spec.
552  
553 However, this will ignore what you passed to new(). Caveat emptor.
554  
555 For the general list of options supported by each browser, see here:
556  
557 =over 4
558  
559 =item C<Firefox> - https://developer.mozilla.org/en-US/docs/Web/WebDriver/Capabilities/firefoxOptions
560  
561 =item C<Chrome> - https://sites.google.com/a/chromium.org/chromedriver/capabilities
562  
563 =item C<Edge> - https://docs.microsoft.com/en-us/microsoft-edge/webdriver-chromium/capabilities-edge-options
564  
565 =item C<Safari> - https://developer.apple.com/documentation/webkit/about_webdriver_for_safari
566  
567 =back
568  
569 =head2 catalog(BOOL verbose=0) = HASHREF
570  
571 Returns the entire method catalog.
572 Prints out every method and a link to the relevant documentation if verbose is true.
573  
574 =head1 SUBCLASSES
575  
576 =head2 Selenium::Capabilities
577  
578 Returned as first element from NewSession().
579 Query this object for various things about the server capabilities.
580  
581 =head2 Selenium::Session
582  
583 Returned as second element of NewSession().
584 Has a destructor which will automatically clean itself up when we go out of scope.
585 Alternatively, when the driver object goes out of scope, all sessions it spawned will be destroyed.
586  
587 You can call Selenium methods on this object which require a sessionid without passing it explicitly.
588  
589 =head2 Selenium::Element
590  
591 Returned from find element calls.
592  
593 You can call Selenium methods on this object which require a sessionid and elementid without passing them explicitly.
594  
595 =head1 STUPID SELENIUM TRICKS
596  
597 There are a variety of quirks with Selenium drivers that you just have to put up with, don't log bugs on these behaviors.
598 Most of this will probably change in the future,
599 as these are firmly in the "undefined/undocumented behavior" stack of the browser vendors.
600  
601 =head3 alerts
602  
603 If you have an alert() open on the page, all calls to the selenium server will 500 until you dismiss or accept it.
604  
605 Also be aware that chrome will re-fire alerts when you do a forward() or back() event, unlike firefox.
606  
607 =head3 tag names
608  
609 Safari returns ALLCAPS names for tags. amazing
610  
611 =head2 properties and attributes
612  
613 Many I<valid> properties/attributes will I<never> be accessible via GetProperty() or GetAttribute().
614  
615 For example, getting the "for" value of a <label> element is flat-out impossible using either GetProperty or GetAttribute.
616 There are many other such cases, the most common being "non-standard" properties such as aria-* or things used by JS templating engines.
617 You are better off using JS shims to do any element inspection.
618  
619 Similarly the IsElementSelected() method is quite unreliable.
620 We can work around this however by just using the CSS :checked pseudoselector when looking for elements, as that actually works.
621  
622 It is this for these reasons that you should consider abandoning Selenium for something that can actually do this correctly such as L<Playwright>.
623  
624 =head3 windows
625  
626 When closing windows, be aware you will be NOT be shot back to the last window you had focused before switching to the current one.
627 You have to manually switch back to an existing one.
628  
629 Opening _blank targeted links *does not* automatically switch to the new window.
630 The procedure for handling links of such a sort to do this is as follows:
631  
632 # Get current handle
633 my $handle = $session->GetWindowHandle();
634  
635 # Assuming the element is an href with target=_blank ...
636 $element->ClickElement();
637  
638 # Get all handles and filter for the ones that we aren't currently using
639 my @handles = $session->GetWindowHandles();
640 my @new_handles = grep { $handle != $_ } @handles;
641  
642 # Use pop() as it will always be returned in the order windows are opened
643 $session->SwitchToWindow( handle => pop(@new_handles) );
644  
645 Different browser drivers also handle window handles differently.
646 Chrome in particular demands you stringify handles returned from the driver.
647 It also seems to be a lot less cooperative than firefox when setting the WindowRect.
648  
649 =head3 frames
650  
651 In the SwitchToFrame documentation, the claim is made that passing the element ID of a <frame> or <iframe> will switch the browsing context of the session to that frame.
652 This is quite obviously false in every driver known. Example:
653  
654 # This does not ever work
655 $session->SwitchToFrame( id => $session->FindElement( using => 'css selector', value => '#frame' )->{elementid} );
656  
657 The only thing that actually works is switching by array index as you would get from window.frames in javascript:
658  
659 # Supposing #frame is the first frame encountered in the DOM, this works
660 $session->SwitchToFrame( id => 0 );
661  
662 As you might imagine this is a significant barrier to reliable automation as not every JS interperter will necessarily index in the same order.
663 Nor is there, say, a GetFrames() method from which you could sensibly pick which one you want and move from there.
664 The only workaround here would be to always execute a script to interrogate window.frames and guess which one you want based on the output of that.
665  
666 =head3 arguments
667  
668 If you make a request of the server with arguments it does not understand it will hang for 30s, so set a SIGALRM handler if you insist on doing so.
669  
670 =head2 MSWin32 issues
671  
672 The default version of the Java JRE from java.com is quite simply ancient on windows, and SeleniumHQ develops against JDK 11 and better.
673 So make sure your JDK bin dir is in your PATH I<before> the JRE path (or don't install an ancient JRE lol)
674  
675 If you don't, you'll probably get insta-explosions due to their usage of new language features.
676 Kind of like how you'll die if you use a perl without signatures with this module :)
677  
678 Also, due to perl pseudo-forks hanging forever if anything is ever waiting on read() in windows, we don't fork to spawn binaries.
679 Instead we use C<start> to open a new cmd.exe window, which will show up in your task tray.
680 Don't close this or your test will fail for obvious reasons.
681  
682 This also means that if you have to send ^C (SIGTERM) to your script or exit() prematurely, said window may be left dangling,
683 as these behave a lot more like POSIX::_exit() does on unix systems.
684  
685 =head1 UTF-8 considerations
686  
687 The JSON responses from the selenium server are decoded as UTF-8, as per the Selenium standard.
688 As a convenience, we automatically apply NFC to output via L<Unicode::Normalize>, which can be disabled by passing normalize=0 to the constructor.
689 If you are comparing output from selenium calls against UTF-8 glyphs, `use utf8`, `use feature qw{unicode_strings}` and normalization is strongly suggested.
690  
691 =head1 AUTHOR
692  
693 George S. Baugh <george@troglodyne.net>
694  
695 =head1 AUTHOR
696  
697 George S. Baugh <george@troglodyne.net>
698  
699 =head1 COPYRIGHT AND LICENSE
700  
701 This software is Copyright (c) 2023 by George S. Baugh.
702  
703 This is free software, licensed under:
704  
705 The MIT (X11) License
706  
707 =cut
↑ Summary lib/Selenium/Specification.pm »