Tuesday Tip Day – Handling File Downloads

Tuesday Tip Day – Handling File Downloads

Pixel Ratio Confusion

It’s a common misconception that when writing automated tests using Selenium, that anything that happens outside of a browser window or the scope of the application, can’t be tested and there’s no way to deal with it. This can sometimes be the case but more often than not, there will be a way to handle it, either through simple logic or third party libraries.

One such occasion that often gets left behind when automated testing is the verification of files being downloaded correctly and to the correct location. Your application might download an executable or a pdf file as an example when opening a link, and as part of your test, you want to ensure that it has successfully downloaded.

And to do this, it’s actually a very small amount of code write. Assuming we are already at a point that we have downloaded 

public bool VerifyTermsAndConditionsPdfFileDownloads()
{
    string expectedFilePath = @“C:\Downloads\TermsAndConditions.pdf”;
bool fileExists = false;
    
    var options = new ChromeOptions();
    options.AddUserProfilePreference(“download.default_directory”, @“C:\Downloads”);
    var driver = new ChromeDriver(options);

    driver.Navigate().GoToUrl(“https://www.yourapplicationtotest.com/files/TermsAndConditions.pdf”);
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
    wait.Until<bool>(x => 
         fileExists = File.Exists(expectedFilePath));

return fileExists;
}

That small piece of code will test that your url will download the file correctly and to the correct location. It’s as simple as that.

You could easily improve this method to make it more robust by adding a try catch look to handle files not being found or timing out. Also, if you wanted, you could use the FileInfo library to get other information such as file size if you wanted to ensure that your file matches the expected download size.

While the above example would work with Chrome, you would need to update the code to use different browser options for other browsers

FirefoxProfile profile = new FirefoxProfile();
profile.SetPreference(“browser.download.folderList”, 2);
profile.SetPreference(“browser.download.dir”, @“C:/Downloads”);
profile.SetPreference(“browser.helperApps.neverAsk.saveToDisk”, “application/pdf”);
var driver = new FirefoxDriver(profile);

The above is similar to the way we set the download directory for Chrome, however we also need to tell Firefox not to bother us with requests on where to save and whether to just open or save. At the moment, I’ve only set it for PDF files, but you can add any extension or file type.

For IE and Edge, unfortunately it doesn’t use Profiles so as a result, there is no easy way to perform the above behaviour in IE and Edge. 

 

2 Responses

Comments are closed.