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;
    }

Tuesday, January 19, 2021

BrowserMob Proxy Integration with Selenium

BrowserMob proxy allows you to manipulate HTTP requests and responses, capture HTTP content, and export performance data as a HAR file.

Add below maven dependency to your pom.xml in the project.

<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
</dependency>

Start a browermob server.

public BrowserMobProxyServer proxy;

    public BrowserMobProxyServer getProxyServer() {
        proxy = new BrowserMobProxyServer();
        proxy.setTrustAllServers(true);
        // above line is needed for application with invalid certificates
        proxy.start();
        return proxy;
    }

Stop a browermob server.
    public void stopProxyServer() {
        if (proxy != null) {
        proxy.stop();
        }
    }

Set browsermob proxy with selenium proxy object.

public Proxy getSeleniumProxy() throws MyException {
        getProxyServer();
        // get the Selenium proxy object - org.openqa.selenium.Proxy;
        Proxy seleniumProxy = ClientUtil.createSeleniumProxy(proxy);
        try {
            String hostIp = Inet4Address.getLocalHost().getHostAddress();
            seleniumProxy.setHttpProxy(hostIp + ":" + proxy.getPort());
            seleniumProxy.setSslProxy(hostIp + ":" + proxy.getPort());
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return seleniumProxy;
    }

Set proxy object with Chrome Options.

public ChromeOptions proxyChromeOptions() throws MyException {
        ChromeOptions chromeOptions = new ChromeOptions();
        try {
            // set proxy object with chromeoption
            chromeOptions.setProxy(getSeleniumProxy());
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return chromeOptions;
    }

Set proxy object with Firefox Options.

public FirefoxOptions proxyFirefoxOptions() throws MyException {
        FirefoxOptions firefoxOptions = new FirefoxOptions();
        try {
            // set proxy object with Firefox option
            firefoxOptions.setProxy(getSeleniumProxy());
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return firefoxOptions;
    }

Set proxy object with Edge Options.

public EdgeOptions proxyEdgeOptions() throws MyException {
        EdgeOptions edgeOptions = new EdgeOptions();
        try {
            // set proxy object with chromeoption
            edgeOptions.setProxy(getSeleniumProxy());
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
        return edgeOptions;
    }

Enable har logs.

public void enableHar(String harLogName) {
        proxy.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
        // create a new HAR with the label (EX:APP Testing)
        proxy.newHar(harLogName);
    }

Write har details in har file.

public void getHarData(String filePath) throws MyException {
        try {
            // get the HAR data
            Har har = proxy.getHar();
            // Write HAR Data in a File (C:\\networklog.har)
            File harFile = new File(filePath);
            har.writeTo(harFile);
        } catch (Exception e) {
            throw new MyException(e.getMessage());
        }
    } 

What is HAR -HTTP Archive format or HAR is a JSON-formatted archive file format for logging of a web browser's interaction with a web application.

To view the HAR file download the HTTP Archive Viewer chrome addon.