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/
------

No comments:

Post a Comment