Saturday, June 4, 2016

How to Download files using Selenium (2)

In my previous post about Selenium I explained how can we modify browsers before tests in order to have desired configuration. Today I like to discuss different topic which lacks quality guides - downloading files. Mixing Selenium with AutoIT isn't good, trust me.

I'm using FluentLenium syntax to navigate on the page (that would be Micheal Bolton's homepage to be more precise), but it's very intuitive and you shouldn't have any problems rewriting it on Selenium. I borrowed some code from Mastering Selenium WebDriver book, which I once again recommend. 

Testers who don't understand HTTP protocol usually get stuck with 'Are you sure you want to download this file?' popup.  The thing is, it's just internal browser implementation and we don't have to test it. We are going to bypass it completely. I'll give you 4 examples how can you test it. Make risk assessment and decide which one would be appropriate for your site. First one is the fastest one, and the last one is the slowest.

1. Checking that file is available on given address

We will not only bypass browser's download handling mechanism, but we won't use Selenium too. It's just HttpClient request and response code verification (we expect 200 -> SC_OK). We don't verify that user sees the link and is able to click on it.

And here is HttpClient implementation. Quite a few lines, I know.

2. Checking that file is available for real user

Now we would simulate the real user. We are going to get url from existing site selector and add user cookies to http request. Note that only getUrlFromSite() method uses FluentLenium. That's the class you need to modify to make it work in clean Selenium.

There is very nice method which I found in Mastering Selenium WebDriver book. It copies all the cookies and adds to request. It's Request.class extension required to make our test pass.

3. Checking that file isn't empty

Now we would download file and check that it isn't empty. Have in mind that this approach is applicable for small files.

And that's the downloadFile() method from Request.class.

4. Checking that we download correct file

And finally the most reliable approach. We would not only download file, but also check it's md5 checksum.

If you prefer to read code only, here is everything: