Friday, June 5, 2020

Selenium Coding Challenge FAQs


IMPORTANT: DO NOT search the answer online or ask somebody else to help you

  1. Create a script using Selenium Web Driver that perform the following steps –
Note: Use browser of your choice (IE, Chrome and Firefox)
  1. Open “testing.com” homepage.
  2. Verify the title of homepage
  3. Comparing and print out the result of comparison
  4. Closing the Browser Session
Selenium Code :
Method I : I am using If Statement :
------------------------------------
package OptumUHGtest;

import java.util.concurrent.TimeUnit;

import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

public static void main(String[] args) {


// System Property for Chrome Driver
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
// Instantiate a ChromeDriver class.
WebDriver driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.navigate().to("https://www.Testing.com");
String actualTitle = driver.getTitle();
//Maximize the browser
driver.manage().window().maximize();
String expectedTitle = "Health Testing and Screening Resources";
if(actualTitle.equalsIgnoreCase(expectedTitle))
System.out.println("Title Matched");
else
System.out.println("Title Didn't Match");
//Driver.close() is just closing one tab of the browser.
driver.close();
//Driver.quit() is closing all the browsers and also ending the WebDriver session
driver.quit();

}

}




RESULT : After executing the codes : You can see the result in the console :
--------
Title Matched




Method II : I am Assert Command :
------------------------------------
package OptumUHGtest;


import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class Test {

public static void main(String[] args) {


// System Property for Chrome Driver
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
// Instantiate a ChromeDriver class.
WebDriver driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.navigate().to("https://www.Testing.com");
String actualTitle = driver.getTitle();
//Maximize the browser
driver.manage().window().maximize();
String expectedTitle = "Health Testing and Screening Resources";
Assert.assertEquals("Condition true", actualTitle, expectedTitle);
//Driver.close() is just closing one tab of the browser.
driver.close();
//Driver.quit() is closing all the browsers and also ending the WebDriver session
driver.quit();

}

}


RESULT : After executing the codes : You can see the result in the console :
--------
Title Matched


  1. What is the difference between Absolute Path and Relative Path in Selenium?
Note: Consider automating a web page using Selenium, please provide sample code to differentiate the two.
Absolute Xpath: It uses Complete path from the Root Element to the desire element.
Relative Xpath: You can simply start by referencing the element you want and go from there.
Always Relative Xpaths are preferred as they are not the complete paths from the Root element. (//html//body) ..
Beacuse in future any of the webelement when added/Removed then Absolute Xpath changes. So Always use Relative Xpaths in your Automation.
Selenium Code :
// Absolute Path starts from root path, Relative Path starts from current path
//Selenium WebDriver - Absolute and Relative Path Examples
//Example Absolute and Relative Paths for Selenium WebDriver


import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;


public class AbsoluteRelativePaths {


@Test
public void absolutePath() throws InterruptedException {


System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("E:\\Selenium\\absolute.html");


// Absolute Path starts from root path
WebElement link1 = driver.findElement(By.xpath("/html/body/li[@id='test']/a"));


// Relative Path starts from current path
WebElement link2 = driver.findElement(By.xpath(".//*[@id='test']/a"));


driver.quit();


}


}
  1. List some scenarios which cannot be automated using Selenium WebDriver?
  • We can not automate desktop Application. Selenium is only for Web Based application.
    Finding elements is only possible with id, css, xpath, name, partial link etc. ...With Selenium webdriver,
  • Mobile testing is not possible. ...
  • Captcha cannot be automated using selenium.
  • Bitmap comparison is not possible using Selenium WebDriver.
  • Automating Captcha is not possible using Selenium WebDriver.
  • We can not read bar code using Selenium WebDriver.
  • We can not automate OTP submission.
  • We can not automate Video streaming scenarios: More often that not, Selenium won’t be able to recognise video controls. JavaScript Executor and flex-ui-selenium will work to some extent, but they are not entirely reliable.
  1. Please review the following code and answer what it refers to in Selenium?
Code:
try {
driver.get("www.testing.com");
}catch(Exception e){
System.out.println(e.getMessage());
}


ANSWER:
// Try-catch: This method can catch Exceptions, which uses a combination of the try and catch keywords.
// Try command indicates the start of the block, and Catch is placed at the end of the try block,
// which helps to resolve the Exception.
try {
//launching URL using driver.get()
driver.get("www.testing.com");
}catch(Exception e){
// getMessage(): Helps to displays the description of the Exception.
System.out.println(e.getMessage());
}

  1. What is a requirements traceability matrix (RTM) and what are its advantages?
Given the following requirements and test cases, Please come up with a RTM.
Requirements:
R1 - A user can log in to the system
R2 - A user can send messages to other users
R3 - A user can open the profile page
R4 - A user can edit sent messages
R5 - A user can have a profile picture
Test cases :
TC1 - Verify that a user is able to log in
TC2 - Verify that a user can open the profile page and edit the profile picture
TC3 - Verify that a user can send and edit messages


ANSWER :
Requirements traceability matrix (RTM):
100% test coverage; It allows to identify the missing functionality easily;
It allows to identify the test cases which needs to be updated in case of change in requirement;
It is easy to track the overall test execution status
Advantage as we update the RTM, we can know the coverage status accuratly any time
Let us see how our RTM coverage; Here 100% Test has been cover. TC1 Covers R1, TC2 Covers R3,R5 and TC3 covers R2 and R4.

  1. How will you automate basic “login” functionality of a web application? Please list down some high level test cases as well as your test plan to automate them.


1. We can handle directly in the main method ( refer to the below and other login code hereby.)
driver.get (“https://www.OptumUHG.com”)
driver.find_element_by_id(“email”).send_keys(‘MyOptumUHGID@gmail.com’)
driver.find_element_by_id(“pass”).send_keys(“TempPassword1”)
driver.find_element_by_id(“loginbutton”).click()


2. We can call the respective methods in the Optum().
public class Optum {


static WebDriver driver= new FirefoxDriver();


@Test
public void test() {
//Method1 for Opening Browser.
openBrowser();
// Method2 for Login
LoginElement();
}


public static void openBrowser(){
driver.get (“https://www.OptumUHG.com”)
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}


public static void LoginElement(){


driver.find_element_by_id(“email”).send_keys(‘MyOptumUHGID@gmail.com’)
driver.find_element_by_id(“pass”).send_keys(“TempPassword1”)
driver.find_element_by_id(“loginbutton”).click()


}


}

  1. What are the main attributes of test automation, List some of them?


1.Maintainability - the effort needed to update the test automation suites for each new release
2.Reliability : The accuracy and repeatability of the test automation
3.Flexibility : The ease of working with all the different kinds of automation test ware
4.Efficiency : The total cost related to the effort needed for the automation
5.Portability : The ability of the automated test to run on different environments
6.Robustness : The effectiveness of automation on an unstable or rapidly changing system
7.Usability : The xtent to which automation can be used by different types of users
8.Return on Investement : High automation ROI
9.Test data: The ability to create test data is functionality, but how easy and fast we can do it is a quality attribute.
10.Integration: It should be easy and fast to integrate the test automation framework with other tools.

  1. SQL query test:
Device:
Device_Id
Device_Name
Device_Cost
Location_Id
1
Device1
100
1
2
Device2
200
null
3
Device3
300
2
4
Device4
400
null

Asset:
Asset_Id
Computer_InfoAsset
_Description
Device_Id
1
A_Asset1
Good
1
2
B_Asset1
Ok
4
3
A_Asset2
Bad
2
4
B_Asset2
Good
1
5
A_Asset3
Bad
1
6
B_Asset3
Bad
3
7
A_Asset4
Bad
2
8
B_Asset4
Ok
3

Location:
Location_Id
Location_Code
Location_State
Location_City
1
Code1
CT
City1
2
Code2
OH
City2

Write a query using above tables to retrieve “Device Name”, “Computer Info” and “Location State” on the condition: “Computer_Info” starts with “A” or Location_State is CT or no location.

ANSWER :
SELECT Device.Device_Id, Asset.Computer_InfoAsset, Asset._Description, Location.Location_City
FROM ((Device
INNER JOIN Asset ON Device.Device_Id = Asset.Device_Id)
INNER JOIN Location ON Device.Location_Id = Location.Location_Id) Where Asset.Location_City = "CT"


RESULT :
--------
Number of Records: 3

Device_Id Computer_InfoAsset _Description Location_City
1 A_Asset1 Good CT
1 B_Asset2 Good CT
1 A_Asset3 Good CT

Thank you and Good Luck!!


Tuesday, June 2, 2020

UFT and VB Script Interview FAQs

Interview Questions : (3i infotech / Cigniti):
------------------------------------------------------
Please find some points to prepare for your interview tomorrow apart from regular testing concepts.
1.VB script
2.QTP/UFT
3.Logical Thinking
4.Object Identification
5.HTML DOM
6.Exposure on custom add-in designing
7.Extensibility Add-in manager
8.Framework Design

UFT and VB script interview FAQs:
--------------------------------------------

Q1. How to find the length of string in QTP?

Answer -You can find the length of the string using one vb script function called len.

Suppose you want to find the length of "salunke" then you will have the below statement which will print the length of string .

print len("salunke")


Q2. How to find the current system time in QTP?

Answer - You can find the current system time using Time function in vbscript.

Print time


Q3. How to remove all spaces from given string in QTP?

Answer - We can use replace function in vbscript to remove all spaces in string.

e.g. newstring = replace(stringwithspaces," ","")


Q4. How to find the modulus of a number in QTP?

Answer - We can find the modulus of given number using MOD operator.

a = 10 mod 5

print a


Q5. How to find the size of array in QTP?

Answer - To find the size of array, we can use ubound function in QTP.

print ubound(arr) - 'prints upper bound of array.


Q6. What is the difference between byref and byval in QTP?

Answer - You can pass the parameters to function or procedure using byref or byval method.

byref will pass the address of variable but
byval will pass the copy of variable.
So when you want the passed value to change, you can pass the value using byref method.
Otherwise you can pass it using byval method.

'Sample 2 ByRef
'-------------------
' Argument is passed by Reference - myname1 can be modified.
Function learnqtp1( ByRef var1)

myname1= "Manick1"
msgbox var1
msgbox myname1

End Function

myname1= "Sundar1"

call learnqtp1 (myname1)

'Sample 2 ByVal
'-------------------
'Argument is passed by Value -  myname can NOT be modified.
Function learnqtp( ByVal var)

myname= "Manick12"
msgbox var
msgbox myname

End Function

myname= "Sundar12"

call learnqtp (myname)



Q7. How to find the difference between 2 dates in QTP?

Answer - You can find the difference between 2 dates using datediff function. You can get the difference in terms of minutes, seconds, hours, months or years.


Q8. How to generate the random number in given range in QTP?

Answer:
Min = 1
Max = 10
Randomize
RandomNumber = (Int((max-min+1)*Rnd+min))


Q 9. How to create an array of dictionaries in QTP?

Answer - We can create the array of dictionary like how we create array of scalar variables.
Syntax is shown below –
'Declare Array with 5 elements
Dim myArray(5)
'Make first element in array as a dictionary object
Set myArray(0) = createobject("scripting.dictionary")
'Once we have a dictionary object, We can use its methods like add, remove, removeall etc
myArray(0).Add"mykey","myvalue"
'display item value of mykey in dictionary myArray(0)
print myArray(0)("mykey")
myArray(0).removeall


Q 10. How Can we store array variable in dictionary in QTP?

Answer -
Dim a
a = array(2,3,4,5)
Set d = createobject("Scripting.Dictionary")
d.Add "mykey", a
print d("mykey")(0)
Q 11. What is win32 API and how to use it in QTP?
Answer -
win32 API is an API that can be used to perform different administrative tasks. It has many WIN32 classes like Win32_Process etc.

Below Example used Win32 API in QTP to close the process by its name.

'Get the WMI object
Set WMI = GetObject("winmgmts:\\localhost\root\cimv2")
'Get collection of processes for with name pname
Set allp = WMI.ExecQuery("Select * from Win32_Process Where Name = '" & pname & "'")
'Loop through each process and terminate it
For Each p in allp
p.Terminate()
Next
This is how we can use win32 API in QTP.

Here is the list of more QTP-Vbscript Interview Questions.

Difference between Executefile and execute in QTP
How to convert data types in qtp
How to send mail from outlook in qtp
How to fetch data from database in QTP
How to get xml node value in QTP`
How to Find Test Execution Time in QTP
How to find screen resolution in QTP
How to define Array in QTP
How to convert date format in qtp

Refer to : http://qtp-interview-questions.blogspot.com/p/qtp-vbscript-interview-questions-and.html

HTML DOM :
----------
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the
document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.

Applications : Web browsers:
----------------------------
To render a document such as a HTML page, most web browsers use an internal model similar to the DOM. The nodes of every document are organized
in a tree structure, called the DOM tree, with the topmost node named as "Document object". When an HTML page is rendered in browsers,
the browser downloads the HTML into local memory and automatically parses it to display the page on screen.

My Youtube Reference : https://youtu.be/ZsY6yp0zoQs ( How to automate HTML DOM Objects and Normal objects Scripting with Micro Focus UFT / QTP )

* 7 Types of Identification of an Object in QTP/UFT :
------------------------------------------------------
 1) Normal Identification
 2) Smart Identification
 3) Ordinal Identification  ( 3 Type Index based , Location based and Creation Time - value CreationTime=0 )
 4) Visual Based Identification
 5) Object Identification based on CSS XPath
 6) Image Based Identification
 7) VRI- Visual relation Identifier

* What is XPath?
----------------

  // Absolute Path starts from root path ( Full path from the root)
  WebElement link1 = driver.findElement(By.xpath("/html/body/li[@id='test']/a"));

  // Relative Path starts from current path
  WebElement link2 = driver.findElement(By.xpath(".//*[@id='test']/a"));

XPath is a language used to get the information from an xml document.

XPath uses path expressions to navigate and identify the element in the xml document

The advantage of using XPath is to identify any object in the application easily without wasting much time looking for combination of properties to make it unique.
 If you are working on a commercial application, you would see code like this.
<form>
<label for="male">Male</label>
<input type="radio" name="sex" id="male"/><br/>
<label for="female">Female</label>
5.<input type="radio" name="sex" id="female"/>
</form>

  *i.To identify the first input box copy and paste the following syntax into the Value edit box:
/html/body/form/input[1]

  *ii. To identify the second input box copy and paste the following syntax into the Value edit box:
/html/body/form/input[2]

* What is import \ export ( Excel sheet)
----------------------------------------
 'Datatable.Imxport "C:\Users\manicm\Downloads\work\Data\" & Environment ("TestName") &".xls"
 'Datatable.Export "C:\Users\manicm\Downloads\work\Data\" & Environment ("TestName") &".xls"


* I will show you how to locate elements in UFT using HTML DOM and also by Normal objects?
------------------------------------------------------------------------------------------
'
'-------------------------------------
'*** UFT Script : HTML DOM    ***
'*** Object Native Properties ***
'---------------------------------------

Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").Sync

'''' WebEdit - Search Box ''''
Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").object.getElementsByName("field-keywords").item(0).Value="Samsung Galaxy"

'''' WebButton  - Search Box button ''''
Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").object.getElementsByClassName("nav-input").item(0).click


'Reference : https://www.youtube.com/watch?v=FGYrQHtABrk

'----------------------------------
'****** Normal UFT Scripting: *****
'----------------------------------
'
VarSearchPhone="Samsung Galaxy"
Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").Sync
'''' WebEdit - Search Box ''''
Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").WebEdit("field-keywords").Set VarSearchPhone 
'''' WebButton  - Search Box button ''''
Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").WebButton("Go").Click


* How to automate or Identify the custom add-in designing objects?:
-------------------------------------------------------------------
WIP

* 1. Descriptive Code:
----------------------
Browser("title:=Google").Page("title:=Google").WebEdit("name:=q","type:=text").Set "google"

* 2. Create Object:
-------------------
Set Desc = Description.Create()
Desc("micclass").Value = "WebEdit"
Set Edits = Browser("Google Sets").Page("Google Sets").ChildObjects(Desc)

MsgBox "Number of Edits: " & Edits.Count


* QTP - Quick trick if QTP/UFT is not recognizing objects in your application:
------------------------------------------------------------------------------
For .NET application:
1. Now Spy will show as Winows and Winobject for the login Screen ( Username and Password )
2. i.   Click on record button
   ii.  Select the <Record and run test on any open Window-based application
   iii. Now recognize the right object as scripts as below:
        '''' WebEdit - Search Box ''''
SwftWindow("Amazon.com: Online Shopping").SwfEdit("field-keywords").Set VarSearchPhone 
'''' WebButton  - Search Box button ''''
SwftWindow("Amazon.com: Online Shopping").SwfButton("Go").Click
 
Also Reference to: https://www.youtube.com/watch?v=MkkVOWCip_E

* UFT Automation Object Model (AOM):
------------------------------------
Save the below Notepad++ sciprt as "CignitiExecute.vbs" in your desktop

Dim MsUftObj
Set MsUftObj = CreateObject("QuickTest.Application")
MsUftObj.Launch
MsUftObj.Visible = True

MsUftObj.Open("C:\Users\SunNik\Cigniti_AUT\Test1")
MsUftObj.Test.Run
MsUftObj.Test.Close
MsUftObj.quit
Set MsUftObj=Nothing

* Douple Click the "CignitiExecute.vbs" in your desktop Will run the below script
after Launching the MsUFT :
'--------------------
'Cigniti Test1 Script
'--------------------
Dim MsUftTstObj
msgbox "Welcome to Cigniti"
Wait(3)
Set MsUftTstObj=CreateObject("wscript.shell")
MsUftTstObj.SendKeys "{enter}"
Set MsUftTstObj.Nothing

Also Reference to: https://www.youtube.com/watch?v=uyhqqPCvcjQ

* How to load a object repository in QTP during runtime?
--------------------------------------------------------
we can add object repository at runtime
Two ways are there u can add

1. when u write below syntax in Action1
Syntax: RepositoriesCollection.Add(Path)
Ex: RepositoriesCollection.Add(E:\OR\ObjRes.tsr)

if write in Action1 it will automatically add the Object
Respository to the Action1
(i.e Edit Menu-->Action-->Action Properties-->Associate
Repository tab) at runtime.

no need to add the object repository before running.

2. Add the object repository at runtime by using AOM
(Automated Object Model)

Ex:
Dim qtAppn
Dim qtObjRes

Set qtAppn = CreateObject("QuickTest.Application")
qtAppn.Launch
qtAppn.Visible = True

qtApp.Open "E:\Test\Test2", False, False
Set qtObjRes = qtApp.Test.Actions
("Login").ObjectRepositories

qtObjRes.Add "E:\OR\ObjRes.tsr", 1

The above example Add the Object Repository(ObjRes.tsr) to
the "Login" action in Test2.

Here also no need to add the object repository in Test2.


* UFT Test object Vs Run-Time object:
-------------------------------------
Test object in general its the object repository of the object.
The object properties are stored with in UFT is called Test Object.

'Sample Flight Script:
'---------------------
Dialog("Login").WinEdit("Agent Name:").Set "Test"
Dialog("Login").WinEdit("Agent Name:").Type micTab'
Dialog("Login").Move 657,504
Dialog("Login").WinEdit("Password:").SetSecure "5786jhjkhjkdsaiw124gqe12321earcdex2424555ffe9"
Dialog("Login").WinButton("OK").Click

Simple to Remember quick TO is Test object and
RO is Run-Time object, the object which appears while run time of the application.

* UFT(QTP) Tutorials -8. GetROProperty vs GetTOProperties vs SetTOProperty with example :
-----------------------------------------------------------------------------------------
Types of objects and important Methods
 > Test Object(TO)
 > Run Time Object(RO)
 > GetTOProperty method
 > SetTOProperty method
 > GetROProperty method

>Test Object(TO): The object which is present in the Object Repository are called Test Object

>Run Time Object(RO): The object which is present in the appliction (AUT : Application under test) are call run time object

 * UFT While executing the script, if the TO equals to RO, then the action is perfomed.

>GetTOProperty method: We are going to get the properties from the object repository
'Script GetTOProperty
''''''Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").link("iphone xs").Click
VarGetTo = Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").link("iphone xs").GetTOProperty("text")
Msgbox VarGetTo

>SetTOProperty method: We are going to check the properties value of the object repository, here the objects
properties are change temporarily and which will not change the Object repository
'Script SetTOProperty
''''''Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").link("iphone xs").Click
Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").link("iphone xs").SetTOProperty "text","Shop Apple"
VarSetTo = Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").link("iphone xs").GetTOProperty("text")
Msgbox VarSetTo
' Now the Run time value will be "Shop Apple"
' The below will click the Shop Apple on the run time.
Browser("Amazon.com: Online Shopping").Page("Amazon.com: Online Shopping").Click


>GetROProperty method: We are going to get the run time properties value from AUT on run time.
' The fare to train Name : NYC's total and Total fare to train Name : NJ's  is different by the Total Fare (eg. $150 and $75)
  ' if you record the object for the total fare amout $150, inside the OR the innertext will have the static value $150 so
    ' delete the innertext it will work for other values, then it will become dynamic.

'Now select the Train NYC and run the below line of script, will pop-up message show $150 now from the AUT.
msgbox = Browser("Welcome to USA Metro").Page("Welcome to USA Metro").WebElement("TotalAmount").GetROProperty("innertext")

'Now select the Train NJ and run the below line of script, will pop-up message show $75 now from the AUT.
msgbox = Browser("Welcome to USA Metro").Page("Welcome to USA Metro").WebElement("TotalAmount").GetROProperty("innertext")


Var = "a1b2cde45"

Retrive numberic from the string form this variable
How to extract a number from alphanumeric text string?
Dim mystring, myLength
mystring = "abhikansh567st1239test"
myLength = Len(mystring)

For i = 1 To myLength
    If Asc(Mid(mystring, i, 1)) <> 32 Then
        If Asc(Mid(mystring, i, 1)) >= 48 And Asc(Mid(mystring, i, 1)) <= 57 Then
            myNumber = myNumber & Mid(mystring, i, 1)
        End If
    Else
        msgbox("no numeric")
    End If
Next
msgbox(myNumber)

* For tests, the definitions in a function library loaded by LoadFunctionLibrary statement are available globally until the end of the run session,

      Whereas the definitions in a file run by ExecuteFile statement are available only within the scope of the action that called the statement

* 4 Different Ways to Associate Function Libraries to your QTP Scripts
-----------------------------------------------------------------------
1) By using ‘File > Settings > Resources > Associate Function Library’ option in QTP.
2) By using Automation Object Model (AOM).
3) By using ExecuteFile method.
4) using LoadFunctionLibrary method.

1. Using ‘File > Settings > Resources > Associate Function Library’ option from the Menu bar:
---------------------------------------------------------------------------------------------
This is the most common method used to associate a function library to a test case. To use this method,
select File > Settings option from the Menu bar. This will display the ‘Test Settings’ window. Click on Resources from the left hand side pane.
From the right hand side pane, click on the ‘+’ button and select the function library that needs to be associated with the test case.

2. Using AOM (Automation Object Model):
---------------------------------------

QTP AOM is a mechanism using which you can control various QTP operations from outside QTP. Using QTP Automation Object Model, you can write a
code which would open a QTP test and associate a function library to that test.

'---------------------------------------
'*Save in notepad "AOMExecuteScript.vbs"
'---------------------------------------
'Open QTP
Set objQTP = CreateObject("QuickTest.Application")
objQTP.Launch
objQTP.Visible = True

'Open a test and associate a function library to the test
objQTP.Open "C:\Automation\SampleTest", False, False
Set objLib = objQTP.Test.Settings.Resources.Libraries

'If the library is not already associated with the test case, associate it..
If objLib.Find("C:\SampleFunctionLibrary.vbs") = -1 Then ' If library is not already added
  objLib.Add "C:\SampleFunctionLibrary.vbs", 1 ' Associate the library to the test case
End

3. Using ExecuteFile Method:
----------------------------
ExecuteFile statement executes all the VBScript statements in a specified file. After the file has been executed, all the functions,
subroutines and other elements from the file (function library) are available to the action as global entities. Simply put,
once the file is executed, its functions can be used by the action. You can use the below mentioned logic to use ExecuteFile method
to associate function libraries to your script.

'---------------------------
'*Inside the action Scripts.
'---------------------------
'Action begins
ExecuteFile "C:\YourFunctionLibrary.vbs"

'Other logic for your action would come here
'.....

4. Using LoadFunctionLibrary Method:
------------------------------------
LoadFunctionLibrary, a new method introduced in QTP 11 allows you to load a function library when a step runs. You can load multiple
function libraries from a single line by using a comma delimiter.

'----------------------------------------
'LoadFunctionLibrary Method in the script
'----------------------------------------
'Some code from the action
'.....

LoadFunctionLibrary "C:\YourFunctionLibrary_1.vbs" 'Associate a single function library
LoadFunctionLibrary "C:\FuncLib_1.vbs", "C:\FuncLib_2.vbs" 'Associate more than 1 function libraries

'Other logic for your action would come here
'.....


* Associating Libraries vs LoadFunctionLibrary vs ExecuteFile in UFT:
---------------------------------------------------------------------
Header
1. Associating Libraries :
2. LoadFunctionLibrary   :
3. ExecuteFile           :

a) ( Below 3 row description should be mapped to the above 3 rows of Header)
User needs to specify the path of library in File->Setings->Resources
Way for loading Libraries in runtime. User needs to use "LoadFunctionLibrary" statement
Way for loading Libraries in runtime. User needs to use "ExecuteFile" statement

b)
Associated Libraries will be loaded in QTP rightaway.
Library will be loaded when QTP executes particular statement
Library will be loaded when QTP executes particular statement

c)
If library not available in specified path, that will be displayed in missing resources
Library will not be displayed in Missing Resources Tab. But displays an error when executing the statement if not available
Library will not be displayed in Missing Resources Tab. But displays an error when executing the statement if not available

d)
The functions which are there in library will be displayed in QTP Intellisence
QTP intellisence doesn't display the function or variable names after using of the "LoadFunctionLibrary" Statement
QTP intellisence doesn't display the function or variable names after using of the "ExecuteFile" Statement

e)
Library will be displayed in Resources TAB
Library File doesn't display in Resources TAB
Library File doesn't display in Resources TAB

f)
Functions which are there in the library will be displayed in Keywords Tab
Functions which are there in the library will not be displayed in Keywords Tab
Functions which are there in the library will not be displayed in Keywords Tab

g)
QTP doesn't understand user defined classes from an associated library
QTP doesn't understand user defined classes from the library which got loaded using "LoadFunctionLibrary" statement
Only way to use classes in QTP. QTP understands userdefined classes when the library got loaded using "ExecuteFile" Statement

h)
Associated Libraries will be opened on pressing of F11(Step InTo) at any functiona call
Associated Libraries will be opened on pressing of F11(Step InTo) at any functiona call
Library will not be opened in debug mode.

i)
Associated libraries are global to the test. All actions can use the functions or variables of associated libraries
It has local scope. Only the action in which this statement got executed can use this.
It has local scope. Only the action in which this statement got executed can use this.

j)
Accepts Relative and absolute Paths
Accepts Relative and absolute Paths
Accepts Relative and absolute Paths


* How to extract a number from alphanumeric text string?

'Var = "a1b2cde45"
'Retrive numberic from the string form this variable
Dim mystring, myLength
mystring = "abhikansh567st1239test"
myLength = Len(mystring)

For i = 1 To myLength
    If Asc(Mid(mystring, i, 1)) <> 32 Then
        If Asc(Mid(mystring, i, 1)) >= 48 And Asc(Mid(mystring, i, 1)) <= 57 Then
            myNumber = myNumber & Mid(mystring, i, 1)
        End If
    Else
        msgbox("no numeric")
    End If
Next
msgbox(myNumber)




* How to find repeated sub string in a given  string using VBScript?
This will give the count of all words in a given substring
* How to find the number of occurrences of a substring within a string vb.net \ VBS


Example 1

Use the InStr() Function to Count Occurrences Within a String

There are many ways to count the occurrences of a string within a text. Here's a simple function that uses the InStr() function:

    Function CountWords(ByVal Text As String, _
        ByVal Word As String, _
        Optional ByVal Compare As VbCompareMethod _
         = vbTextCompare) As Long

    Dim Position As Long
    Dim WordLength As Long
        Position = InStr(1, Text, Word, Compare)
        WordLength = Len(Word)
        Do While Position
            CountWords = CountWords + 1
            Position = InStr(Position + WordLength, Text, _
Word, Compare)
        Loop
    End Function


Example 2
---------

Dim input As String = "hello there. this is a test. hello there hello there!"
    Dim phrase As String = "hello there"
    Dim Occurrences As Integer = 0

    Dim intCursor As Integer = 0
    Do Until intCursor >= input.Length

        Dim strCheckThisString As String = Mid(LCase(input), intCursor + 1, (Len(input) - intCursor))

        Dim intPlaceOfPhrase As Integer = InStr(strCheckThisString, phrase)
        If intPlaceOfPhrase > 0 Then

            Occurrences += 1
            intCursor += (intPlaceOfPhrase + Len(phrase) - 1)

        Else

            intCursor = input.Length

        End If

    Loop

06302020
--------
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the
results of the last operation performed. You have to explicitly check whether the Err. Number
property is non-zero after each operation
------
VBScript Error Handling: VBScript On Error, On Error GoTo 0, On Error Resume Next

Error Handling is a very useful mechanism of programming languages like VBScript in order to deal with the errors and to continue the execution of
the program even after the occurrence of errors inside a program.

Methods of Error Handling in the VBScript
VBScript basically supports 2 main methods to handle errors in the scripts.

They are as follows:

#1) On Error Resume Next
Most of us must have come across this method in some of the other programming languages. This method, as the name itself suggests,
moves the control of the cursor to the next line of the error statement.

Which means, if any runtime error occurs at a particular line in the script then the control will move into the next line of the statement
where the error has occurred.

A Simple Example:

In this case, the division is by 0 and if you do not want your script to get stuck due to this error then you put ‘On Error Resume Next’ at the top
of your script as shown below.

On Error Resume Next (Putting error handling statement)
Dim result
result = 20/0 (Performing division by 0 Scenario)
If result = 0 Then (Checking the value of result variable)
Msgbox “0630Result is 0.”
Else
Msgbox “Result is non-zero.”
End If

#2) Err Object:
This method is basically used to capture the details of the Error. If you want to know more about the Error like Number, description, etc.,
then you can do so by accessing the properties of this Object.

As this is an intrinsic object, there is no need to create an instance of this object to access its properties i.e.
you can use this directly in your scripts.

Following is the list of properties of Err Object with their details:

Number: This will tell you the error number i.e. the integer value of the type of the error occurred.

Description: This will tell you about the error i.e. the description of the error.

Raise: This will let you raise the specific error by mentioning its number.

Clear: This will clear the error i.e. will set to error handler to nothing.

Let’s use the same Example in this case also:

Dim result
result = 20/0 (Performing division by 0 Scenario)
If Err.Number <> 0 Then (Making use of Err Object’s Number property)
Msgbox “Number of the Error and Description is “& Err.Number & “ “ & Err.Description (Give details about the Error)
Err.Clear (Will Clear the Error)
End If

One more to the list:

#3) On Error GoTo 0:

This method is however not an Error Handler mechanism directly because this is used to disable any error handler that is used in the script.
This will set the handler to nothing i.e. no more error handler will be supported in the script.

Refer to : https://www.softwaretestinghelp.com/vbscript-error-handling-tutorial-14/
------

Tuesday, April 14, 2020

REST API

REST API

What is REST?
REST is acronym for REpresentational State Transfer. It is architectural style for distributed hypermedia systems

Like any other architectural style, REST also does have it’s own 6 guiding constraints which must be satisfied if an interface needs to be referred as RESTful.
These principles are listed below.

* Guiding Principles of REST:

Client–server – By separating the user interface concerns from the data storage concerns, we improve the portability of the user interface across multiple
platforms and improve scalability by simplifying the server components.

Stateless – Each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any
stored context on the server. Session state is therefore kept entirely on the client.

Cacheable – Cache constraints require that the data within a response to a request be implicitly or explicitly labeled as cacheable or non-cacheable.
If a response is cacheable, then a client cache is given the right to reuse that response data for later, equivalent requests.

Uniform interface – By applying the software engineering principle of generality to the component interface, the overall system architecture is simplified
and the visibility of interactions is improved. In order to obtain a uniform interface, multiple architectural constraints are needed to guide the behavior
of components. REST is defined by four interface constraints: identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state.

Layered system – The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior such that each component
cannot “see” beyond the immediate layer with which they are interacting.

Code on demand (optional) – REST allows client functionality to be extended by downloading and executing code in the form of applets or scripts.
This simplifies clients by reducing the number of features required to be pre-implemented.

* Architectural Constraints :
REST defines 6 architectural constraints which make any web service – a true RESTful API.

Uniform interface
Client–server
Stateless
Cacheable
Layered system
Code on demand (optional)

* 200(OK):
HTTP Status 200 (OK)
The HTTP Status 200 (OK) status code indicates that the request has been processed successfully on server. The response payload depends on
HTTP method which was selected for request.

HTTP Status 200 – Response Payload
HTTP    METHOD RESPONSE PAYLOAD
GET     An entity corresponding to the requested resource is sent in the response.
HEAD Response has only HTTP header fields and no payload is sent in response.
POST Response generally contain information about progress status representation or result of action that was performed in request.
PUT Progress status representation of request is sent in response.
DELETE Progress status representation of request is sent in response.
OPTIONS:
        A list of valid request methods associated with the resource using Allow header. e.g.
Allow: HEAD, GET, OPTIONS
Content-Length: 18
Content-Type: text/plain;charset=UTF-8
Date: Thu, 06 Apr 2020 16:51 EST
Server: Apache-Coyote/1.1

TRACE A representation of the request message as received by the end server.

* HTTP Status:
1×× Informational
100 Continue
101 Switching Protocols
102 Processing

2×× Success

200 OK
201 Created
202 Accepted
203 Non-authoritative Information
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status
208 Already Reported
226 IM Used

3×× Redirection

300 Multiple Choices
301 Moved Permanently
302 Found
303 See Other
304 Not Modified
305 Use Proxy
307 Temporary Redirect
308 Permanent Redirect

4×× Client Error

400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Payload Too Large
414 Request-URI Too Long
415 Unsupported Media Type
416 Requested Range Not Satisfiable
417 Expectation Failed
418 I’m a teapot
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
431 Request Header Fields Too Large
444 Connection Closed Without Response
451 Unavailable For Legal Reasons
499 Client Closed Request

5×× Server Error

500 Internal Server Error
501 Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported
506 Variant Also Negotiates
507 Insufficient Storage
508 Loop Detected
510 Not Extended
511 Network Authentication Required
599 Network Connect Timeout Error

SoapUI
Q #1. What are web services?

Ans. Web services are web components that transfer data between client and server. The client sends a web request to the server and the server then responds to the client. The response and request are related and different requests evoke the corresponding response.

Web Service is a web component or software program that can be accessed on the Internet. It is mainly used to communicate with the web-based applications through XML messaging concepts. For example, if we want to access a particular location using Google Maps, we can use the corresponding web service URL. For that, we have to pass the appropriate inputs.

Q #2. What is the primary challenge when testing web services?

Ans. Majority of the functional testing is carried out via the GUI; the biggest challenge of web services is that they do not have a UI.

Q #3. What are the communication channels available for a web service?

In general, web service is combined with the following protocols. They are,

HTTP / POST
HTTP / GET
SOAP
While exposing the web services, these channels will be used for communication with the clients. Here HTTP / POST protocol transfers the information between the clients with a secure mode. HTTP / GET protocol allows the clients to view transferred data partially at the browser’s address bar. SOAP is used for transferring the confidential data safely.

Q #4. What are the different components can be used in the web services?

There are four components are used in web services. They are,

WSDL – Web Service Description Language
SOAP – Simple Access Object Protocol
UDDI – Universal Description, Discovery and Integration
RDF – Resource Description Framework
XML – eXtensible Markup Language
Q #5. What are the tools used for testing Web services?

To perform functional testing for web services, we can use the following tools.

SoapUI
RESTClient – This is a Firefox plug-in
JMeter – Specially made it for performance testing tool and also we can do functional testing the web services.
Q #6. What is WSDL?

Ans. WSDL stands for Web Service Description Language and is a document written in XML. It uses XML to define the service layer document which consists of origin of the web service, headers, port types, request and response data. This one can provide the information about web methods and web service.

It describes:

Origin of the web service
Header information
Port type
Input and output messages
For more info and examples, check out this article https://www.softwaretestinghelp.com/web-services-api-testing-tool-soapui-tutorial-1/

Q #7. What is the role of WSDL document in web service testing?

Ans. Validating web services in only possible with WSDL document because to configure web services in SoapUI, WSDL document is mandatory. If the WSDL document is not valid, SoapUI will throw an exception immediately.

Q #8. What is UDDI?

Ans. Universal Description, Discovery and Integration- a directory or global repository where all the web services can be found. A new Webservice can also be registered through this. This is also the place where WSDL detailed definitions are found.

It uses the discovery layer which is used in the web services. UDDI has all the information about the web services in detail. Global web services can be deployed at http://uddi.xml.org/

Q #9. What is SOAP?

Ans. Simple Object access protocol that uses XML to interact with web applications. It uses XML based content to communicate between two client machines across any network

Q #10. What would be the message format of SOAP protocol?

Generally, all the SOAP-based web services are written by using XML language which uses standard message format that is accepted across the universe. In this format, it is easy to read, identify the errors, avoids interoperability problems etc.

Here’s the sample SOAP message format.

POST /InStock HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: 399
SOAPAction: “http://www.example.com/soap-envelope”

<?xml version=”1.0??>
<soap:Envelope xmlns:soap=”http://www.example.com/soap-envelope”>
<soap:Header>
</soap:Header>
<soap:Body>
<m:TutorialName>SoapUI</m:TutorialName>
</soap:Body>
</soap:Envelope>

Q #11. What are the advantages of SOAP?

Ans. Since its XML based, it is platform and programming language independent. RPC (Remote procedure calls) are sometimes blocked by firewalls and proxy servers- Soap overcomes that.

Q #12. What does a soap document contain?

Ans. Envelope element is the topmost tag which identifies the XML document as a SOAP message. Followed by Envelope element, you see the header element that has header information. The Body element specifies the call and response information. Finally, you have a Fault element which contains errors and status information.

Q #13. What is meant by Protocols and what are the major types are used in web services?

A protocol is a set of standard rules that help to communicate the hardware devices through the software applications. There are different types of protocols used in the Internet and Intranet applications. They are

TCP which stands for Transmission Control Protocol. It has the rules to exchange the messages between two different Internet applications.

Internet Protocol uses the rules for sending and receiving the information between two different Internet addresses.

Similarly, HTTP, FTP and DHCP protocols have used the set of rules to transfer the data other than Internet applications.

Q #14. What is XML?

Ans. XML (eXtensible Markup Language) is a mark-up language that is used for storing, sharing and formatting data. In general, an XML document is built by the tags. For more info and examples, check out this article https://www.softwaretestinghelp.com/web-services-api-testing-tool-soapui-tutorial-1/

Q #15. SoapUI and SoapUI Pro?

Ans. SoapUI is a web service testing tool and SoapUI Pro is its commercial version. SoapUI can help create functional, security and load testing test suites. SoapUI Pro does all that with advanced drag and drop, Data Driven testing, advanced reporting and coverage analysis. Check out this article for more information: https://www.softwaretestinghelp.com/soapui-tutorial-12-soapui-pro-features/

Q #16. What we can do with the help of SoapUI?

SoapUI offers us to perform automation testing which includes functional testing, load testing and Data Driven testing.
It also provides in build reporting tool and export test results log provision
We assert our services using various types of assertions
Q #17. What hierarchy does SoapUI follow to build a proper testing project?

In a SoapUI project, the following order should be maintained.

TestSuite – This is combination of functional tests and logical blocks
Testcase – It's a group that contains several test steps for the specific aspects of the service.
Teststep – it contains the set of functional tests
Q #18. What is the basic method to automate web services in SoapUI?

Ans.

Create a project and add the WSDL file
Add test suites, Test cases and Test cases- in that order
Include custom programming/validation using by adding Groovy steps
Call external data sources if using
Add assertions if necessary
Then RUN.

Q #19. What are SoapUI assertions?

Ans. Assertions compare the parts/all of the response message to the expected outcome.

Q #20. What are the major types of assertions available in SoapUI?

Assertions are one of the major features in SoapUI. It offers the following types of assertions.

Simple contains
Schema compliance
Simple not contain
Soap Faults
Response SLA
XPath Match
XQuery Match
WS security status
Script Assertion
WS- Addressing Request or Response Assertion
Additionally, Equals assertion is introduced in SoapUI NG Pro version

Q #21. What are the different types of assertions used in SoapUI?

Ans. The following are the different types of assertions:

Contains & Not Contains
XPath match
XQuery match
Schema compliance
Soap Faults
Response SLA
WS security Status
Script Assertion
WS- Addressing Request or Response Assertion


Q #22. Soap vs REST?

Ans.

SOAP is a protocol and REST is architecture. It allows us to send SOAP envelops to REST-based applications.
REST supports different message formats but SOAP permits XML only.
REST services are faster and easy to handle.
SOAP is tied with SMTP and HTTP protocols whereas REST relies on HTTP only.
SOAP is more secure and structured format.
REST does not depend on any specific standards as it supports various messaging formats like JSON, CSV and XML.
SOAP web services allow us to build the client with RESTful services.
SOAP was introduced for distributed computing.
After REST’s entry, it accommodated the web by its performance and scalability as it is a lightweight component.
REST is stateless whereas SOAP is a stateful specification.
REST uses Uniform Resource Identifier (URI) and it has the methods like GET, PUT, POST and DELETE to expose their resources.
SOAP uses named operations and interfaces to achieve its business logic.

Q #23. What can data sources be used in SoapUI?

Ans.
Excel Files
CSV Files
ODBC Sources
SQL / ADO Objects

Reference : https://www.softwaretestinghelp.com/soapui-interview-questions-and-answers/

Q #24. Explain what assertion is in Soap UI is and give some example of assertion possible in SOAPUI?

In SOAP UI assertion functionality is used to validate the response of request received by the Test Steps at the time of execution.  It is used to compare a part of message to some expected value.

Assertion types in SOAPUI includes

Simple contains
Schema compliance
Simple not contains
Soap Faults
Response SLA
XPath Match
XQuery Match
WS security status
Script Assertion
WS- Addressing Request or Response Assertion

Q #25. Does SoapUI support SSL Authentication

Yes

Q #26. Explain where you use properties in SoapUI?

We can read the property values into test step endpoint, username, header values, password, domain, POST, PUT, GET and DELETE method properties.

Q #27. Mention what languages does SoapUI use?

SOAP UI supports two language, Groovy, and JavaScript.

Q #28. Mention what are the default properties in SOAPUI?

By default, SOAPUI has properties at three levels

Project level default or custom properties:
User can append any number of properties at project level and it can be opened from any test steps from any test cases under any test suites

Test suite level default or custom properties:
User can append any number properties at test suite level and it can be used from any test steps from any test cases under this test suite

Test case level default or custom properties:
At Test Case level users can add any number properties at test case level and it can be used from any test steps from this test case

Q #29. SoapUI RESTful - HTTP Methods
The most-commonly-used HTTP methods are POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and delete (or CRUD)
operations, respectively. There are a number of other methods too, however they are utilized less frequently.

* POST:
The POST method is used to create new resources. It is used to create subordinate resources. That is, subordinate to some other (e.g. parent) resource.

In other words, when creating a new resource, POST to the parent and the service takes care of associating the new resource with the parent,
assigning an ID (new resource URI), etc.

On successful creation, return HTTP status 201, returning a location header with a link to the newly-created resource with the 201 HTTP statuses.

* GET:
The HTTP GET method is used to read or retrieve a representation of a resource. In successful response, GET returns a representation in XML or JSON
and an HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT FOUND) or 400 (BAD REQUEST).

According to the design of the HTTP specification, GET (along with HEAD) requests are used only to read data and not change it.
Therefore, GET is considered as safe.

* PUT:
PUT is used to update the existing resources. PUT is used as a known resource URI with the request body that contains the
updated representation of the original resource.

PUT can also be used to create a resource where the resource ID is chosen by the client instead of by the server.
In other words, if PUT is used as a URI that contains the value of a non-existent resource ID.

* PATCH:
PATCH is used to modify capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource.
It resembles PUT, but the body contains a set of instructions describing how a resource currently residing on the server should be modified to produce a new version.

This means that the PATCH body should not just be a modified part of the resource, but should be in some kind of patch language
such as JSON Patch or XML Patch.

* DELETE:
DELETE is used to delete a resource identified by a URI. On successful deletion, it returns HTTP status 200 (OK) along with a response body,
representation of the deleted item. Else, it returns HTTP status 204 (NO CONTENT) with no response body.

In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.