selenium 校验文件下载成功

转自: 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;
    }

原文地址:https://www.cnblogs.com/cheese320/p/9089975.html

时间: 2024-11-02 11:11:19

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

selenium+firefox调试成功

背景介绍:win7 64bit - selenium 3.8.1 - firefox 56 32bit - geckodriver.exe 0.19.0 利用上述软件经一下午调试终于成功利用Firefox浏览器打开搜索selenium.(太菜了) selenium 直接利用 pip install selenium 安装的,不再多说. 下载geckodriver.exe(https://github.com/mozilla/geckodriver/releases)注意和Firefox对应好版本

TestNG 判断文件下载成功

用WatchService写一个方法放在onTestStart()方法里监听文件夹的变化. 但是判断下载成功还需要写一个方法, 用来判断什么时候文件从.xlsx.rcdownload改成.xlsx才行 (TODO). package com.tcemo.ui.bean; import static com.tcemo.ui.bean.ScreenShotOnFailure.SCREEN_SHOT_NAME; import static com.tcemo.ui.bean.ScreenShotOn

selenium截图对比校验方法

/**对比图片进行校验是否成功**/package com.allin.pc; import java.awt.image.BufferedImage;import java.awt.image.DataBuffer;import java.io.File;import java.io.IOException;import java.util.concurrent.TimeUnit; import javax.imageio.ImageIO; import org.apache.commons.

Mac下搭建Python2.7+selenium+pycharm

1.下载pip https://pypi.org/project/pip/ 下载上面红线标出的,然后打开终端,cd到上面文件下载成功后setup.py的所在目录,执行sudo python setup.py install 2.安装selenium 联网执行 sudo pip install –U selenium(默认是最新的3) 如果想换成selenium2的,并且已安装selenium3的,可以在终端cd到selenium3的安装目录下,输入:sudo pip uninstall sele

Service实现文件下载

首先在Activity中声明Intent对象,启动Service: //生成Intent对象 Intent intent = new Intent(); //将文件名对象存入到intent对象当中 intent.putExtra("name", filename); intent.setClass(this, DownloadService.class); //启动Service startService(intent); DownloadService定义如下: public cla

Python + Selenium 环境搭建

Python + Selenium 环境搭建 注:本文是根据网上资料收集验证整理而得,仅供学习 准备如下: 1.下载 python http://python.org/getit/ 2.下载 setuptools http://pypi.python.org/pypi/setuptools 3.下载 pip https://pypi.python.org/pypi/pip setuptools 是 python 的基础包工具,可以帮助我们轻松的下载,构建,安装,升级,卸载 python的软件包.

selenium 代理 Cookies 截图 等待 调用JS

改变用户代理 读取Cookies 调用Java Script Webdriver截图 页面等待 1. 改变用户代理 [java] view plain copy import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver;

flex 文件下载 +Tomcat web应用服务器

注意点: 1.FileReference.download() 方法提示用户提供文件的保存位置并开始从远程 URL 进行下载.直接加载请求路径下载,不需要后台的支持. 2.针对文件中文名的问题,需要双方设置编码: 首先flex端: var download_request:URLRequest=new URLRequest(encodeURI(StringUtil.trim(url))); encodeURI(uri:String="undefined"):String 将字符串编码为

安装selenium操作步骤(python中使用selenium)

前置条件:系统中已经安装好python个pip 第一步:在cmd中进入到pip安装目录,如:D:\python34\scripts 第二步:执行安装命令:pip install selenium 安装完成后进行浏览器驱动配置 第三步:在网上下载浏览器驱动(谷歌.IE.火狐等) 第四步:将下载好的浏览器驱动放在python安装的目录的根目录 第五步:将浏览器驱动的路径配置到环境变量中,如:D:\python34\Chome.exe 完成以上步骤可以输入以下代码进行测试: from selenium