Friday, 15 August 2014

Array Functions in QTP


1)Array() in QTP


-> The Array function returns a  variant containing an array.

-> The first element of array index is zero.



Syntax

Array(arglist)


Here,

arglist - Required. Its contains value seperated by comma. and values represented as array.


Example:


a=array(3,5,8)
msgbox a(1)


Here the values are,

a(0)=3
a(1)=5
a(2)=8




2) Filter() in QTP

-> Filter function used to create another array variable from another array variable by using some filter creteria.


Syntex:

Filter(Source_arrayvariable,value[,include[,compare]])


Here,


Source_arrayvariable = Required. one dimensional array. This is source string

value = Required. Used for search string in Source_arrayvariable. Its case- sensitive.

include = Optional, Boolean value
 True = Default. Return String as per matched with above given value.
 False = Return string that is not matched as per above given value.
Compare = Optional. Specifies the string comparison to use.
0 = vbBinaryCompare - Perform a binary comparison
1 = vbTextCompare - Perform a textual comparison



Return Values:

Return new array with values from Source_arrayvariable as per the filter creteria.



Example:


a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
b=filter(A,"Sun",true)
For each str  In b
print str
Next



O/P
Sunday




3) IsArray() function in QTP

-> IsArray() returns boolean value and its indicates that given variable is array variable or normal variable.

->  If the variable is an array, it returns True, otherwise, it returns False.


Syntex :

IsArray(variable)

Variable : Required. Any variable


Return type:

True : If the variable is an array
False : If the variable is NOT an array,


Example:

a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
print msgbox(IsArray(A))


O/P

TRUE



4) Join() funtion in QTP

The Join() function used to join all elements from array.


Syntex:

Join(Array_Variable[,delimiter])

Here,

Array_Variable = Required. one dimensional array variable name.
delimiter = optional, used to add delemiter char with end of all element(Sub String) in given array variable.


Return Types:

Its return String which contains all number of element (substrings) in an array.


Example :

a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
print join(a,"#")

o/p

Sunday#Monday#Tuesday#Wednesday#Thursday#Friday#Saturday



5) Split Function in QTP


Split function used to zero based, one dimensional array that contains specified number of sub string.


Syntax:

Split(expression[,delimiter[,count[,compare]]])

Here,


6) LBound Function in QTP

Returns the smallest subscript for the indicated dimension of an array

LBound(arrayname[,dimension])





7) UBound Function in QTP

Returns the largest subscript for the indicated dimension of an array


UBound(arrayname[,dimension])

String Function in QTP



1) Instr function in QTP

Instr returns first occurance of the string1 with in another string2.

Syntex:

Instr([start,] String1,String2, [compare])

Here,

Start   = optional, Postion of the start search from String1
String1 = Required, This is main String.
String2 = Required, This is sub String to be search in String2
Compare = Optional, Specifies the string comparison to use. Default is 0

 Can have one of the following values:

 0 = vbBinaryCompare - Perform a binary comparison
     1 = vbTextCompare - Perform a textual comparison



Return Values :

0      -> If String1 is ""
0       ->  If String2 is not found
0           -> if start > len(String1)
Null       -> If String1 is Null
Null       -> If String2 is Null
Start val   -> If Strin2 is ""
position val-> If string2 is found within string1



Example :

Instr(1,"The QTP Tutorial","T")

o/p 1


2) InStrRev function in QTP

InstrRev returns first occurance of the String1 with in another string. The search begin starts from end of the string. But position returned counts from the beginning of the string.


Syntex:

InStrRev(String1,String2[,start],[compare])

Here,

String1 = Required, This is main String.
String2 = Required, This is sub String to be search in String2
Start   = Optional. Specifies the starting position for each search. The search begins at the last character position by default (-1)
Compare = Optional. Specifies the string comparison to use. Default is 0

 Can have one of the following values:

 0 = vbBinaryCompare - Perform a binary comparison
     1 = vbTextCompare - Perform a textual comparison



Return Values :

0      -> If String1 is ""
0       ->  If String2 is not found
0           -> if start > len(String1)
Null       -> If String1 is Null
Null       -> If String2 is Null
Start val   -> If Strin2 is ""
position val-> If string2 is found within string1


Example :

Instr(1,"The QTP Tutorial","a")

o/p 11



3) Lcase function in QTP

Converts specified string to lower case.

Syntex:

Lcase(String)

Here,

String = Required, string to be change lower case.



4) Ucase function in QTP

Converts specified string to upper case.

Syntex:

Ucase(String)

Here,

String = Required, string to be change upper case.







5) Left function in qtp

Left function used to returns number of characters from left side of the string.

Syntex:

Left(string1,length)

Here,

String1 = Required, Main string used to returns character from.
lenght  = Required, Specifies how many characters to return from left side of the string.


Return values

if length = 0      -> Returns Empty String ""
if length >= len(String) -> Returns full String
if lenght < len(string)    -> Returns number of character from left side


Example :

left("This is QTP tutorial",11)

o/p "This is QTP"





6) Right function in qtp

Right function used to returns number of characters from right side of the string.

Syntex:

Right(string1,length)

Here,

String1 = Required, Main string used to returns character from.
length  = Required, Specifies how many characters to return from right side of the string.


Return values

if length = 0      -> Returns Empty String ""
if length >= len(String) -> Returns full String
if lenght < len(string)    -> Returns number of character from right side


Example :

left("This is QTP tutorial",11)

o/p "TP tutorial"




7) Len Function in QTP

Len function used to returns the number of characters from given string.

Syntex:

Len(String)

Here,

String = Required

Example:

len("qtp")

o/p 3



8) Ltrim function in QTP

Ltrim Function used to remove spaces from left side.

Syntex:

Ltrim(String)

Here,

String = Required

Example:

len("qtp  ")

o/p qtp


9) Ltrim function in QTP

Rtrim Function used to remove spaces from right side.

Syntex:

Rtrim(String)

Here,

String = Required

Example:

len("  qtp")

o/p qtp



10) Trim function in QTP

Trim Function used to remove spaces from both side.

Syntex:

Ltrim(String)

Here,

String = Required

Example:

len("  qtp  ")

o/p qtp   



11) Mid function in QTP

Mid function returns number of characters from given string

Syntax

Mid(string,start[,length])

Here,

String = Required, The string which char can be returned
Start  = Required, Specifies the starting position.
lenght = optional, the number of characters to be returned.

Return values,

If start > len(String) = Return empty string ("")

Ex:

mid("This is QTP Tutorial",1,4)

o/p  This




12) Replace function in QTP

Replace the specified number of string with in one another.

Syntex:

Replace(String,Find,ReplaceWith[,Start[,Count[,compare)

Here,

String      = Required. Main String used to replace
Find    = Required, THis is String which is find in the main String for replacement
ReplaceWith = Required, Substring which is going to replace in main string.
Start       = Optional, From which postion from main string going to search and replace. Default is 1. All characters before the start position will be removed.
count       = Optional, number of replacement in Main String. Default value is -1, which means make all possible substitutions
compare       = Optional, Specifies the string comparison to use. Default is 0

 Can have one of the following values:
 0 = vbBinaryCompare - Perform a binary comparison
        1 = vbTextCompare - Perform a textual comparison   



Example :

Replace("This is a beautiful day!","i","##",2,2)

o/p  "h##s ##s a beautiful day!"




13) Space function in QTP

The Space function returns a string that consists of a specified number of spaces.


Syntax

Space(number)


Here,

number    = Required. The number of spaces you want in the string


Example

space(3)

o/p "   "



14) Strcomp function in QTP

The Strcomp function used to comapare the two string and return the values as per the result of comparison.

Syntax:

StrComp(string1,string2[,compare])

String1 = Required.
String2 = Required.
compare = Optional, Specifies the string comparison to use. Default is 0

 Can have one of the following values:
 0 = vbBinaryCompare - Perform a binary comparison
        1 = vbTextCompare - Perform a textual comparison


Return values,

-1    = if string1 < string2
0    = if string1 = string2
1    = if string1 > string2
Null    = if string1 or string2 is Null





15) String function in QTP

The String function returns the string with contains given number of continuous character.

Syntex:

String(Number,character)


Here,

number     = Required. The length of the returned string
character = Required. The character that will be repeated


Return values,

if character = "more than one letter"  -> It consists first letter of that string.

Example:

String(4,H)   ->  O/P  HHHH
String(4,"

How to use FOR EACH loop in QTP



-> FOR EACH loop used to execute every single element or item in a group.

-> Normally its used to like

1) Every single element in an Array
2) Every single files in a folder
3) Every character in a String

in these type of situation we can use FOR EACH loop.

Syntex

For Each [Item] In [Group]
   [loopBody]
Next [Item]


Example :

a=Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")

For each str In a
print str
Next

output :

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday



From above example, we print the every element in array.


GetAttribute Method in Selenium





-> This method used to Gets the value of the specified attribute for this Web element.

Syntex:

WebElement.GetAttribute("Attribute_Name")

o/p

Returns the value of the Attribute name.



Example:



Source :

<a id="link1" href="http:gmail.com">
<span lang="LBLSHOVIDEOS">Selenium</span></a>


Script :


String attr1=driver1.findElement(By.linkText("Selenium")).getAttribute("id");
System.out.println("Attribute ID Value="+attr1);

String attr2=driver1.findElement(By.linkText("Selenium")).getAttribute("href");
System.out.println("Attribute HREF Value="+attr2);



O/P :

Attribute ID Value= Link1

Attribute HREF Value=http:gmail.com

Data driven testing in TestNG (Using @DataProvider annotaion)





-> @DataProvider annotations in TestNG is important for data driven framework in selenium.

-> @DataProvider Annotation of testng framework provides us a facility of storing and preparing data set In method.

-> Task for @DataProvider Annotation is supplying data for test method. That means we can configure data with in the @DataProvider annotations and use those data inside the @Test methods.

-> @dataprovider method should return an Object[][] with data.

-> we have to create two dimensional array in @DataProvider annotation data to stored the data.



Example:


Bellow given example will retrieve userid and password one by one from @DataProvider annotated method and will feed them In LogIn_Test(String Usedid, String Pass) one by one. Run this example In your eclipse and observe result.



public class Sample_Login {

 WebDriver driver = new FirefoxDriver();


 @BeforeTest
    public void setup() throws Exception {
         driver.manage().window().maximize();
         driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
         driver.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
    }


  @AfterTest
 public void tearDown() throws Exception {
   driver.quit();
     }


 //This method will return two dimensional array.
 //This method behaves as data provider for LogIn_Test method.

 @DataProvider

 public Object[][] LoginCredentials(){

  //Created two dimensional array with 4 rows and 2 columns.
  //4 rows represents test has to run 4 times.
  //2 columns represents 2 data parameters.

 Object[][] Cred = new Object[4][2];

  Cred[0][0] = "UserId1";
  Cred[0][1] = "Pass1";

  Cred[1][0] = "UserId2";
  Cred[1][1] = "Pass2";

  Cred[2][0] = "UserId3";
  Cred[2][1] = "Pass3";

  Cred[3][0] = "UserId4";
  Cred[3][1] = "Pass4";
  return Cred; //Returned Cred
 }



 //Give data provider method name as data provider.
 //Passed 2 string parameters as LoginCredentials() returns 2 parameters In object.

 @Test(dataProvider="LoginCredentials")

 public void LogIn_Test(String Usedid, String Pass){
   driver.findElement(By.xpath("//input[@name='userid']")).clear();
   driver.findElement(By.xpath("//input[@name='pswrd']")).clear();
   driver.findElement(By.xpath("//input[@name='userid']")).sendKeys(Usedid);
   driver.findElement(By.xpath("//input[@name='pswrd']")).sendKeys(Pass);
   driver.findElement(By.xpath("//input[@value='Login']")).click();
   String alrt = driver.switchTo().alert().getText();
   driver.switchTo().alert().accept();
   System.out.println(alrt);
  }
}




testng.xml file to run this example Is as bellow.


<suite name="Simple Suite">
 <test name="Simple Skip Test">
  <classes>
   <class name = "Testng_Pack.Sample_Login"/>
  </classes>
 </test>
</suite>




After run the above code, the user id and password entered one by one in above URL.

Selenium WebDriver Parallel Tests Execution Using TestNG - @Parameters




-> Browser compatibility testing Is most Important thing for any web application and generally you have to perform browser compatibility testing before 1 or 2 days of final release of application. In such a sort time period, you have to verify each Important functionality In every browsers suggested by client.


-> If you will go for running your all webdriver tests In each browsers one by one then It will take too much time to complete your test and you may not complete It before release.

-> In such situation, Running your tests In all required browsers at same time will helps you to save your time efforts.

-> The above situation solved in selenium by using @Parameters annotation in TestNG framework.



Parallelism In TestNG


We can configure our TestNG.xml file in such a way to run our test suite or tests or methods in seperate browsers Is known as parallelism In TestNG.


ParellelTestng.java


package TestNG_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestNG_Test1 {

 private  WebDriver driver1=null;

  @BeforeClass
  @Parameters ({"browser"})

  public void setup(String browser)
 {
   if (browser.equals("FFX"))
  {
     System.out.println("Test Starts Running In Firefox Browser.");
     driver1 = new FirefoxDriver(); 
    }
  else if (browser.equals("CRM"))
  {
     System.out.println("Test Starts Running In Google chrome.");
     System.setProperty("webdriver.chrome.driver",  "D:\\chromedriver_win32_2.3\\chromedriver.exe");
     driver1 = new ChromeDriver(); 
   }
   driver1.manage().window().maximize();
   driver1.get("http://only-testing-blog.blogspot.in/2014/05/login.html");
  }


 @AfterClass
 public void closebrowser()
 {
    driver1.quit();
 }


 @Test
 public void MethodOne() {

  String a= "Selenium";
  if(a.equals("Selenium")
   throw new SkipException("Skipped");

  String title = driver1.getTitle();
  System.out.println("title"+title);   
 }



 @Test
 public void MethodTwo() {
  String title = driver1.getTitle();
  System.out.println("title"+title);   
 }


}




testng.xml

<suite name="webDriver" parallel="tests">

 <test name="Test In FireFox" >
    <parameter name="browser" value="FFX" />
    <classes>
      <class name="Testng_Pack.Test_Parallel" />
    </classes>
  </test>

   <test name="Test In Google Chrome" >
    <parameter name="browser" value="CRM"></parameter>
    <classes>
      <class name="Testng_Pack.Test_Parallel"></class>
    </classes>
  </test>

</suite>




From above example we can run same test in both Chrome and FireFox at same time.

From above Testng.xml file

-> parallel="tests" which inside <suite> tag will instruct TestNG to consider method of each <test> tag as seperate Thread. that Means If you wants to run your test In 2 different browsers then you need to create two <test> blocks for each browser Inside testng.xml file.

-> Inside each <test> tag block, define one more tag "parameter" with same name(In both <test> block) but with different values.Its used to pass in ParellelTestng.java method.



From ParellelTestng.java

-> Here we are used @Parameters annotation to pass parameter in method.Values of this parameter will be feed by testng.xml file.

-> If condition will check that value to decide which driver to use for test. This way, example testng.xml file will feed two values(FFX and CRM) In parameter so It will open Firefox and Google chrome browsers and run test In both browsers

How To Skip WebDriver Test In TestNG





We can skip the execution from perticular test by using throw new SkipException() exception. THis is TestNG exception.

Sometimes you need to check some condition like If some condition match then skip test else perform some action In your webdriver test. In this kind of situation, you can use SkipException() exception.


Consider below example




package TestNG_Package;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestNG_Test1 {
WebDriver driver1=new FirefoxDriver();
@BeforeMethod
public void OpenBrowser(){
driver1.get("http://google.com");
driver1.manage().window().maximize();
}
@AfterMethod
public void CloseBrowser(){
driver1.quit();
}
@Test
public void MethodOne() {

String a= "Selenium";
if(a.equals("Selenium")
throw new SkipException("Skipped");

String title = driver1.getTitle();
System.out.println("title"+title);   
}



@Test
public void MethodTwo() {
String title = driver1.getTitle();
System.out.println("title"+title);   
}


}



o/p

MethodOne Skipped due to SkipException()
MethodTwo executed


From above example if execution throw SkipExeption() means the rest of the commands inside the method wont get executed. Its skipped from current method and control goes to next method.