浏览代码

add upload_file() method to the driver, similar to what java client library has

Ivan Kurmanov 13 年之前
父节点
当前提交
9d4ea565f2
共有 3 个文件被更改,包括 39 次插入0 次删除
  1. 2 0
      Makefile.PL
  2. 4 0
      lib/Selenium/Remote/Commands.pm
  3. 33 0
      lib/Selenium/Remote/Driver.pm

+ 2 - 0
Makefile.PL

@@ -14,6 +14,8 @@ requires 'Carp';
 test_requires 'Carp' => '1.25';
 requires 'JSON';
 requires 'Net::Ping';
+requires 'MIME::Base64';
+requires 'IO::Compress::Zip';
 
 resources 'bugtracker' => 'https://github.com/aivaturi/Selenium-Remote-Driver/issues';
 resources 'repository' => {

+ 4 - 0
lib/Selenium/Remote/Commands.pm

@@ -281,6 +281,10 @@ sub new {
                'method' => 'POST',
                'url'    => 'session/:sessionId/buttonup'
         },
+        'uploadFile' => {
+               'method' => 'POST',
+               'url'    => 'session/:sessionId/file'
+        },
         #'setVisible' => {
         #               'method' => 'POST',
         #               'url' => "session/:sessionId/visible"

+ 33 - 0
lib/Selenium/Remote/Driver.pm

@@ -6,6 +6,9 @@ use warnings;
 use Carp;
 our @CARP_NOT;
 
+use MIME::Base64;
+use IO::Compress::Zip qw(zip $ZipError) ;
+
 use Selenium::Remote::RemoteConnection;
 use Selenium::Remote::Commands;
 use Selenium::Remote::WebElement;
@@ -1829,6 +1832,36 @@ sub button_up {
   return $self->_execute_command($res);
 }
 
+=head2 upload_file
+
+ Description: 
+    Upload a file from the local machine to the selenium server
+    machine. That file then can be used for testing file upload on web
+    forms. Returns the remote-server's path to the file.
+
+ Usage:
+    my $remote_fname = $driver->upload_file( $fname );
+    my $element = $driver->find_element( '//input[@id="file"]' );
+    $element->send_keys( $remote_fname );
+
+=cut
+
+# this method duplicates upload() method in the
+# org.openqa.selenium.remote.RemoteWebElement java class.
+
+sub upload_file {
+    my ($self, $filename) = @_;
+    if (not -r $filename) { die "upload_file: no such file: $filename"; }
+    my $string = "";                         # buffer
+    zip $filename => \$string
+        or die "zip failed: $ZipError\n";    # compress the file into string
+    my $res = { 'command' => 'uploadFile' }; # /session/:SessionId/file
+    my $params = {
+        file => encode_base64($string)       # base64-encoded string
+    };
+    return $self->_execute_command($res, $params);
+}
+
 1;
 
 __END__