Verify file downloaded - Keyword

So this might be useful to others. I needed a way to verify a file downloaded based upon it’s name and type. I found a solution online and modified it to be a keyword.

Here is my keyword code:

package customKeywords

import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.util.KeywordUtil
import org.testng.Assert

/*
 * Author: B_L
 * Last Modified: 01/04/2019
 * Last Modified By: B_L
 * Purpose: checks to see if a file was downloaded based upon name and file path this was written for checking downloading
 * 
 * 
 * based on: https://stackoverflow.com/questions/30726126/detecting-a-file-downloaded-in-selenium-java
 * 
 */

@Keyword
public boolean isFileDownloaded(String downloadPath, String fileName) {

	File dir = new File(downloadPath);
	File[] dirContents = dir.listFiles();
	String lastAttempt = '';
	if (dirContents.length > 0) {
		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();
				KeywordUtil.markPassed(fileName + ' exist in ' + downloadPath + ' and was deleted')
				return true;
			}
			lastAttempt = dirContents[i].getName().equals(fileName);
		}
		if (lastAttempt != fileName) {
			KeywordUtil.markFailed(fileName + ' does not exist in ' + downloadPath)
			return false;
		}
	}
	return false;
}

This is what it looks like in a test case when used:

CustomKeywords.'customKeywords.verifyFileDownloaded.isFileDownloaded'(userDownloads, 'exampleName.pdf')

In order to get the filepath of the logged in user I have this at the top of my test case:

String home = System.getProperty('user.home')
String userDownloads = new File(home + '/Downloads/')
6 Likes

Nice work :slight_smile:

There’s also a simpler alternative :slight_smile:

import java.nio.file.Files
import java.nio.file.Paths

public boolean isFileDownloaded(String dir, String filename) {
	return Files.exists(Paths.get(dir, filename))
}

Note: I would keep such methods focused on a single action - I’d extract delete functionality to other keyword - you may run into a situation that you only want to verify if file is present and keep it.

6 Likes

Hi guys. I need to verify that I download a document. However I have a problem, the name is generated dynamically.

an example: AX_Documents_043019_0037.zip

The document’s name contain the date and seconds when I download the file. that means that the document name never will be the same.

Any Idea how to handle this Scenario?

Hope someone can help.

Regards

Sorry for the late reply, could you generate the dynamic portion? What i mean is that perhaps you can run java code to capture now timestamp or date and pass this into a variable for the document name then pass that into this method.

Thanks, this is work

When you generate the file, store its name in a temp variable, then pass that variable to the function as the file name