转自: http://www.seleniumeasy.com/selenium-tutorials/verify-file-after-downloading-using-webdriver-java

It is very important to verify if the file is downloaded successful or not. Most of the cases we just concentrate on clicking the downloaded button. But at the same time it is also very important to confirm that file is downloaded successfully without any errors or if some other file is getting downloaded.

In most of the cases we know which file is getting downloaded after clicking on download button / link. Now when we know the file name, we can verify using java for the 'File Exists' in a downloaded folder location which we specify.

Even there are cases where file name is not unique. File name may be generated dynamically. In such cases we can also check for the file exists with the file extension.

We will see all the above cases and verify for the file which is being downloaded. We will see examples using Java File IO and WatchService API

package com.pack;

import java.io.File;
import java.io.FileFilter;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Arrays;
import java.util.concurrent.TimeUnit; import org.apache.commons.io.comparator.LastModifiedFileComparator;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; public class FileDownloadVerify { private WebDriver driver; private static String downloadPath = "D:\\seleniumdownloads";
private String URL="http://spreadsheetpage.com/index.php/file/C35/P10/"; @BeforeClass
public void testSetup() throws Exception{
driver = new FirefoxDriver(firefoxProfile());
driver.manage().window().maximize();
} @Test
public void example_VerifyDownloadWithFileName() {
driver.get(URL);
driver.findElement(By.linkText("mailmerge.xls")).click();
Assert.assertTrue(isFileDownloaded(downloadPath, "mailmerge.xls"), "Failed to download Expected document");
} @Test
public void example_VerifyDownloadWithFileExtension() {
driver.get(URL);
driver.findElement(By.linkText("mailmerge.xls")).click();
Assert.assertTrue(isFileDownloaded_Ext(downloadPath, ".xls"), "Failed to download document which has extension .xls");
} @Test
public void example_VerifyExpectedFileName() {
driver.get(URL);
driver.findElement(By.linkText("mailmerge.xls")).click();
File getLatestFile = getLatestFilefromDir(downloadPath);
String fileName = getLatestFile.getName();
Assert.assertTrue(fileName.equals("mailmerge.xls"), "Downloaded file name is not matching with expected file name");
} @AfterClass
public void tearDown() {
driver.quit();
}

Here we are defining the preferences to the Firefox browser and we will pass this to the Webdriver. We can set different preferences based on the requirement. In this tutorial there are many other preferences which are used when downloading a file using Firefox Preferences.

public static FirefoxProfile firefoxProfile() throws Exception {

        FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false);
firefoxProfile.setPreference("browser.download.dir",downloadPath);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk",
"text/csv,application/x-msexcel,application/excel,application/x-excel,application/vnd.ms-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml"); return firefoxProfile;
}

Below method takes the download directory and the file name, which will check for the file name mention in the directory and will return 'True' if the document is available in the folder else 'false'. When we are sure of the file name, we can make use of this method to verify.

public boolean isFileDownloaded(String downloadPath, String fileName) {
boolean flag = false;
File dir = new File(downloadPath);
File[] dir_contents = dir.listFiles(); for (int i = 0; i < dir_contents.length; i++) {
if (dir_contents[i].getName().equals(fileName))
return flag=true;
} return flag;
}

The below method takes two parameters, first takes the folder path and the file extension / mime type. it will return true if the file with the specific extension is available in the specified folder.

/* Check the file from a specific directory with extension */
private boolean isFileDownloaded_Ext(String dirPath, String ext){
boolean flag=false;
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
flag = false;
} for (int i = 1; i < files.length; i++) {
if(files[i].getName().contains(ext)) {
flag=true;
}
}
return flag;
}

The below method is used to get the document name based on the last action performed in the specified folder. This is done by using java LastModifiedwhich returns a long value representing the time the file was last modified.

/* Get the latest file from a specific directory*/
private File getLatestFilefromDir(String dirPath){
File dir = new File(dirPath);
File[] files = dir.listFiles();
if (files == null || files.length == 0) {
return null;
} File lastModifiedFile = files[0];
for (int i = 1; i < files.length; i++) {
if (lastModifiedFile.lastModified() < files[i].lastModified()) {
lastModifiedFile = files[i];
}
}
return lastModifiedFile;
}

When ever we click on download, based on the file size and network we need to wait for specific to complete download operation. If not we may encounter issues as the file is not downloaded.

We can also make use of 'Java Watch Service API' which monitors the changes in the directory. Note: This is compatible with Java 7 version. Below is the example program using Watch Service API. And here we will user only for 'ENTRY_CREATE' event.

public static String getDownloadedDocumentName(String downloadDir, String fileExtension)
{
String downloadedFileName = null;
boolean valid = true;
boolean found = false; //default timeout in seconds
long timeOut = 20;
try
{
Path downloadFolderPath = Paths.get(downloadDir);
WatchService watchService = FileSystems.getDefault().newWatchService();
downloadFolderPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
long startTime = System.currentTimeMillis();
do
{
WatchKey watchKey;
watchKey = watchService.poll(timeOut,TimeUnit.SECONDS);
long currentTime = (System.currentTimeMillis()-startTime)/1000;
if(currentTime>timeOut)
{
System.out.println("Download operation timed out.. Expected file was not downloaded");
return downloadedFileName;
} for (WatchEvent> event : watchKey.pollEvents())
{
WatchEvent.Kind> kind = event.kind();
if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE))
{
String fileName = event.context().toString();
System.out.println("New File Created:" + fileName);
if(fileName.endsWith(fileExtension))
{
downloadedFileName = fileName;
System.out.println("Downloaded file found with extension " + fileExtension + ". File name is " + fileName);
Thread.sleep(500);
found = true;
break;
}
}
}
if(found)
{
return downloadedFileName;
}
else
{
currentTime = (System.currentTimeMillis()-startTime)/1000;
if(currentTime>timeOut)
{
System.out.println("Failed to download expected file");
return downloadedFileName;
}
valid = watchKey.reset();
}
} while (valid);
} catch (InterruptedException e)
{
System.out.println("Interrupted error - " + e.getMessage());
e.printStackTrace();
}
catch (NullPointerException e)
{
System.out.println("Download operation timed out.. Expected file was not downloaded");
}
catch (Exception e)
{
System.out.println("Error occured - " + e.getMessage());
e.printStackTrace();
}
return downloadedFileName;
}

selenium 校验文件下载成功的更多相关文章

  1. Python+selenium测试环境成功搭建,简单控制浏览器(firefox)接下来,继续学习其他浏览器上的测试环境搭建;学习Python语言,利用Python语言来写测试用例。加油!!!

    Python+selenium测试环境成功搭建,简单控制浏览器(firefox)接下来,继续学习其他浏览器上的测试环境搭建:学习Python语言,利用Python语言来写测试用例.加油!!!

  2. 【自动化测试】使用Java+selenium填写验证码成功登录

    这是我第一次发博客,若有问题,请多多指教! 本次是为了帮忙解决,如果在平时自动化遇到有验证码填写的情况,我们如何成功登录情况. 思路: 首先我们先将验证码复制并保存成一个图片,然后使用tesserac ...

  3. TestNG 判断文件下载成功

    用WatchService写一个方法放在onTestStart()方法里监听文件夹的变化. 但是判断下载成功还需要写一个方法, 用来判断什么时候文件从.xlsx.rcdownload改成.xlsx才行 ...

  4. selenium+Python(文件下载)

    webdriver允许我们设置默认的文件下载路径,也就是说,文件会自动下载并保存到设置的目录中 下面以Firefox浏览器为例: from selenium import webdriver from ...

  5. selenium 定位元素成功, 但是输入失败 (textarea)

    问题描述 UI页面功能测试中, 定位元素并输入(通过sendKey()方法输入), 显示输入失败. 根本原因 为了修复一个bug, 这个元素从input改成了textarea, 而textarea是有 ...

  6. DEVOPS技术实践_23:判断文件下载成功作为执行条件

    在实际生产中,我们经常会需要通过判断一个结果作为一个条件去执行另一个内容,比如判断一个文件是否存在,判官一个命令是否执行成功等等 现在我们选择其中一个场景进行实验,当某个目录下存在,则执行操作 1. ...

  7. selenium截图对比校验方法

    /**对比图片进行校验是否成功**/package com.allin.pc;import java.awt.image.BufferedImage;import java.awt.image.Dat ...

  8. python + selenium 自动化测试框架

    分享一个网站自动化测试框架 结构如下: test_project|--logs|---pages |---register_page.py|      |---base_page.py|---test ...

  9. Selenium+Python+jenkins搭建web自动化测测试框架

    python-3.6.2 chrome 59.0.3071.115 chromedriver 2.9 安装python https://www.python.org/downloads/  (Wind ...

随机推荐

  1. .NET Framework 源码查看与调试

    1. 直接下载.NET Framework源代码(下载地址),然后用Visual Studio 13 打开查看.2. 在线查看,网址:http://referencesource.microsoft. ...

  2. ListView中的TextView实现跑马灯效果

    1.TextView首先添加android:ellipsize="marquee"   android:marqueeRepeatLimit="marquee_forev ...

  3. php获取全选checkbox多个值

    <form name="myform"  action="index2.php" method="post">          ...

  4. java学习--高效的除模取余运算(n-1)&hash

    没有测试过使用取余运算符和位运算符都做同一件事时的时间效率! 取余运算符% 如3除以2取余数 a = a%; 结果为1 上面是传统的方式进行求余运算. 需要先将10进制转成2进制到内存中进行计算,然后 ...

  5. mongo学习使用记录2 spring data

    spring data mongo 打印mongo NoSql语句 log4j.properties log4j.rootLogger=INFO, stdout log4j.logger.org.sp ...

  6. Java @Repeatable

    查看@PropertySource注解时候,发现了@Repeatable,从来没见过的注解,学习了下: 首先介绍下@Repeatable注解: JDK1.8出现的,作用是解决一个类上不能标注重复的注解 ...

  7. 未能找到路径E:\项目文件\W\vbc.exe”的一部分

    网上找的说要引用Microsoft.CodeDom.Providers.DotNetCompilerPlatform, 我已经引用了,是差roslyn文件夹,从别的项目考一份过来就好了

  8. 如何一键式搭建微信小程序

    有了微信小程序,对你到底意味着什么? 对于用户来说,再也不用担心手机的内存不够用了!一个小程序只有1M,随便卸载一个App,就能安装很多小程序! 对于老板来说,你不再需要花费数十万来去请外包公司帮你去 ...

  9. c# 导出text 文本文件

    /// <summary> /// 机构代码信息 /// </summary> public static void ExportT_XQJBQK_SLGAJGDM(DataT ...

  10. Java 支付宝支付,退款,单笔转账到支付宝账户(单笔转账到支付宝账户)

    上次分享了支付宝订单退款的代码,今天分享一下支付宝转账的操作.  现在是有一个余额提现的功能,本来是打算做提现到银行卡的,但是客户嫌麻烦不想注册银联的开放平台账户,就说先提现到支付宝就行,二期再做银行 ...