3

I am using selenium and testng to do Web UI automation test. I download files with Firefox using the same way as Access to file download dialog in Firefox. The file will be downloaded with default name without Open/Save/Cancel dialog successfully.

I repeat the test for different test data. The problems are

  1. When there is a file with 'abc.pdf' in target 'browser.download.dir', if I download a file with same name, the new file will be saved to 'abc (1).pdf'; that's not what I want. In the following test I have problem to decide to open which pdf and check its content.

(Now my solution is, write a retry method: check if the file is downloaded, if yes, move it to another folder; if no, check again. Is there a better way?)

  1. Sometimes when I click link or button to download, the file name is generated dynamically by web system. The file could be .pdf, .eml, .txt, etc. I can know the file suffix from UI. But I can't know the name in advance. Same here, I need open the file and do assertion in following test.

How to overcome? What if I need run the test in multiple threads? Much appreciated!

Community
  • 1
  • 1
rong
  • 121
  • 7

1 Answers1

1

An easy way is to wait for a new file to be created with a file watcher: https://docs.oracle.com/javase/tutorial/essential/io/notification.html

This is an example to wait for a .pdf file to be created:

// wait for the PDF to be downloaded
File file = WaitForNewFile(download_folder, ".pdf", 100);
/**
 * Waits for a new file to be downloaded with a file watcher
 */
public static File WaitForNewFile(Path folder, String extension, int timeout_sec) throws InterruptedException, IOException {
    long end_time = System.currentTimeMillis() + timeout_sec * 1000;

    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
        folder.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);

        for (WatchKey key; null != (key = watcher.poll(end_time - System.currentTimeMillis(), TimeUnit.MILLISECONDS)); key.reset()) {
            for (WatchEvent<?> event : key.pollEvents()) {
                File file = folder.resolve(((WatchEvent<Path>)event).context()).toFile();
                if (file.toString().toLowerCase().endsWith(extension.toLowerCase()))
                    return file;
            }
        }
    }
    return null;
}
Florent B.
  • 41,537
  • 7
  • 86
  • 101