Browse Source

Implement phantomjs binary startup

Daniel Gempesaw 10 years ago
parent
commit
fb74a579c0
1 changed files with 47 additions and 0 deletions
  1. 47 0
      lib/Selenium/PhantomJS.pm

+ 47 - 0
lib/Selenium/PhantomJS.pm

@@ -1,7 +1,9 @@
 package Selenium::PhantomJS;
 package Selenium::PhantomJS;
 
 
 # ABSTRACT: A convenience package for creating a PhantomJS instance
 # ABSTRACT: A convenience package for creating a PhantomJS instance
+use Selenium::Binary qw/start_binary_on_port/;
 use Moo;
 use Moo;
+use namespace::clean;
 extends 'Selenium::Remote::Driver';
 extends 'Selenium::Remote::Driver';
 
 
 =head1 SYNOPSIS
 =head1 SYNOPSIS
@@ -10,9 +12,54 @@ extends 'Selenium::Remote::Driver';
 
 
 =cut
 =cut
 
 
+use constant PHANTOMJS_PORT => 8910;
+
 has '+browser_name' => (
 has '+browser_name' => (
     is => 'ro',
     is => 'ro',
     default => sub { 'phantomjs' }
     default => sub { 'phantomjs' }
 );
 );
 
 
+# By shadowing the parent's port function, we can set the port in
+# _build_binary_mode's builder
+has '+port' => (
+    is => 'lazy'
+);
+
+has 'binary_mode' => (
+    is => 'ro',
+    init_arg => undef,
+    builder => 1
+);
+
+sub _build_binary_mode {
+    my ($self) = @_;
+
+    if (! $self->has_remote_server_addr && ! $self->has_port) {
+        try {
+            my $port = start_binary_on_port('phantomjs', PHANTOMJS_PORT);
+            $self->port($port);
+            return 1;
+        }
+        catch {
+            warn $_;
+            return 0;
+        }
+    }
+    else {
+        return 0;
+    }
+}
+
+sub DEMOLISH {
+    my ($self) = @_;
+
+    if ($self->binary_mode) {
+
+        my $port = $self->port;
+        my $ua = LWP::UserAgent->new;
+
+        $ua->get('127.0.0.1:' . $port . '/wd/hub/shutdown');
+    }
+}
+
 1;
 1;