Wednesday, March 9, 2022

How to capture browser logs for failed tests

 

public static void getBrowserLog(WebDriver driver) {
        Logs log = driver.manage().logs();
        LogEntries logEntries = log.get(LogType.BROWSER);
        APP_LOGS.info("======== Browser log - starts ========");
        for (LogEntry logEntry : logEntries) {
            APP_LOGS.info(logEntry.getMessage() + "\n");
        }
        APP_LOGS.info("======== Browser log - ends ========");
    } 


Note: Call the above method in onTestFailure method of TestNG listener.

Wednesday, February 23, 2022

How to Automate Slider in Selenium WebDriver

We can achieve it using xOffse and yOffse of the web element and drag and drop by method.

WebElement slider = driver.findElement(By.xpath("//*[@id='slider']/a"));
Actions action = new Actions(driver);
action.dragAndDropBy(source, xOffset, yOffset).build.perform();
action.click();
action.release();

Note: We can get the X,Y coordinates using Page Ruler Redux chrome plugin.
xOffset horizontal move offset (Top value in the Page Ruler).
yOffset vertical move offset (Right value in the Page Ruler).

Monday, January 10, 2022

Taking screenshots for soft asserts

 

it is advisable to take screenshots of failed test cases for further analysis and proof of failure.

 public class CustomSoftAssert extends SoftAssert {
 

private static final String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";


    @Override
    public void onAssertFailure(IAssert<?> assertCommand, AssertionError ex) {
        try {
            WebDriver driver = TestBase.getDriver();
         
            // Take screenshot
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy hh.mm.ss.S");
            String currentTimeInstance = formatter.format(date);
            String screenshotPath = System.getProperty("user.dir")+"/Screenshots"+ "-(" + currentTimeInstance
                    + ").jpg";
         
            File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

            FileUtils.copyFile(scrFile, new File(screenshotPath));


            // To add screenshot to ReportNG HTML report as a link
            System.setProperty(ESCAPE_PROPERTY, "false");
            Reporter.log("<a href=\"" + screenshotPath + "\">Screenshot</a>");

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Tuesday, August 24, 2021

Merging more than one data providers in TestNG

 We can merge more than one data providers into.

EX:

public Object[][] dp1() {
return new Object[][] {{ "a", "b" },{ "c", "d" }};
}
public Object[][] dp2() {
return new Object[][] {{ "e", "f" },{ "g", "h" }};
}

@DataProvider
public Object[][] dp() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(dp1()));
result.addAll(Arrays.asList(dp2()));
return result.toArray(new Object[result.size()][]);
}

@Test(dataProvider = "dp")
public void f(String a, String b) {
System.out.println("f " + a + " " + b);
}

 

Sunday, August 1, 2021

Json dataset to DataProvider

 public class JsonReader {

    public static Object[][] getData(String jsonPath, String dataObject, int totalDataRow, int totalColumnEntry)
            throws Exception {

        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObj = jsonParser.parse(new FileReader(jsonPath)).getAsJsonObject();
        JsonArray array = (JsonArray) jsonObj.get(dataObject);
        return searchJsonElement(array, totalDataRow, totalColumnEntry);

    }

    public static Object[][] toArray(List<List<Object>> list) {
        Object[][] r = new Object[list.size() + 1][];
        int i = 0;
        for (List<Object> next : list) {
            r[i++] = next.toArray(new Object[list.size() + 1]);
        }
        return r;
    }

    public static Object[][] searchJsonElement(JsonArray jsonArray, int totalDataRow, int totalColumnEntry)
            throws Exception {
        Object[][] matrix = new Object[totalDataRow][totalColumnEntry];
        int i = 0;
        int j = 0;
        for (JsonElement jsonElement : jsonArray) {
            for (Map.Entry<String, JsonElement> entry : jsonElement.getAsJsonObject().entrySet()) {
                matrix[i][j] = entry.getValue().toString().replace("\"", "");
                j++;
            }
            i++;
            j = 0;
        }
        return matrix;
    }


    public static void main(String[] args) throws Exception {

        String Json_path = "D:\\xxx\\xxx\\Login.json";
        Object[][] data = JsonReader.getData(Json_path, "LoginData", 2, 3);
        System.out.println(Arrays.deepToString(data));
    }
}

Friday, February 12, 2021

CSV dataset to DataProvider

 private Iterator<Object[]> parseCsvData(String fileName) throws IOException
{
  BufferedReader input = null;
  File file = new File(fileName);
  input = new BufferedReader(new FileReader(file));
  String line = null;
  ArrayList<Object[]> data = new ArrayList<Object[]>();
  while ((line = input.readLine()) != null)
  {
    String in = line.trim();
    String[] temp = in.split(“,”);
    List<Object> arrray = new ArrayList<Object>();
    for(String s : temp)
    {
      arrray.add(Integer.parseInt(s));
    }
    data.add(arrray.toArray());
  }
  input.close();
  return data.iterator();
}


/**
  Use the above method in dataprovider
**/
@DataProvider(name = "testData")
public Iterator<Object[]> testData() throws IOException
{
  return parseTestData(<Location of csv file>);
}

@Test(dataProvider = “testData”)
public void verifyLoginUsingCsv (String username, String password, String testDescription)
{
/** Your Test Code **/
}

Thursday, February 11, 2021

Random Data Generator

 Random Number Generator:

public String randomNumberGenerator(int length) throws Exception{
        Random random = new Random();
        char[] digits = new char[length];
        digits[0] = (char) (random.nextInt(9) + '1');
        for (int i = 1; i < length; i++) {
            digits[i] = (char) (random.nextInt(10) + '0');
        }
        long st = Long.parseLong(new String(digits));
        String uniqueID = String.valueOf(st);
        return uniqueID;
    } 

 Random String Generator:

public String randomStringGenerator(int length) throws Exception {
        // Chose a Character random from this String
        String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvxyz";

        // create StringBuffer size of AlphaNumericString
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int index = (int) (AlphaNumericString.length() * Math.random());

            // add Character one by one in end of sb
            sb.append(AlphaNumericString.charAt(index));
        }

        return sb.toString();
    }

Random Alpha Numeric Generator:

public String randomAlphaNumericGenerator(int length) throws Exception {
        // chose a Character random from this String
        String AlphaNumericString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "0123456789" + "abcdefghijklmnopqrstuvxyz";

        // create StringBuffer size of AlphaNumericString
        StringBuilder sb = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int index = (int) (AlphaNumericString.length() * Math.random());

            // add Character one by one in end of sb
            sb.append(AlphaNumericString.charAt(index));
        }

        return sb.toString();
    }

Random Date Generator:

Enter Start and End Year.

public static int randomInBetween(int start, int end) {
        return start + (int) Math.round(Math.random() * (end - start));
    }

public String randomDateGenerator(int startYear, int endYear) throws Exception {
        int day = createRandomIntBetween(1, 28);
        int month = createRandomIntBetween(1, 12);
        int year = createRandomIntBetween(startYear, endYear);
        return LocalDate.of(year, month, day).toString();
    }

Calculate The Discount Price:

public String calculateDiscount(String Percentage, String Amount) {
        Amount= Amount.replace(",", "");                                                                                                                BigDecimal price = new BigDecimal(Amount);
        BigDecimal discount = new BigDecimal(Percentage);
        BigDecimal ONE_HUNDRED = new BigDecimal(100);
        BigDecimal discountValue = price.multiply(discount).divide(ONE_HUNDRED);
        discountValue = price.subtract(discountValue);
        discountValue = discountValue.setScale(2, BigDecimal.ROUND_HALF_UP);
        double value = Double.parseDouble(discountValue.toString());
        String afterDiscount = NumberFormat.getCurrencyInstance().format(value);
        // To remove prefix $ symbol
        afterDiscount = afterDiscount.substring(1);
        System.out.println("Amount after discount: " + afterDiscount);
        return afterDiscount;
    }