Verify file downloaded - Keyword


#1

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/')

Verify downloaded file is a word document
#2

Nice work :slight_smile:


#3

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.