Saturday, 1 December 2018

Open Browser with out downloading driver.exe file || Quick webdriver setup

Dependency:

<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>3.0.0</version>
<scope>test</scope>
</dependency>


Code:

WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();

OR

WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();

OR

WebDriverManager.iedriver().version("3.0.0").setup();
driver = new InternetExplorerDriver();


Friday, 12 October 2018

Java + SOAP API

<dependency>
<groupId>javax.xml.soap</groupId>
<artifactId>javax.xml.soap-api</artifactId>
<version>1.3.8</version>
</dependency>


package com.google.soap;

import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.util.Base64;

import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

public class Final {
public static void main(String[] args) throws SOAPException {
String str = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/ </soapenv:Body></soapenv:Envelope>";
SOAPConnection connection = null;
String authorization = Base64.getEncoder()
.encodeToString(("uname" + ":" + "pwd").getBytes(Charset.forName("UTF-8")));
String endPointURLString = "http://googlec.om/abc";

try {
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
connection = soapConnectionFactory.createConnection();
MessageFactory factory = MessageFactory.newInstance();

SOAPMessage request = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(str.getBytes()));

MimeHeaders headers = request.getMimeHeaders();
headers.addHeader("Authorization", "Basic " + authorization);
headers.addHeader("SOAPAction", "getSum");
headers.addHeader("Content-Type", "multipart/related; type=\"text/xml\";");
request.saveChanges();
SOAPMessage response = connection.call(request, endPointURLString);
System.out.println(getResspString(response));

} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
connection.close();
}
}

public static String getResspString(SOAPMessage response) {
final StringWriter sw = new StringWriter();
try {
TransformerFactory.newInstance().newTransformer().transform(new DOMSource(response.getSOAPPart()),
new StreamResult(sw));
} catch (TransformerException e) {
throw new RuntimeException(e);
}
return sw.toString();
}
}

Thursday, 11 October 2018

JAVA + SOAP API CALL

<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>

public static void main2(String[] args) {
try {
HttpClient client = new HttpClient();
HttpState state = client.getState();
Credentials credentials = new UsernamePasswordCredentials("uname", "pwd");
state.setCredentials(null, null, credentials);

String strXMLFilename = "C:\\Users\\KKasthuri\\Documents\\req.xml";
File input = new File(strXMLFilename);
RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");

String url = "http://abc.com/xyx/proj";
HttpMethod method = new PostMethod(url);
method.setRequestHeader("SOAPAction", "getmthods");
((EntityEnclosingMethod) method).setRequestEntity(entity);

client.executeMethod(method);
String response = method.getResponseBodyAsString();

System.out.println(response);
method.releaseConnection();
} catch (Exception ex) {
}
}



public static void main4(String[] args) {
try {
HttpClient client = new HttpClient();
HttpState state = client.getState();
Credentials credentials = new UsernamePasswordCredentials("uname", "pwd");
state.setCredentials(null, null, credentials);

String url = "http://google.com/test";
HttpMethod method = new PostMethod(url);
method.setRequestHeader("SOAPAction", "MyMethod");
method.setRequestHeader("Content-Type", "text/xml");
((EntityEnclosingMethod) method).setRequestEntity(new StringRequestEntity(
"<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:v1=\"http://yieldstar.com/ws/AppExchange/v1\"><soapenv:Header/><soapenv:Body></soapenv:Body></soapenv:Envelope>"));

client.executeMethod(method);
String response = method.getResponseBodyAsString();

System.out.println(response);
method.releaseConnection();
} catch (Exception ex) {
}
}

Saturday, 22 September 2018

Wednesday, 19 September 2018

TestNG | Running suite file programmatically

public class MainTest {
    public static void main(String[] args){
    List<String> file = new ArrayList<String>();
    file.add("D:/Selenium_workspace/Framework/src/Framework.xml");
    TestNG testNG = new TestNG();
    testNG.setTestSuites(file);
    testNG.run();}
}

Tuesday, 18 September 2018

ATU reports download folder

https://drive.google.com/drive/folders/0B7rZvkq9tkwPMkJlUjJGTkJjOTA

Monday, 17 September 2018

TestNg | Rerun a failed test case ; Amazon interview qn

Option# 1. testng-failed.xml file in test-output directly
when we run any test suite tesng generates testng-failed.xml file if any failure happens. Just go there and right click on it and Run it.

Option#2 IRetryAnalyzer

public class Retry implements IRetryAnalyzer{
int count =0, retryCount = 3;
   public boolean retry(ITestResult result){
       if(count<retryCount){
           count++;
           return true;
         }
    }
}

In Test file
@Test(retryAnalizer=Retry.class)
public void m1(){
}


Option#3: IAnnotationTransformer
a. Use the same Retry class here

b. public class Transformation implement IAnnotationTrnasformer
{
          @Override
          public void transform(ITestAnnotation annotation, Class testClass, Constructor                    testConstructor,Method test method){
           IRetryAnalyzer  retry = annotation.getRetryAnalyzer();
            if(retry == null){
            annoatation.setRetryAnalyzer(Retry.class);
                 }
           }
}
c. add a listener
<listeners>
<listener class-name="com.google.Transformation">
</listners>

TestNG : Hard vs Soft assertion

Soft : Test Fails for sure, but execution Do not Stops even any assertion condition fails.
SoftAssert s = new SoftAssert();
s.assertEquls(1,1);
s.assertEquls(2,1);
s.assertAll();

Hard: Test Fails & STOPS then and their where any assertion condition fails.
Assertion a = new Assertion();
a.assertEquls(1,1);

Testng - how to skip a test case at run time

@Test
public void m1(){
if(aboveMethodFailed)
throw new SkipException("Skipped");
}

using
throw new SkipException("Skipped"); statement we can skip an test case.

Thursday, 16 August 2018

Report NG reports


Report NG report config is quite simple.

1. add dependencies
2. add listeners
3. Verify reports in test-output/HTML folder

As we are aware these ReportNG reports are beautiful than default TestNG reports


Maven dependenciets

<!-- https://mvnrepository.com/artifact/org.uncommons/reportng -->
<dependency>
<groupId>org.uncommons</groupId>
<artifactId>reportng</artifactId>
<version>1.1.4</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/velocity/velocity-dep -->
<dependency>
<groupId>velocity</groupId>
<artifactId>velocity-dep</artifactId>
<version>1.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.inject/guice -->
<dependency>
<groupId>com.google.inject</groupId>
<artifactId>guice</artifactId>
<version>3.0</version>
</dependency>


Add listeners in testng.xml

       <listeners>
<listener class-name="org.uncommons.reportng.HTMLReporter" />
<listener class-name="org.uncommons.reportng.JUnitXMLReporter" />
</listeners>




Thursday, 7 June 2018

Interview Qn: How can we avoid Authentication for gmail.com using webdriver

Hint : Profiles

RemoteWebDriver vs AppiumDriver vs AndroidDriver vs IOSDriver

RemoteWebDriver: This driver class comes directly from the upstream Selenium project. This is a pretty generic driver where initializing the driver means making network requests to a Selenium hub to start a driver session. Since Appium operates on the client-server model, Appium uses this to initialize a driver session. However, directly using the RemoteWebDriver is not recommended since there are other drivers available that offer additional features or convenience functions.

AppiumDriver: This driver class inherits from the RemoteWebDriver class, but it adds in additional functions that are useful in the context of a mobile automation test through the Appium server.

AndroidDriver: This driver class inherits from AppiumDriver, but it adds in additional functions that are useful in the context of a mobile automation test on Android devices through Appium. Only use this driver class if you want to start a test on an Android device or Android emulator.

IOSDriver: This driver class inherits from AppiumDriver, but it adds in additional functions that are useful in the context of a mobile automation test on iOS devices through Appium. Only use this driver class if you want to start a test on an iOS device or iOS emulator.

As you can see, the drivers and their names tie in closely with what they do. When it comes to initializing a driver, only use the Android or IOS drivers.

Wednesday, 16 May 2018

Interview question | Page Factory | Lazy loading

Here is the interview question:

As per "Page Factory", all the elements will be initialized at the time of page load.
But in dynamic applications how page factory works?
Ex: Assure a drop down content ( options)  loads on click of the respected select box, how can you implement page factory for this?, as page factory initializes elements at the time of page load only.

Answer:
Lazy load concept.

AjaxElementLocatorFactory is a lazy load concept in Page Factory pattern to identify WebElements only when they are used in any operation
i.e. a timeOut for a WebElement can be assigned to the Object page class with the help of AjaxElementLocatorFactory.

Syntax : ( similer to plain "Page Factory init elemnts"  method )

PageFactory.initElements(new c(driver, 30), this);

If element not found in 30 secs, NoSuchElemementException throws.

happy coding.

Thursday, 3 May 2018

query HTML String using jsoup

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.commons.lang.RandomStringUtils;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

Public Class Test
{

public void m1(){
try {
URL myUrl = new URL("https://www.hello.com/abc/abo.php");
URLConnection yc = myUrl.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream(), "UTF-8"));
String inputLine;
StringBuilder a = new StringBuilder();
while ((inputLine = in.readLine()) != null)
a.append(inputLine);
in.close();
String str1 = a.toString();
Document parsedHtmlFragment = Jsoup.parse(str1);
Elements matchingLIs = parsedHtmlFragment.select("#ID");

for (Element matchingLI : matchingLIs) {
cGuid = matchingLI.text();
}

} catch (Exception e) {
// TODO: handle exception
} // TODO Auto-generated method stub
}

Thursday, 26 April 2018

Fiddler : App load testing at each layer

How to capture HTTPS traffic in Fiddler

Download Fiddler software: https://www.telerik.com/download/fiddler

Logo:






The software looks like:



No Configuration required to capture Web Requests in Fiddler.

Every browser Requests are captured by default.

BUT:
By default Fiddler doesn’t show the content of Web requests made to HTTPS Url (Secure site) because it's encrypted. Perform following steps if you want to see HTTPS Traffic.

- Launch Fiddler
- Go to Tools > Fiddler Options > HTTPS > Check [Decrypt Https Traffic Option]
- Once prompted accept certificate generated by Fiddler



To view compressed response in fiddler perform following steps.

- Click on the web request entry on left pane
- Click on the Inspector Tab > Click Transformer tab from bottom panel
- Click on transformer tab and select No compression option and then click Raw tab

Wednesday, 25 April 2018

Java Program : write a method to check if it is well formed expression. Eg: {[()]}

This question was asked in an interview that I found interesting.

Here you go.

I know, There are other ways to do it better.

                Map<Character, Character> exprssionMap = new HashMap<>();
exprssionMap.put('{', '}');
exprssionMap.put('[', ']');
exprssionMap.put('(', ')');

String inputExpression = "{[({{)}}]}";
int expressionLengh = inputExpression.length();
if (expressionLengh % 2 == 1) {
System.out.println("malformed Expression; Size of the Expression is not even                                           number");
} else {
for (int i = 0; i < expressionLengh / 2; i++) {
if (!exprssionMap.get(inputExpression.charAt(i))
.equals(inputExpression.charAt(expressionLengh - 1 - i))) {
System.out.println(
"Matching expression not found for: " +                                                                                                    inputExpression.charAt(i) + "; index:" + i);
}
}
}

Happy Coding.

Thursday, 15 February 2018

Selenium Grid -> Get Node Ip address

public  void getNodeIpAddress(){
        try {
            URL url = new URL("http://hub-ip:4444//grid/api/testsession?session="+((RemoteWebDriver) driver).getSessionId().toString());
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", url.toExternalForm());
            DefaultHttpClient client = new DefaultHttpClient();
            HttpHost host = new HttpHost(url.getHost(), url.getPort());
            HttpResponse response = client.execute(host, request);           
            String responseBody=EntityUtils.toString(response.getEntity());
            System.out.println(responseBody);
//Here you can find ip addr of the node machine at ProxyId parameter
            //  URL nodeUrl = new URL(object.getString("proxyId"));
            //return nodeUrl.getHost();
        } catch (Exception e){
        }