15

Downloading Secure Files

The Problem

In a previous tip we covered how to write tests to download files in a browser agnostic way by leveraging Selenium Webdriver and an HTTP library in tandem.

This approach is great, but there are often times where the file you want to download is behind authentication, presenting a hurdle to overcome.

A Solution

In order to access secure files with an HTTP library, we want to pull the authenticated session information out of Selenium's cookie store and pass it into the HTTP library when we perform the download action.

Let's dig in with an example.

An Example

We start by requiring our libraries (Selenium to drive the browser, RSpec for our assertions, and RestClient for our download action) and wire up our setup, teardown, and run actions.

require 'selenium-webdriver'
require 'rspec-expectations'
require 'rest-client'

def setup
  @driver = Selenium::WebDriver.for :firefox
end

def teardown
  @driver.quit
end

def run
  setup
  yield
  teardown
end

Next we access a page of download links that is behind Basic HTTP Authentication, grab the first download link, and pull the authentication session cookie from the cookie store. Once we have that we fire up RestClient and perform a HEAD request against the download link with the cookie information and then check the headers to make sure it has the correct type and is not empty.

run do
  @driver.get 'http://admin:admin@the-internet.herokuapp.com/download_secure'
  link = @driver.find_element(css: 'a').attribute('href')
  cookie = @driver.manage.cookie_named 'rack.session'
  response = RestClient.head link, cookie: "#{cookie[:name]}=#{cookie[:value]};"
  response.headers[:content_type].should == 'application/pdf'
  response.headers[:content_length].to_i.should > 0
end

In order for things to work correctly with RestClient we have to stringify the cookie values (due to an open issue in the library). But your cookie configuration will likely vary depending on your HTTP library of choice.

And note that we are using a HEAD request instead of a GET request. Since we only care about the header information this will perform a partial fetch of data, avoiding a full download of the file.

Expected Behavior

  • Load the page
  • Get the first download link
  • Pull the authenticated cookie information
  • Use it to perform a HEAD request against the download link
  • Check the headers to make sure the file is the correct type and not empty

Outro

While this example demonstrates accessing files behind Basic HTTP Authentication it should also work with form-based authentication.

And hopefully this helps save you some time, enabling you to build a more lean and fast set of download tests.

Until next time, Happy Testing!

Found this helpful?

Submit your e-mail in the form below to recieve tips like this!

One email every Tuesday. No Spam. Ever. Unsubscribe anytime.


Back to the archives