Tuesday, August 23, 2016

Find Broken / Invalid Links and Images on a Page



/**
* Validate invalid images on the webpage
*/

public void validateInvalidImages() {

try {

int invalidImageCount = 0;

List "<"imagesList">" = driver.findElements(By.tagName("img"));
System.out.println("Total no.of images are :: " + imagesList.size());
for (WebElement imgElement : imagesList) {
if (imgElement != null) {
invalidImageCount = verifyimageActive(imgElement);
}
}
System.out.println("Total no.of invalid images are :: " + invalidImageCount);

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

}

public static void verifyimageActive(WebElement imgElement) {
int invalidImageCount =0;
try {
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(imgElement.getAttribute("src"));
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() != 200){
invalidImageCount++;
}
} catch (Exception e) {
e.printStackTrace();
}
return invalidImageCount;
}


/**
* Validate brokenLinks on the webpage
*/

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class VerifyLinks {
 public static void main(String[] args)
 {
  WebDriver driver=new FirefoxDriver(); 
  driver.manage().window().maximize(); 
  driver.get("http://www.google.co.in/");
 
  List links=driver.findElements(By.tagName("a"));
  System.out.println("Total links are "+links.size());
 
  for(int i=0;i<
links.size(); i++){
   WebElement ele= links.get(i);
   String url=ele.getAttribute("href");
   verifyLinkActive(url);
  }
 }

 public static void verifyLinkActive(String linkUrl)
 {
        try
        {
           URL url = new URL(linkUrl);
           HttpURLConnection httpURLConnect=(HttpURLConnection)url.openConnection();
           httpURLConnect.setConnectTimeout(3000);
           httpURLConnect.connect();
 
           if(httpURLConnect.getResponseCode()==200)
           {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage());
            }
          if(httpURLConnect.getResponseCode()==HttpURLConnection.HTTP_NOT_FOUND) 
           {
               System.out.println(linkUrl+" - "+httpURLConnect.getResponseMessage() + " - "+ HttpURLConnection.HTTP_NOT_FOUND);
            }
        } catch (Exception e) {
           e.printStackTrace();
        }
    }
 
}

Tuesday, August 9, 2016

How to check data with arthematic Operators in Java?


public static void compareTo() {

String s1 = "Say";

String s2 = "Tell";



if (s1.compareTo(s2) > 0) {

System.out.println("s1 is Greater s2");

} else if (s1.compareTo(s2) < 0) {

System.out.println("s1 is Lesser s2");

} else if (s1.compareTo(s2) == 0) {

System.out.println("s1 is equal to s2");

} else if (s1.compareTo(s2) != 0) {

System.out.println("s1 is Not equal to s2");

} else if (s1.compareTo(s2) >= 0) {

System.out.println("s1 is GreaterThan to s2");

} else if (s1.compareTo(s2) <= 0) {

System.out.println("s1 is LessThan to s2");

}

}

Tuesday, August 2, 2016

How to Resolve the Certificate Error with Selenium Webdriver?

IE :

driver.get("yourwebsite url that had certificate error");
driver.navigate().to("javascript:document.getElementById('overridelink').click()");
Thread.sleep(5000);

FIREFOX:

DesiredCapabilities capabilities = new DesiredCapabilities(); 
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); 
driver= new FirefoxDriver(capabilities);
driver.get("yourwebsite url that had certificate error");

Chrome:

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
 capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true); 
 System.setProperty("webdriver.chrome.driver", "path to file chromedriver.exe");
 WebDriver driver = new ChromeDriver(capabilities);
 driver.get("yourwebsite url that had certificate error");
 
 

 

Wednesday, July 27, 2016

Getting the name of the current executing method

String methodName = new Object(){}.getClass().getEnclosingMethod().getName();
(OR)
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
 

 
 
 
 
 

Monday, July 25, 2016

Currency and Phone Number Format Check?


public String currencyFormatCheck(String location, int currencyValue) {
if (location.equalsIgnoreCase("US")) {
Locale currentLocale = Locale.US;
Double currencyAmount = new Double(currencyValue);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
return currencyFormatter.format(currencyAmount);
} else if (location.equalsIgnoreCase("UK")) {
Locale currentLocale = Locale.UK;
Double currencyAmount = new Double(currencyValue);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
return currencyFormatter.format(currencyAmount);
}
return null;
}
 
private static boolean phoneNumberFormatCheck(String phoneNo) {
// validate phone numbers of format "1234567890"
if (phoneNo.matches("\\d{10}"))
return true;
// validating phone number with -, . or spaces
else if (phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}"))
return true;
// validating phone number with extension length from 3 to 5
else if (phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}"))
return true;
// validating phone number where area code is in braces ()
else if (phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}"))
return true;
// return false if nothing matches the input
else
return false;
}

//Example '(866) 825-3227' then you can use below regular expression

public static boolean validatePhone(String phone) {
 String phonePattern = "\\([0-9]{3}) [0-9]{3}\\-[0-9]{4}";
 // e.g. (866) 825-3227
 Pattern pattern = Pattern.compile(phonePattern);
 Matcher matcher = pattern.matcher(phone);
 return matcher.matches();
}

Tuesday, July 5, 2016

Resizing a web element using movebyoffset

public void resize(WebElement elementToResize, int xOffset, int yOffset) {
        try {
        if (elementToResize.isDisplayed()) {
        Actions action = new Actions(driver);
        action.clickAndHold(elementToResize).moveByOffset(xOffset, yOffset).release().build().perform();
        } else {
        System.out.println("Element was not displayed to drag");
        }
        } catch (StaleElementReferenceException e) {
        System.out.println("Element with " + elementToResize + "is not attached to the page document "  + e.getStackTrace());
        } catch (NoSuchElementException e) {
        System.out.println("Element " + elementToResize + " was not found in DOM " + e.getStackTrace());
        } catch (Exception e) {
        System.out.println("Unable to resize" + elementToResize + " - " + e.getStackTrace());
        }
        }

(OR)

moveToElement(WebElement toElement, int xOffset, int yOffset)
Moves the mouse to an offset from the top-left corner of the element.
 
Actions builder = new Actions(driver);   
builder.moveToElement(knownElement, 10, 25).click().build().perform();

Monday, June 20, 2016

TestNG Annotation

TestNG Annotation

Annotation
Description
@BeforeSuite
The annotated method will be run only once before all tests in this suite have run.
@AfterSuite
The annotated method will be run only once after all tests in this suite have run.
@BeforeClass
The annotated method will be run only once before the first test method in the current class is invoked.
@AfterClass
The annotated method will be run only once after all the test methods in the current class have been run.
@BeforeTest
The annotated method will be run before any test method belong ing to the classes inside the tag is run.
@AfterTest
The annotated method will be run after all the test methods belong ing to the classes inside the tag have run.
@BeforeGroups
The list of g roups that this config uration method will run before. T his method is g uaranteed to run shortly before the first test method that belong s to any of these g roups is invoked.
@AfterGroups
The list of g roups that this config uration method will run after. T his method is g uaranteed to run shortly after the last test method that belong s to any of these g roups is invoked.
@BeforeMethod
The annotated method will be run before each test method.
@AfterMethod
The annotated method will be run after each test method.
@DataProvider
Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assig ned the parameter list of the test method. T he @T est method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.
@Factory
Marks a method as a factory that returns objects that will be used by T estNG as Test classes. T he method must return Object[].
@Listeners
Defines listeners on a test class.
@Parameters
Describes how to pass parameters to a @T est method.
@Test
Marks a class or a method as part of the test.
 
 Note: alwaysRun, If set to true, this test method will always be run even if it depends on a method that failed.
 
 public class AnnotationsTest {

    @BeforeSuite(alwaysRun = true)
    public static void beforeSuite() {
        System.out.println("@BeforeSuite");
    }

    @BeforeTest(alwaysRun = true)
    public static void beforeTest() {
        System.out.println("@BeforeTest");
    }
  
    @BeforeClass(alwaysRun = true)
    public static void beforeClass() {
        System.out.println("@BeforeClass");
    } 

    @BeforeMethod(alwaysRun = true)
    public static void beforeMethod() {
        System.out.println("@BeforeMethod");
    }

      @Test
    public void test() {
        System.out.println("Test");
    }

    @Test
    public void test2() {
        System.out.println("Test2");
    }

    @AfterMethod(alwaysRun = true)
    public static void afterMethod() {
        System.out.println("@AfterMethod");
    }

     @AfterClass(alwaysRun = true)
    public static void afterClass() {
        System.out.println("@AfterClass");
    }

     @AfterTest(alwaysRun = true)
    public static void afterTest() {
        System.out.println("@AfterTest");
    }  

    @AfterSuite(alwaysRun = true)
    public static void afterSuite() {
        System.out.println("@AfterSuite");
    }
    
}

Output:
@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
Test  
@AfterMethod
@BeforeMethod
Test2  
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite