Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting a file downloaded in selenium java

I wrote an automation test in selenium java that detects if the page is redirecting (the automation detects if a new page is opened, the page redirects to other page, a new tab is opened and if an alert window is opened)

Now to the problem. one of the redirects i can't find any way to detect is an automatic downloaded file (you enter a website and the website automatically downloads a file without any trigger from the user)

p.s.

I know the download process may differ in each browser, I need it to work mainly on chrome

Thanks

like image 646
Avidan Avatar asked Jun 09 '15 07:06

Avidan


People also ask

How does Selenium verify downloaded files?

Though Selenium provides basic commands to download any file from a website, BrowserStack provides custom executors to assert if the file is downloaded successfully, view file properties, and transfer files to local machine.

How do I find a file in Selenium?

Uploading files in WebDriver is done by simply using the sendKeys() method on the file-select input field to enter the path to the file to be uploaded. WebDriver cannot automate downloading of files on its own.


2 Answers

I had the same question and here is what I found somewhere on the Internet (maybe on stackoverflow, I cannot remember). I just added a line to delete the file so that by calling this method at the beginning of my test, I'm making sure the file does not exist anymore when trying to download it again.

  public boolean isFileDownloaded(String downloadPath, String fileName) {
  File dir = new File(downloadPath);
  File[] dirContents = dir.listFiles();

  for (int i = 0; i < dirContents.length; i++) {
      if (dirContents[i].getName().equals(fileName)) {
          // File has been found, it can now be deleted:
          dirContents[i].delete();
          return true;
      }
          }
      return false;
  }

You just have to call with this single line: isFileDownloaded("C:\Path\To\Your\Folder", "yourPdfFile.abc");

Hope this helps!

like image 158
Fab738 Avatar answered Sep 28 '22 06:09

Fab738


My solution in the end was to count the files in the download directory before and after i open the page.

I'll be glad to know if someone knows a way to find the trigger for the download

like image 23
Avidan Avatar answered Sep 28 '22 05:09

Avidan