Automated Page Load Time Tracker

     I got an opportunity to work with a POC to capture web page load time tracking for an application. I have to map all the tracked time against the flow in an excel report. That excel report should have a benchmark time to compare the actual time. Finally, set the status based on the actual time and benchmark time. I have successfully completed the POC and integrated it into an automation framework. We can use this method for any project and any platform. In this article, I would like to share the actual implementation of the automated page load tracker.

     I have used stopwatch from apache commons, StopWatch provides a convenient API for timings. Then used explicit wait from Selenium and the expected condition is presenceOfElementLocated to check the expected object on the screen. Finally, used apache poi to generate the excel report and map the actual time, benchmark time, and status for different flows or pages.

     I have created a common method called collectLoadTime, it will collect the load time and map the details to the excel report. The parameters of collectLoadTime include WebDriver, expected object, expected time, page name/flow and report name. WebDriver object helps to do the explicit wait on the expected object. expected time is the benchmark time for each flow that captures in the excel report, report name is used in the excel file name to understand the report for the required module or feature. Following is the actual code implementation for collectLoadTime:

StopWatch pageLoad = new StopWatch();
pageLoad.start();// this line of code need to be added at constructor of the class. Don't add within collectLoadTime method.
public void collectLoadTime(WebDriver driver, String expectedObject, long expectedTime, String pageNameOrFlow, String reportName) throws Exception {
		StringBuilder message = new StringBuilder();
		try {
			WebDriverWait wait = new WebDriverWait(driver, expectedTime);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(expectedObject)));

			pageLoad.stop();
			long pageLoadTime_ms = pageLoad.getTime();
			long pageLoadTime_Seconds = pageLoadTime_ms / 1000;
			if (pageLoadTime_Seconds < 1) {
				System.out.println("Total Page Load Time for " + pageNameOrFlow + " is less than 1 second");

				trackDetailsToReport(pageNameOrFlow, pageLoadTime_Seconds, expectedTime, reportName);
			} else {
				System.out.println(
						"Total Page Load Time for " + pageNameOrFlow + " : " + pageLoadTime_Seconds + " seconds");

				trackDetailsToReport(pageNameOrFlow, pageLoadTime_Seconds, expectedTime, reportName);
			}
		} catch (Exception e) {
			throw new Exception(pageNameOrFlow + " is not loaded within " + expectedTime + " seconds");
		}
	}

     When we call the collectLoadTime method, it will start the stopwatch and immediately look for the expected object; once the object is loaded it will stop the stopwatch and calculate the time in seconds. The collected actual time, benchmark time, page name/flow and report name values are passed to the trackDetailsToReport method. Following is the detailed implementation of trackDetailsToReport method:

private void trackDetailsToReport(String pageNameOrFlow, long pageLoadTime_Seconds, long benchmarTime_Seconds,
			String reportName) throws IOException {

		// Creating file object of existing excel file
		if (!new File(System.getProperty("user.dir") + "\\Reports").exists()) {
			(new File(System.getProperty("user.dir") + "\\Reports")).mkdir();
		}
		if (!new File(System.getProperty("user.dir") + "\\Reports\\Performance").exists()) {
			(new File(System.getProperty("user.dir") + "\\Reports\\Performance")).mkdir();
		}
		if (!new File(System.getProperty("user.dir") + "\\Reports\\Performance\\Summary").exists()) {
			(new File(System.getProperty("user.dir") + "\\Reports\\Performance\\Summary")).mkdir();
		}
		DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy_MM_dd");
		LocalDateTime dateNow = LocalDateTime.now();
		String dateValue = dateFormat.format(dateNow);
		String filePath = System.getProperty("user.dir") + "\\Reports\\Performance\\Summary\\Performance_Test_Report_"
				+ reportName + "_" + dateValue + ".xlsx";

		File excelFile = new File(filePath);
		OutputStream fileOut = null;
		Sheet sheet;
		File fileName;
		Workbook wb = new XSSFWorkbook();
		if (!excelFile.exists()) {
			fileName = new File(filePath);
			fileOut = new FileOutputStream(fileName);
			sheet = wb.createSheet("Sheet1");

			// Create headers and set style
			Row header = sheet.createRow(0);
			header.createCell(0).setCellValue("Page or Flow");
			header.createCell(1).setCellValue("Actual Load Time (in Seconds)");
			header.createCell(2).setCellValue("Benchmark Time (in Seconds)");
			header.createCell(3).setCellValue("Status");
			CellStyle style = wb.createCellStyle();
			Font font = wb.createFont();
			font.setFontHeightInPoints((short) 12);
			font.setBold(true);
			style.setFont(font);
			style.setWrapText(true);
			sheet.setColumnWidth(0, 70 * 256);
			sheet.setColumnWidth(1, 15 * 256);
			sheet.setColumnWidth(2, 15 * 256);
			sheet.setColumnWidth(3, 10 * 256);
			for (int j = 0; j <= 3; j++) {
				header.getCell(j).setCellStyle(style);
				CellStyle cellHeaderStyle = header.getCell(j).getCellStyle();
				cellHeaderStyle.setVerticalAlignment(VerticalAlignment.CENTER);
				cellHeaderStyle.setAlignment(HorizontalAlignment.CENTER);
				header.getCell(j).setCellStyle(cellHeaderStyle);
			}
			wb.write(fileOut);
			System.out.println("Report has been created successfully.");
		}
		wb.close();

		// New records to update in the report
		Object[][] newdataLists = {
				{ pageNameOrFlow, String.valueOf(pageLoadTime_Seconds), String.valueOf(benchmarTime_Seconds) } };
		try {
			// Creating input stream
			FileInputStream inputStream = new FileInputStream(filePath);

			// Creating workbook from input stream
			Workbook workbook = WorkbookFactory.create(inputStream);

			// Reading first sheet of excel file
			sheet = workbook.getSheetAt(0);

			// Getting the count of existing records
			int rowCount = sheet.getLastRowNum();

			// Iterating new data to update
			for (Object[] data : newdataLists) {

				// Creating new row from the next row count
				Row row = sheet.createRow(++rowCount);

				int columnCount = 0;

				// Iterating data informations
				for (Object info : data) {

					// Creating new cell and setting the value
					Cell cell = row.createCell(columnCount++);
					if (info instanceof String) {
						cell.setCellValue((String) info);
					} else if (info instanceof Integer) {
						cell.setCellValue((Integer) info);
					}
				}
				// Setting the status after compare with benchmark value and also setting the
				// color style
				for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
					CellStyle style = workbook.createCellStyle();
					Font font = workbook.createFont();
					font.setBold(true);
					DataFormatter df = new DataFormatter();
					int actualTime = Integer.parseInt(df.formatCellValue(sheet.getRow(i).getCell(1)));
					int benchmarkTime = Integer.parseInt(df.formatCellValue(sheet.getRow(i).getCell(2)));
					Cell cell = row.createCell(3);
					if (actualTime > benchmarkTime) {
						font.setColor(HSSFColorPredefined.RED.getIndex());
						style.setFont(font);
						cell.setCellStyle(style);
						cell.setCellValue((String) "FAIL");
					} else {
						font.setColor(HSSFColorPredefined.GREEN.getIndex());
						style.setFont(font);
						cell.setCellStyle(style);
						cell.setCellValue((String) "PASS");
					}
				}
			}
			// Close input stream
			inputStream.close();

			// Crating output stream and writing the updated workbook
			FileOutputStream os = new FileOutputStream(filePath);
			workbook.write(os);

			// Close the workbook and output stream
			workbook.close();
			os.close();

			System.out.println("Report has been updated successfully.");

		} catch (EncryptedDocumentException | IOException e) {
			System.err.println("Exception while updating an existing report.");
			e.printStackTrace();
		}
	}

     trackDetailsToReport method will generate a beautiful performance load benchmarking report in excel format. The report will be available under the Reports > Performance > Summary folder in the project structure. Below is the sample format of the report:

     I hope you really enjoyed reading this article and also you got some idea for the implementation wherever it is required in your automation workflow. You can try this logic in both web and mobile automation.

make it perfect!

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: