2023年7月3日发(作者:)
selenium校验⽂件下载成功
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 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 most of the cases we know which file is getting downloaded after clicking on download button / link. Now when we know the file name, wecan verify using java for the 'File Exists' in a downloaded folder location which we there are cases where file name is not unique. File name may be generated dynamically. In such cases we can also check for the fileexists with the file will see all the above cases and verify for the file which is being downloaded. We will see examples using and
package ;import ;import lter;import stems;import ;import ;import rdWatchEventKinds;import vent;import ey;import ervice;import ;import it;import difiedFileComparator;import rdFileFilter;import ;import ver;import xDriver;import xProfile;import ;import lass;import Class;import ;public class FileDownloadVerify {
private WebDriver driver;
private static String downloadPath = "D:seleniumdownloads"; private String URL="//file/C35/P10/";
@BeforeClass public void testSetup() throws Exception{ driver = new FirefoxDriver(firefoxProfile());
().window().maximize(); }
@Test public void example_VerifyDownloadWithFileName() { (URL); ement(xt("")).click(); True(isFileDownloaded(downloadPath, ""), "Failed to download Expected document"); }
@Test public void example_VerifyDownloadWithFileExtension() { (URL); ement(xt("")).click(); True(isFileDownloaded_Ext(downloadPath, ".xls"), "Failed to download document which has extension .xls"); } @Test public void example_VerifyExpectedFileName() { (URL); ement(xt("")).click(); File getLatestFile = getLatestFilefromDir(downloadPath); String fileName = e(); True((""), "Downloaded file name is not matching with expected file name"); }
@AfterClass public void tearDown() { (); }View Code
Here we are to the Firefox browser and we will pass this to the Webdriver. We can set different preferences based on the requirement. In thistutorial there are many other preferences which are used when .public static FirefoxProfile firefoxProfile() throws Exception {
FirefoxProfile firefoxProfile = new FirefoxProfile(); ference("List",2); ference("enStarting",false); ference("",downloadPath); ference("Disk","text/csv,application/x-msexcel,application/excel,application/x-excel,application/-excel,image/png,image/jpeg,text/html,text/plain,application/msword,application/xml");
return firefoxProfile; }View Code
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' ifthe document is available in the folder else 'false'. When we are sure of the file name, we can make use of this method to boolean isFileDownloaded(String downloadPath, String fileName) { boolean flag = false; File dir = new File(downloadPath); File[] dir_contents = les();
for (int i = 0; i < dir_; i++) { if (dir_contents[i].getName().equals(fileName)) return flag=true; } return flag; }View Code
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 thespecific 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 = les(); if (files == null || == 0) { flag = false; }
for (int i = 1; i < ; i++) { if(files[i].getName().contains(ext)) { flag=true; } } return flag; }View Code
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 whichreturns 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 = les(); if (files == null || == 0) { return null; }
File lastModifiedFile = files[0]; for (int i = 1; i < ; i++) { if (dified() < files[i].lastModified()) { lastModifiedFile = files[i]; } } return lastModifiedFile; }
View Code
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 wemay encounter issues as the file is not can also make use of 'Java Watch Service API' which monitors the changes in the directory. Note: This is compatible with Java 7 is the example program using Watch Service API. And here we will user only for 'ENTRY_CREATE' 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 = (downloadDir); WatchService watchService = ault().newWatchService(); er(watchService, _CREATE); long startTime = tTimeMillis(); do
{ WatchKey watchKey; watchKey = (timeOut,S); long currentTime = (tTimeMillis()-startTime)/1000; if(currentTime>timeOut) { n("Download operation timed out.. Expected file was not downloaded"); return downloadedFileName; }
for (WatchEvent> event : ents()) { > kind = (); if ((_CREATE))
{ String fileName = t().toString(); n("New File Created:" + fileName); if(th(fileExtension)) { downloadedFileName = fileName; n("Downloaded file found with extension " + fileExtension + ". File name is " +
fileName); (500); found = true; break; } } } if(found) { return downloadedFileName; } else { currentTime = (tTimeMillis()-startTime)/1000; if(currentTime>timeOut) { n("Failed to download expected file"); return downloadedFileName; } valid = (); } } while (valid); }
catch (InterruptedException e)
{ n("Interrupted error - " + sage()); tackTrace(); } catch (NullPointerException e)
{ n("Download operation timed out.. Expected file was not downloaded"); } catch (Exception e) { n("Error occured - " + sage()); tackTrace(); } return downloadedFileName; }View Code
发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688382810a129713.html
评论列表(0条)