diff --git a/pom.xml b/pom.xml index 682fe1c..0fd1bcb 100644 --- a/pom.xml +++ b/pom.xml @@ -49,6 +49,7 @@ 3.20.0 1.14.0 9.5.0 + 5.9 src/test/resources/suites/SuiteFeatureByTag.xml @@ -317,6 +318,13 @@ ${aspectjweaver.version} + + + com.opencsv + opencsv + ${opencsv.version} + + diff --git a/src/main/java/com/anhtester/helpers/CsvHelpers.java b/src/main/java/com/anhtester/helpers/CsvHelpers.java new file mode 100644 index 0000000..575ddb7 --- /dev/null +++ b/src/main/java/com/anhtester/helpers/CsvHelpers.java @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2024 Anh Tester + * Automation Framework Selenium + */ + +package com.anhtester.helpers; + +import com.anhtester.utils.LogUtils; +import com.opencsv.CSVReader; +import com.opencsv.exceptions.CsvException; + +import java.io.FileReader; +import java.io.IOException; +import java.util.List; + +public class CsvHelpers { + + /** + * Reads all data from a CSV file. + * + * @param csvFilePath the path to the CSV file. + * @return a 2D String array containing the CSV data, or null if an error occurs. + */ + public static String[][] readCsvData(String csvFilePath) { + try (CSVReader reader = new CSVReader(new FileReader(csvFilePath))) { + List allRows = reader.readAll(); + return allRows.toArray(new String[0][]); + } catch (IOException | CsvException e) { + LogUtils.error("Failed to read CSV file: " + e.getMessage()); + return new String[0][]; + } + } + +} diff --git a/src/main/java/com/anhtester/helpers/ExcelHelpers.java b/src/main/java/com/anhtester/helpers/ExcelHelpers.java index d1bd287..84bce17 100644 --- a/src/main/java/com/anhtester/helpers/ExcelHelpers.java +++ b/src/main/java/com/anhtester/helpers/ExcelHelpers.java @@ -9,361 +9,319 @@ import com.anhtester.utils.LogUtils; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFCellStyle; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.Hashtable; import java.util.Map; +import java.util.Objects; public class ExcelHelpers { private FileInputStream fis; private FileOutputStream fileOut; - private Workbook workbook; - private Sheet sheet; + private final Workbook workbook; + private final Sheet sheet; private Cell cell; private Row row; - private String excelFilePath; - private Map columns = new HashMap<>(); - - public ExcelHelpers() { - } - - //Set Excel File - public void setExcelFile(String excelPath, String sheetName) { - LogUtils.info("Set Excel File: " + excelPath); - LogUtils.info("Sheet Name: " + sheetName); - + private final String excelFilePath; + private final Map columns = new HashMap<>(); + + /** + * Constructs an ExcelHelpers object and sets up the Excel file and sheet for reading and writing. + * + * @param excelPath the path to the Excel file. + * @param sheetName the name of the sheet to be accessed. + */ + public ExcelHelpers(String excelPath, String sheetName) { + this.excelFilePath = excelPath; try { - File f = new File(excelPath); - - if (!f.exists()) { - try { - LogUtils.info("File Excel path not found."); - throw new InvalidPathForExcelException("File Excel path not found."); - } catch (Exception e) { - e.printStackTrace(); - } - } - if (sheetName.isEmpty()) { - try { - LogUtils.info("The Sheet Name is empty."); - throw new InvalidPathForExcelException("The Sheet Name is empty."); - } catch (Exception e) { - e.printStackTrace(); - } - } - fis = new FileInputStream(excelPath); workbook = WorkbookFactory.create(fis); sheet = workbook.getSheet(sheetName); - //sh = wb.getSheetAt(0); //0 - index of 1st sheet if (sheet == null) { - //sh = wb.createSheet(sheetName); - try { - LogUtils.info("Sheet name not found."); - throw new InvalidPathForExcelException("Sheet name not found."); - } catch (Exception e) { - e.printStackTrace(); - } + throw new InvalidPathForExcelException("Sheet with name '" + sheetName + "' does not exist in the Excel file."); } + mapColumnHeaders(); + } catch (IOException e) { + throw new RuntimeException("Failed to read the Excel file: " + e.getMessage(), e); + } + } - excelFilePath = excelPath; - - //adding all the column header names to the map 'columns' - sheet.getRow(0).forEach(cell -> { + /** + * Maps the column headers to their respective column indices. + */ + private void mapColumnHeaders() { + Row firstRow = sheet.getRow(0); + if (firstRow != null) { + firstRow.forEach(cell -> { columns.put(cell.getStringCellValue(), cell.getColumnIndex()); }); - - } catch (Exception e) { - e.getMessage(); - LogUtils.error(e.getMessage()); } } - //This method takes the row number as a parameter and returns the data for that row. - public Row getRowData(int rowNum) { - row = sheet.getRow(rowNum); - return row; - } - - - public Object[][] getExcelData(String excelPath, String sheetName) { - Object[][] data = null; - Workbook workbook = null; - - LogUtils.info("Set Excel file " + excelPath); - LogUtils.info("Selected Sheet: " + sheetName); - + /** + * Closes the workbook and input stream to release file resources. + */ + public void close() { try { - - File f = new File(excelPath); - - if (!f.exists()) { - try { - LogUtils.info("File Excel path not found."); - throw new InvalidPathForExcelException("File Excel path not found."); - } catch (Exception e) { - e.printStackTrace(); - } + if (workbook != null) { + workbook.close(); } - if (sheetName.isEmpty()) { - try { - LogUtils.info("The Sheet Name is empty."); - throw new InvalidPathForExcelException("The Sheet Name is empty."); - } catch (Exception e) { - e.printStackTrace(); - } + if (fis != null) { + fis.close(); } + } catch (IOException e) { + LogUtils.error("Failed to close the Excel file resources: " + e.getMessage()); + } + } - // load the file - FileInputStream fis = new FileInputStream(excelPath); - - // load the workbook - workbook = new XSSFWorkbook(fis); - // load the sheet - Sheet sheet = workbook.getSheet(sheetName); - // load the row - Row row = sheet.getRow(0); - - int noOfRows = sheet.getPhysicalNumberOfRows(); - int noOfCols = row.getLastCellNum(); - - System.out.println(noOfRows + " - " + noOfCols); - - Cell cell; - data = new Object[noOfRows - 1][noOfCols]; - - //FOR loop runs from 1 to drop header line (headline is 0) - for (int i = 1; i < noOfRows; i++) { - for (int j = 0; j < noOfCols; j++) { - row = sheet.getRow(i); - cell = row.getCell(j); - - //This is used to determine the data type from cells in Excel and then convert it to String for ease of reading - switch (cell.getCellType()) { - case STRING: - data[i - 1][j] = cell.getStringCellValue(); - break; - case NUMERIC: - data[i - 1][j] = String.valueOf(cell.getNumericCellValue()); - break; - case BLANK: - data[i - 1][j] = ""; - break; - default: - data[i - 1][j] = null; - break; - } + /** + * Saves the changes made to the workbook back to the Excel file. + */ + public void save() { + try { + fileOut = new FileOutputStream(excelFilePath); + workbook.write(fileOut); + } catch (IOException e) { + LogUtils.error("Failed to save the Excel file: " + e.getMessage()); + } finally { + try { + if (fileOut != null) { + fileOut.close(); } + } catch (IOException e) { + LogUtils.error("Failed to close the FileOutputStream: " + e.getMessage()); } - } catch (Exception e) { - e.getMessage(); - throw new RuntimeException(e); } - return data; } - public Object[][] getDataHashTable(String excelPath, String sheetName, int startRow, int endRow) { - LogUtils.info("Excel File: " + excelPath); - LogUtils.info("Sheet Name: " + sheetName); - - Object[][] data = null; - - try { - - File f = new File(excelPath); - - if (!f.exists()) { - try { - LogUtils.info("File Excel path not found."); - throw new InvalidPathForExcelException("File Excel path not found."); - } catch (Exception e) { - e.printStackTrace(); + /** + * Retrieves the cell value as a String. + * + * @param cell the cell from which to retrieve the value. + * @return the cell value as a String, or an empty string if the cell is null. + */ + private String getCellValue(Cell cell) { + if (cell == null) { + return ""; + } + switch (cell.getCellType()) { + case STRING: + return cell.getStringCellValue(); + case NUMERIC: + if (DateUtil.isCellDateFormatted(cell)) { + return Objects.toString(cell.getDateCellValue(), ""); } - } + return Objects.toString((long) cell.getNumericCellValue(), ""); + case BOOLEAN: + return Objects.toString(cell.getBooleanCellValue(), ""); + case BLANK: + return ""; + default: + return cell.toString(); + } + } - fis = new FileInputStream(excelPath); - workbook = new XSSFWorkbook(fis); - sheet = workbook.getSheet(sheetName); + /** + * Gets the data from the specified row. + * + * @param rowNum the row number. + * @return the Row object. + */ + public Row getRowData(int rowNum) { + return sheet.getRow(rowNum); + } - int rows = getRows(); - int columns = getColumns(); + /** + * Retrieves all test data from the Excel sheet as a 2D array of Hashtables. + * + * @return a 2D array of objects, where each object is a Hashtable representing a row of data. + */ + public Object[][] getTestData() { + return getTestData(1, getRows()); + } - LogUtils.info("Row: " + rows + " - Column: " + columns); - LogUtils.info("StartRow: " + startRow + " - EndRow: " + endRow); + /** + * Retrieves test data from a specified range of rows in the Excel sheet. + * + * @param startRow the starting row number. + * @param endRow the ending row number. + * @return a 2D array of objects, where each object is a Hashtable representing a row of data. + */ + public Object[][] getTestData(int startRow, int endRow) { + Object[][] data = new Object[(endRow - startRow) + 1][1]; + Hashtable table; + for (int i = startRow; i <= endRow; i++) { + table = new Hashtable<>(); + Row row = getRowData(i); + for (int j = 0; j < getColumns(); j++) { + String header = getCellValue(getRowData(0).getCell(j)); + String value = getCellValue(row.getCell(j)); + table.put(header, value); + } + data[i - startRow][0] = table; + } + return data; + } - data = new Object[(endRow - startRow) + 1][1]; - Hashtable table = null; - for (int rowNums = startRow; rowNums <= endRow; rowNums++) { - table = new Hashtable<>(); - for (int colNum = 0; colNum < columns; colNum++) { - table.put(getCellData(0, colNum), getCellData(rowNums, colNum)); + /** + * Retrieves all data from the sheet as a 2D String array, skipping the header row. + * + * @return a 2D String array containing the sheet data. + */ + public String[][] getSheetData() { + int rowCount = getRows(); + int colCount = getColumns(); + String[][] data = new String[rowCount][colCount]; + for (int i = 1; i <= rowCount; i++) { + Row row = getRowData(i); + if (row != null) { + for (int j = 0; j < colCount; j++) { + data[i - 1][j] = getCellValue(row.getCell(j)); } - data[rowNums - startRow][0] = table; } - - } catch (IOException e) { - e.printStackTrace(); - LogUtils.error(e.getMessage()); } - return data; - } + /** + * Gets the name of the test case from a given string. + * + * @param testCaseName the full test case name. + * @return the simplified test case name. + */ public String getTestCaseName(String testCaseName) { - String value = testCaseName; - int position = value.indexOf("@"); - value = value.substring(0, position); - position = value.lastIndexOf("."); - - value = value.substring(position + 1); - return value; + int atIndex = testCaseName.indexOf('@'); + if (atIndex != -1) { + testCaseName = testCaseName.substring(0, atIndex); + } + int dotIndex = testCaseName.lastIndexOf('.'); + if (dotIndex != -1) { + testCaseName = testCaseName.substring(dotIndex + 1); + } + return testCaseName; } - public int getRowContains(String sTestCaseName, int colNum) { - int i; - int rowCount = getRows(); - for (i = 0; i < rowCount; i++) { - if (getCellData(i, colNum).equalsIgnoreCase(sTestCaseName)) { - break; + /** + * Finds the row number that contains a specific test case name in a given column. + * + * @param testCaseName the name of the test case to find. + * @param colNum the column number to search in. + * @return the row number, or -1 if not found. + */ + public int getRowContains(String testCaseName, int colNum) { + for (int i = 0; i <= getRows(); i++) { + if (getCellData(i, colNum).equalsIgnoreCase(testCaseName)) { + return i; } } - return i; + return -1; } + /** + * Gets the total number of rows in the sheet. + * + * @return the last row number. + */ public int getRows() { - try { - return sheet.getLastRowNum(); - } catch (Exception e) { - System.out.println(e.getMessage()); - throw (e); - } + return sheet.getLastRowNum(); } + /** + * Gets the total number of columns in the sheet. + * + * @return the last column number in the first row. + */ public int getColumns() { - try { - row = sheet.getRow(0); - return row.getLastCellNum(); - } catch (Exception e) { - System.out.println(e.getMessage()); - throw (e); - } + return sheet.getRow(0).getLastCellNum(); } - // Get cell data + /** + * Gets the data of a specific cell by row and column number. + * + * @param rowNum the row number. + * @param colNum the column number. + * @return the cell data as a String. + */ public String getCellData(int rowNum, int colNum) { - try { - cell = sheet.getRow(rowNum).getCell(colNum); - String CellData = null; - switch (cell.getCellType()) { - case STRING: - CellData = cell.getStringCellValue(); - break; - case NUMERIC: - if (DateUtil.isCellDateFormatted(cell)) { - CellData = String.valueOf(cell.getDateCellValue()); - } else { - CellData = String.valueOf((long) cell.getNumericCellValue()); - } - break; - case BOOLEAN: - CellData = Boolean.toString(cell.getBooleanCellValue()); - break; - case BLANK: - CellData = ""; - break; - } - return CellData; - } catch (Exception e) { - return ""; - } + if (rowNum < 0 || colNum < 0) return ""; + row = sheet.getRow(rowNum); + if (row == null) return ""; + cell = row.getCell(colNum); + return getCellValue(cell); } + /** + * Gets the data of a specific cell by row number and column name. + * + * @param rowNum the row number. + * @param columnName the column name. + * @return the cell data as a String. + */ public String getCellData(int rowNum, String columnName) { + if (!columns.containsKey(columnName)) { + LogUtils.error("Column '" + columnName + "' does not exist."); + return ""; + } return getCellData(rowNum, columns.get(columnName)); } - // Write data to excel sheet + /** + * Sets the data of a specific cell by row and column number. + * + * @param text the text to set. + * @param rowNumber the row number. + * @param colNumber the column number. + */ public void setCellData(String text, int rowNumber, int colNumber) { - try { - row = sheet.getRow(rowNumber); - if (row == null) { - row = sheet.createRow(rowNumber); - } - cell = row.getCell(colNumber); - - if (cell == null) { - cell = row.createCell(colNumber); - } - cell.setCellValue(text); - - XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle(); - text = text.trim().toLowerCase(); - if (text == "pass" || text == "passed" || text == "success") { - style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); - } - if (text == "fail" || text == "failed" || text == "failure") { - style.setFillForegroundColor(IndexedColors.RED.getIndex()); - } - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - - cell.setCellStyle(style); - - fileOut = new FileOutputStream(excelFilePath); - workbook.write(fileOut); - fileOut.flush(); - fileOut.close(); - } catch (Exception e) { - e.getMessage(); - LogUtils.error(e.getMessage()); + row = sheet.getRow(rowNumber); + if (row == null) { + row = sheet.createRow(rowNumber); } + cell = row.getCell(colNumber); + if (cell == null) { + cell = row.createCell(colNumber); + } + cell.setCellValue(text); + applyCellStyle(cell, text); } + /** + * Sets the data of a specific cell by row number and column name. + * + * @param text the text to set. + * @param rowNumber the row number. + * @param columnName the column name. + */ public void setCellData(String text, int rowNumber, String columnName) { - try { - row = sheet.getRow(rowNumber); - if (row == null) { - row = sheet.createRow(rowNumber); - } - cell = row.getCell(columns.get(columnName)); - - if (cell == null) { - cell = row.createCell(columns.get(columnName)); - } - cell.setCellValue(text); - - XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle(); - text = text.trim().toLowerCase(); - if (text == "pass" || text == "passed" || text == "success") { - style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); - } - if (text == "fail" || text == "failed" || text == "failure") { - style.setFillForegroundColor(IndexedColors.RED.getIndex()); - } - - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setAlignment(HorizontalAlignment.CENTER); - style.setVerticalAlignment(VerticalAlignment.CENTER); - - cell.setCellStyle(style); - - fileOut = new FileOutputStream(excelFilePath); - workbook.write(fileOut); - fileOut.flush(); - fileOut.close(); - } catch (Exception e) { - e.getMessage(); - LogUtils.error(e.getMessage()); + if (!columns.containsKey(columnName)) { + LogUtils.error("Column '" + columnName + "' does not exist. Cannot set cell data."); + return; } + setCellData(text, rowNumber, columns.get(columnName)); } - + /** + * Applies cell style based on the cell text (e.g., "pass" or "fail"). + * + * @param cell the cell to style. + * @param text the text content of the cell. + */ + private void applyCellStyle(Cell cell, String text) { + XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle(); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + + String lowerCaseText = text.trim().toLowerCase(); + if (lowerCaseText.equals("pass") || lowerCaseText.equals("passed") || lowerCaseText.equals("success")) { + style.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); + } else if (lowerCaseText.equals("fail") || lowerCaseText.equals("failed") || lowerCaseText.equals("failure")) { + style.setFillForegroundColor(IndexedColors.RED.getIndex()); + } + cell.setCellStyle(style); + } } diff --git a/src/main/java/com/anhtester/helpers/JsonHelpers.java b/src/main/java/com/anhtester/helpers/JsonHelpers.java index f345ccc..9116e92 100644 --- a/src/main/java/com/anhtester/helpers/JsonHelpers.java +++ b/src/main/java/com/anhtester/helpers/JsonHelpers.java @@ -1,344 +1,99 @@ package com.anhtester.helpers; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; -import com.google.gson.JsonObject; -import com.anhtester.constants.FrameworkConstants; import com.anhtester.utils.LogUtils; -import org.testng.annotations.Test; -import java.io.*; -import java.nio.file.Files; -import java.nio.file.Paths; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; public class JsonHelpers { - @Test - public void testGetValue() { - getValueJsonObject("vehicle", "oto", "number"); - getValueJsonObject("vehicle", "oto", "hyundai"); - getValueJsonObject("users", "new_email"); - //updateValueJsonObject("users", "inbox_id", "123456789"); - - getValueJsonFileArray( - "src/test/resources/testdata/JsonDataTest2.json", - 0, - "lastname" - ); - getValueJsonFileArray( - "src/test/resources/testdata/JsonDataTest2.json", - 0, - "bookingdates", - "checkin" - ); - updateValueJsonFile_Object( - "src/test/resources/testdata/JsonDataTest1.json", - "body", - "height", - 165 - ); - } - - public static String getValueJsonObject(String keyName) { - String value = null; - ObjectMapper objectMapper = new ObjectMapper(); - + private static final ObjectMapper objectMapper = new ObjectMapper(); + + /** + * Reads a JSON file and maps it to a specified class. + * + * @param jsonFilePath the path to the JSON file. + * @param clazz the class to map the JSON to. + * @param the type of the class. + * @return an object of the specified class, or null if an error occurs. + */ + public static T readJsonFile(String jsonFilePath, Class clazz) { try { - // Parse the JSON file into a JsonNode - JsonNode rootNode = objectMapper.readTree(new File(FrameworkConstants.JSON_DATA_FILE_PATH)); - - value = rootNode.path(keyName).asText(); - LogUtils.info("Value: " + value); - + return objectMapper.readValue(new File(jsonFilePath), clazz); } catch (IOException e) { - e.printStackTrace(); + LogUtils.error("Failed to read JSON file: " + e.getMessage()); + return null; } - return value; } - public static String getValueJsonObject(String parentKey, String keyName) { - String value = null; - ObjectMapper objectMapper = new ObjectMapper(); - + /** + * Reads a JSON file and maps it to a list of objects. + * + * @param jsonFilePath the path to the JSON file. + * @param typeReference the type reference for the list of objects. + * @param the type of the objects in the list. + * @return a list of objects, or null if an error occurs. + */ + public static List readJsonFileToList(String jsonFilePath, TypeReference> typeReference) { try { - // Parse the JSON file into a JsonNode - JsonNode rootNode = objectMapper.readTree(new File(FrameworkConstants.JSON_DATA_FILE_PATH)); - - value = rootNode.path(parentKey).path(keyName).asText(); - LogUtils.info("Value: " + value); - + return objectMapper.readValue(new File(jsonFilePath), typeReference); } catch (IOException e) { - e.printStackTrace(); + LogUtils.error("Failed to read JSON file: " + e.getMessage()); + return null; } - return value; } - public static String getValueJsonObject(String parentKey1, String parentKey2, String keyName) { - String value = null; - ObjectMapper objectMapper = new ObjectMapper(); - + /** + * Reads a JSON file and maps it to a map of objects. + * + * @param jsonFilePath the path to the JSON file. + * @param typeReference the type reference for the map of objects. + * @param the type of the keys in the map. + * @param the type of the values in the map. + * @return a map of objects, or null if an error occurs. + */ + public static Map readJsonFileToMap(String jsonFilePath, TypeReference> typeReference) { try { - // Parse the JSON file into a JsonNode - JsonNode rootNode = objectMapper.readTree(new File(FrameworkConstants.JSON_DATA_FILE_PATH)); - - value = rootNode.path(parentKey1).path(parentKey2).path(keyName).asText(); - LogUtils.info("Value: " + value); - + return objectMapper.readValue(new File(jsonFilePath), typeReference); } catch (IOException e) { - e.printStackTrace(); + LogUtils.error("Failed to read JSON file: " + e.getMessage()); + return null; } - return value; } - public static String getValueJsonFileArray(String filePath, int itemIndex, String keyName) { - String value = null; - ObjectMapper objectMapper = new ObjectMapper(); - + /** + * Writes an object to a JSON file. + * + * @param jsonFilePath the path to the JSON file. + * @param object the object to write. + */ + public static void writeJsonFile(String jsonFilePath, Object object) { try { - JsonNode rootNode = objectMapper.readTree(new File(filePath)); - JsonNode itemNode = rootNode.get(itemIndex); - - value = itemNode.path(keyName).asText(); - LogUtils.info("Value: " + value); - + objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(jsonFilePath), object); } catch (IOException e) { - e.printStackTrace(); + LogUtils.error("Failed to write JSON file: " + e.getMessage()); } - return value; } - public static String getValueJsonFileArray(String filePath, int itemIndex, String parentKey, String keyName) { - String value = null; - ObjectMapper objectMapper = new ObjectMapper(); - + /** + * Gets a specific node from a JSON file. + * + * @param jsonFilePath the path to the JSON file. + * @param nodeName the name of the node to get. + * @return the JsonNode, or null if an error occurs. + */ + public static JsonNode getJsonNode(String jsonFilePath, String nodeName) { try { - JsonNode rootNode = objectMapper.readTree(new File(filePath)); - JsonNode itemNode = rootNode.get(itemIndex); - - value = itemNode.path(parentKey).path(keyName).asText(); - LogUtils.info("Value: " + value); - + JsonNode rootNode = objectMapper.readTree(new File(jsonFilePath)); + return rootNode.path(nodeName); } catch (IOException e) { - e.printStackTrace(); + LogUtils.error("Failed to get JSON node: " + e.getMessage()); + return null; } - return value; } - - public static void updateValueJsonObject(String keyName, Number value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(FrameworkConstants.JSON_DATA_FILE_PATH)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to file - File jsonFile = new File(FrameworkConstants.JSON_DATA_FILE_PATH); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - reader.close(); - - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void updateValueJsonObject(String keyName, String value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(FrameworkConstants.JSON_DATA_FILE_PATH)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to file - File jsonFile = new File(FrameworkConstants.JSON_DATA_FILE_PATH); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - reader.close(); - - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void updateValueJsonObject(String parentKey, String keyName, Number value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(FrameworkConstants.JSON_DATA_FILE_PATH)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.getAsJsonObject(parentKey).addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to file - File jsonFile = new File(FrameworkConstants.JSON_DATA_FILE_PATH); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - reader.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void updateValueJsonObject(String parentKey, String keyName, String value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(FrameworkConstants.JSON_DATA_FILE_PATH)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.getAsJsonObject(parentKey).addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to file - File jsonFile = new File(FrameworkConstants.JSON_DATA_FILE_PATH); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - reader.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void updateValueJsonFile_Object(String filePath, String keyName, String value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(filePath)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to new file - File jsonFile = new File(filePath); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - - //Close reader - reader.close(); - - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void updateValueJsonFile_Object(String filePath, String keyName, Number value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(filePath)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to new file - File jsonFile = new File(filePath); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - - //Close reader - reader.close(); - - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void updateValueJsonFile_Object(String filePath, String parentKey, String keyName, String value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(filePath)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.getAsJsonObject(parentKey).addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to file - File jsonFile = new File(filePath); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - reader.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void updateValueJsonFile_Object(String filePath, String parentKey, String keyName, Number value) { - Reader reader; - try { - reader = Files.newBufferedReader(Paths.get(filePath)); - - Gson gson = new Gson(); - //Convert Json file to Json Object - JsonObject jsonObject = gson.fromJson(reader, JsonObject.class); - LogUtils.info("Original JSON: " + jsonObject); - - //Update value if exist key - jsonObject.getAsJsonObject(parentKey).addProperty(keyName, value); - - LogUtils.info("Modified JSON: " + jsonObject); - - //Store new Json data to file - File jsonFile = new File(filePath); - OutputStream outputStream = new FileOutputStream(jsonFile); - outputStream.write(gson.toJson(jsonObject).getBytes()); - outputStream.flush(); - reader.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } diff --git a/src/test/java/com/anhtester/dataprovider/DataProviderManager.java b/src/test/java/com/anhtester/dataprovider/DataProviderManager.java index 877a6ef..7297ed4 100644 --- a/src/test/java/com/anhtester/dataprovider/DataProviderManager.java +++ b/src/test/java/com/anhtester/dataprovider/DataProviderManager.java @@ -1,68 +1,31 @@ -/* - * Copyright (c) 2022. Anh Tester - * Automation Framework Selenium - */ package com.anhtester.dataprovider; import com.anhtester.constants.FrameworkConstants; import com.anhtester.helpers.ExcelHelpers; import com.anhtester.helpers.SystemHelpers; -import com.anhtester.projects.website.crm.models.ClientModel; -import com.anhtester.projects.website.crm.models.SignInModel; import org.testng.annotations.DataProvider; -import org.testng.annotations.Test; - -import java.util.Hashtable; public final class DataProviderManager { private DataProviderManager() { } - @Test(dataProvider = "getSignInDataHashTable") - public void testGetSignInData(Hashtable data) { - System.out.println("signInData.testCaseName = " + data.get(SignInModel.getTestCaseName())); - System.out.println("signInData.username = " + data.get(SignInModel.getEmail())); - System.out.println("signInData.password = " + data.get(SignInModel.getPassword())); - System.out.println("signInData.expectedTitle = " + data.get(SignInModel.getExpectedTitle())); - System.out.println("signInData.expectedError = " + data.get(SignInModel.getExpectedError())); - - } - - @Test(dataProvider = "getClientDataHashTable") - public void testGetClientData(Hashtable data) { - System.out.println("clientData.TestCaseName = " + data.get(ClientModel.getTestCaseName())); - System.out.println("clientData.CompanyName = " + data.get(ClientModel.getCompanyName())); - System.out.println("clientData.OWNER = " + data.get(ClientModel.getOwner())); - System.out.println("clientData.Address = " + data.get(ClientModel.getAddress())); - System.out.println("clientData.CITY = " + data.get(ClientModel.getCity())); - System.out.println("clientData.STATE = " + data.get(ClientModel.getState())); - - } - - @DataProvider(name = "getSignInDataHashTable") + @DataProvider(name = "getSignInDataHashTable", parallel = true) public static Object[][] getSignInData() { - ExcelHelpers excelHelpers = new ExcelHelpers(); - Object[][] data = excelHelpers.getDataHashTable(SystemHelpers.getCurrentDir() + FrameworkConstants.EXCEL_DATA_FILE_PATH, "SignIn", 1, 2); - System.out.println("getSignInData: " + data); - return data; + ExcelHelpers excelHelpers = new ExcelHelpers(FrameworkConstants.EXCEL_DATA_FILE_PATH, "SignIn"); + return excelHelpers.getTestData(1, 2); } - @DataProvider(name = "getSignInDataHashTable2") + @DataProvider(name = "getSignInDataHashTable2", parallel = true) public static Object[][] getSignInData2() { - ExcelHelpers excelHelpers = new ExcelHelpers(); - Object[][] data = excelHelpers.getDataHashTable(SystemHelpers.getCurrentDir() + FrameworkConstants.EXCEL_DATA_FILE_PATH, "SignIn", 2, 3); - System.out.println("getSignInData: " + data); - return data; + ExcelHelpers excelHelpers = new ExcelHelpers(FrameworkConstants.EXCEL_DATA_FILE_PATH, "SignIn"); + return excelHelpers.getTestData(2, 3); } @DataProvider(name = "getClientDataHashTable", parallel = true) public static Object[][] getClientData() { - ExcelHelpers excelHelpers = new ExcelHelpers(); - Object[][] data = excelHelpers.getDataHashTable(SystemHelpers.getCurrentDir() + FrameworkConstants.EXCEL_DATA_FILE_PATH, "Client", 1, 3); - System.out.println("getClientData: " + data); - return data; + ExcelHelpers excelHelpers = new ExcelHelpers(FrameworkConstants.EXCEL_DATA_FILE_PATH, "Client"); + return excelHelpers.getTestData(1, 3); } - } diff --git a/src/test/java/com/anhtester/projects/website/crm/pages/SignIn/SignInPageCRM.java b/src/test/java/com/anhtester/projects/website/crm/pages/SignIn/SignInPageCRM.java index 5ad3963..6aa170c 100644 --- a/src/test/java/com/anhtester/projects/website/crm/pages/SignIn/SignInPageCRM.java +++ b/src/test/java/com/anhtester/projects/website/crm/pages/SignIn/SignInPageCRM.java @@ -15,8 +15,8 @@ public class SignInPageCRM extends CommonPageCRM { - private String pageUrl = "/signin"; - private String pageTitle = "Sign in | RISE CRM | Anh Tester Demo"; + private final String pageUrl = "/signin"; + private final String pageTitle = "Sign in | RISE CRM | Anh Tester Demo"; public By inputEmail = By.xpath("//input[@id='email']"); public By inputPassword = By.xpath("//input[@id='password']"); @@ -27,16 +27,14 @@ public class SignInPageCRM extends CommonPageCRM { public By labelEmailError = By.xpath("//span[@id='email-error']"); public By labelPasswordError = By.xpath("//span[@id='password-error']"); - - ExcelHelpers excelHelpers; + private final ExcelHelpers excelHelpers; public SignInPageCRM() { super(); - excelHelpers = new ExcelHelpers(); + excelHelpers = new ExcelHelpers(FrameworkConstants.EXCEL_DATA_FILE_PATH, "SignIn"); } public DashboardPageCRM signInWithAdminRole() { - excelHelpers.setExcelFile(FrameworkConstants.EXCEL_DATA_FILE_PATH, "SignIn"); openWebsite(FrameworkConstants.URL_CRM); verifyContains(getCurrentUrl(), pageUrl, "The url of sign in page not match."); verifyEquals(getPageTitle(), pageTitle, "The title of sign in page not match."); @@ -50,7 +48,6 @@ public DashboardPageCRM signInWithAdminRole() { } public DashboardPageCRM signInWithClientRole() { - excelHelpers.setExcelFile(FrameworkConstants.EXCEL_DATA_FILE_PATH, "SignIn"); openWebsite(FrameworkConstants.URL_CRM); verifyContains(getCurrentUrl(), pageUrl, "The url of sign in page not match."); verifyEquals(getPageTitle(), pageTitle, "The title of sign in page not match."); @@ -88,15 +85,14 @@ public DashboardPageCRM signIn(Hashtable data) { return new DashboardPageCRM(); } - public void verifySignInSuccess(){ + public void verifySignInSuccess() { waitForPageLoaded(); Assert.assertTrue(checkElementExist(getDashboardPage().menuDashboard), "The Dashboard page not display."); } - public void verifySignInFail(){ + public void verifySignInFail() { waitForPageLoaded(); - Assert.assertTrue(checkElementExist(alertErrorMessage), "The Dashboard page not display."); + Assert.assertTrue(checkElementExist(alertErrorMessage), "The error message is not displayed."); Assert.assertEquals(getTextElement(alertErrorMessage), "Authentication failed!", "The error message content not match."); } - -} \ No newline at end of file +}