Friday, September 30, 2011

Working with Dictionary Object

Set dictObj=Createobject("Scripting.Dictionary")
dictObj.Add "1","One"
dictObj.Add "2","Two"
dictObj.Add 3,"Three" 'Observe here i am passing key as a integer meaning we can pass different types as Key

msgbox dictObj.Count 'This method returns the number of keys

If dictObj.Exists(3) Then 'This method looks for the Key
msgbox "Key exists"
else
msgbox "Key does not exist"
End If

a=dictObj.Keys 'This method assigns all the keys to an array
For i=1 to dictObj.Count
msgbox dictObj.Item(a(i-1)) 'This method retrieves the value of the key
Next

Sunday, July 24, 2011

How to select a check box\click a link in a web table with text

This is one of the most common interview question.
The first column of a web table contains checkboxs, and in the second column have some text.
If any row in the second column contains a text say "uday", then the corresponding checkbox in the first column should be selected.
How can we do that?

It is pretty simple: :)
rowNo=B().P().WT().getrowwithcelltext("uday",2) 'Here "uday" is my search string and 2 the column number
set childObj=B().P().WT().ChileItem(rowNo,1,"webcheckbox")
childObj.set "ON"

Friday, July 22, 2011

Different ways of synchronizing in QTP

In QTP, we can do synchronizing between QTP tool and application in many ways:

1. The best one is, use synchronization point, which waits until the object meets the criteria. The general syntax is:
Object.waitproperty "your criteria"
Ex: B().P().WB().Waitproperty "enabled",1,10000
B().P().WE().WaitProperty "text",micNotEmpty(var)
(Here the tool waits until the object meets the criteria).

2. Wait(least preferred): It is like hard coding the time. The syntax is:
Wait(x) ' waits x seconds irrespective of the object state. For Ex. If we set the x as 60 Seconds and the object is ready by 2 seconds, even then it waits for 60 seconds.
If the object is not ready by 60 seconds, it wont bother and it moves to the next step(may causes script fail).

3. We can use Wait and Exists in some cases

4. And also we can use Wait and CheckProperty, which almost works like synchronization point.

5. You can also configure the default settings in the tool.
Browser navigation timeout : File -> Settings -> Web ->Browser navigation timeout
Object synchronization timeout : File -> Settings ->Run -> Object synchronization timeout.

6. We can also write custom script for QTP like below to wait till the application is loaded.

Set oPage=B().P().Object
While oPage.readystate=”Completed”
Wend

While oPage.Busy
Wend

Tuesday, July 19, 2011

Some common QTP Tips & Tricks:

Maximum no. of actions can be created:
From QTP 9.0(or later) max of 120 actions can be created. We can extend this by installing private patch.
From QTP 8.2(or below) max of 255 actions can be created.

How to find which version of vbscript you are using?
Search for vbscript.dll in c:\windows\system32. In properties -> Version tab
Programatically we can retrieve this by:
msgbox ScriptEngineMajorVersion &"."& ScriptEngineMinorVersion

Associating function library Vs executefile
Use to associate functional libraries to a test rather than using execute file.
By associating functional library, all actions in the test can access those functions.
By calling executefile, all functions are loaded in the calling action only.

Recovery Scenario Vs On Error Resume Next
Recovery scenarios can be used when we dont know where an error arises.
We can use On Error Resume Next when we know the occurance of an error and we dont want to halt the execution because of that error.

Loading function library at run-time
From QTP 11 onwards we can use "LoadFunctionLibrary" statement to load Function library at run-time.
We can load multiple functional libraries in a single call like
LoadFunctionLibrary "c:\flb1","c:\flb2" etc...

Generating Random number
Generating a random number between min and max.
Syntax is: Int((max-min+1)*Rnd +min)
The below example generates a random number between 10 to 50 in each iteration
For i=1 to 5
msgbox Int((50-10+1)*Rnd +10)
Next

Arrays with redim
Small example with arrays and redim preserve
a=Array(5,2,50,33,21)
For i=0 to ubound(a)
msgbox a(i)
Next
ReDim preserve a(7)
a(5)=10
a(6)=20
For i=0 to ubound(a)-1
msgbox a(i)
Next

Monday, July 18, 2011

Shared Object Repository Vs Dynamic Programming

When to use shared repository(SOR) vs descriptive programming(DP).
1. QTP can perform faster with SOR, because while replying a script if it encounters an object, it will create a temporary test object with the description, and it uses this temporary test object for the rest of the test execution rather than building this test object for each occurrence.
Where as in "Static DP" that is not the case, each time it builds the objects and uses while execution.
If properly written\coded, "Dynamic DP" have the same performance as Shared OR.

2. Object identification with OR is more handy, because we can configure properties for mandatory & assistive properties and ordinal identifiers and also we can enable smart identification mechanism for object identification.
Where as in DP, all the properties used are treated as mandatory properties.

3. We can associate a single SOR and we can access in any action\test.
Where as in static DP, we build objects in the action\test, which cannot be accessible in other actions\tests.
Where as using dynamic DP, we can write driver script which loads all objects(say in dictionary object) and can be used.

4. QTP automatically creates the SOR while recording or manually adding Objects to OR.
Where as in DP, we need to identify unique properties in the application, and use those properties which is a time consuming task.

5. With SOR we can export\import objects to XML files. No such functionality with DP.

6. DP is more useful when working with dynamic objects.
Ex: want to verify all links in a webpage. Here we just create an single link object description and use it to verify all the links. That is not the case with SOR, we have to store and each and every link(which is not always possible, because the links are dynamic).

7. Regular expressions can be used in both SOR or DP.

8. Parametrization can be done in both SOR or DP.

Sunday, July 17, 2011

Work with Shared Object Repository

Shared OR are more advantages than local OR.
1. A OR file which can be associated to any action and any test.
2. If the size of OR grows up, we can split that file to multiple files and associate to action\test.
3. Can be handled very easily i.e we can add local objects in OR to shared, merging of local to shared, merging two shared ORs, we can compare two Shared ORs etc...
4. QTP has so size limit for shared OR, but it recommends the file size is upto 1.5MB for performance reasons.
5. We can handle share ORs easily using OR Manager.

Disadvantages:
1. In a team environment, one team member updates\deletes an object, then all other team members who are working on that object get effected.
2. If we use a single file to hold all shared ORs then, then performance will go down.

Through the tool we can associate the share OR in multiple ways:
1. Edit -> Action -> Action properties -> Associated Repositories -> Browse ur shared OR
2. Resources -> Associate Repositories


We can programmatically add shared ORs in following ways:
Method 1:
Set App=CreateObject("QuickTest.Application")
Set ORS=App.test.Actions("Action1").ObjectRepositories
ORS.Add("c:\sharedOR.tsr")
ORS.Count 'returns the number of shared ORs associated
ORS.Find 'finds the shared OR
ORS.Remove 'removes the associated shared OR

Method 2:
SORpath = "c:\sharedOR.tsr"
RepositoriesCollection.Add(SORpath)
Same above methods can be used with RepositoriesCollection(Add, Count, Find, Remove etc..)

Method 3:
Set RepositoryObj = CreateObject("Mercury.ObjectRepositoryUtil")
RepositoryObj.Load "c:\sharedOR.tsr"
"RepositoryObj" util have more methods than the above.

Saturday, July 16, 2011

How to call a function in one action from another action

We can do this QTP, by passing the function name with parameters as Input parameters

Following is the script in my "Action1"
RunAction "LibraryAction",0,"displayMsg(3)"
FuncReturnVal = RunAction ("LibraryAction", oneIteration, "sum 5,6,7,8")
msgbox FuncReturnVal

Create a New action called "LibraryAction", can created an input parameter call "function" of type string
Following is the script in my second action "LibraryAction"

func = Parameter("function")
Execute func
Public function displayMsg(str)
msgbox(str)
End Function

Function sum(a,b,c,d)
temp=a+b+c+d
exitAction(temp)
End Function

Working with cookies in QTP

Cookies are temporary internet files which were created by Web Server in users Harddisk. When we make a request to a website, the Web Server looks for the

cookie in our Harddisk, and uses the stored information(if it finds), or creates a new cookie file in our system.
Only the webserver can understand the cookie information properly, we cannot understand the content of the cookie properly.
Cookies can be long-term, short term.
Long term cookies, can be saved as per the configured number of days(may be months or year)
Short term cookies get deleted once you visited the site and close the browser.
We can access the cookies information by Start->Run ->cookies and enter

We can test these cookies using QTP.

In QTP there is utility called "WebUtil" which was supported completely upto QTP 6.0. Later it was not supported fully. It is there only for backward

compatability.
We have couple of methods related to cookies like:
WebUtil.Addcookie
WebUtil.Deletecookie
WebUtil.Deletecookies 'deletes all cookies in the system
WebUtil.Getcookies

There is otherway around to delete cookies using Windows shell object:
SysUserName=Environment.Value("UserName")
Set ShellObj=CreateObject("WScript.shell")
ShellObj.run("cmd /C cd C:\Documents and Settings\" & SysUserName & "\Cookies & del *.txt")
Set ShellObj=nothing

The above two methods works with IE not with other browsers.

Wednesday, July 13, 2011

Work with command prompt using QTP(vbscript)

We can use Windows Shell object to start a command prompt and execute the command.

In the following i want to list all files\folders in C drive:
Set wscriptObj=createobject("WScript.Shell")
wscriptObj.Run "cmd /K cd c:\ & dir"

When i execute the above statement, it opens the command prompt and execute dir command. You are free to use any command you want as per your needs.

How to work with Windows registry using QTP(vbscript)

We can work with Windows registry using WScript.Shell object.

If you want to read a specific Key from registry
Set wscriptObj=createobject("WScript.Shell")
objProperties=wscriptObj.RegRead("HKLM\SOFTWARE\Mercury Interactive\QuickTest Professional\MicTest\Test Objects\Browser\CommonUse\")
msgbox objProperties
The above will give you the "Default" property value

If you want to read a specific property name in the registry:
objProperties=wscriptObj.RegRead("HKLM\SOFTWARE\Mercury Interactive\QuickTest Professional\MicTest\Test Objects\Browser\CommonUse\Sync")

If you want to update a specific property value in the registry:
wscriptObj.RegWrite "HKLM\SOFTWARE\Mercury Interactive\QuickTest Professional\MicTest\Test Objects\Browser\CommonUse\Sync",0,"REG_DWORD"

If you want to delete a specific property from the registry:
wscriptObj.RegDelete "HKLM\SOFTWARE\Mercury Interactive\QuickTest Professional\MicTest\Test Objects\Browser\CommonUse\Sync"


You can also use DotNetFactory to retrieve any retrieve any value
registryPath1="HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\IEXPLORE.EXE"
'Here i am creating an instance of DotNet Factory computer object
Set objDFComputer=DotNetFactory("Microsoft.VisualBasic.Devices.Computer","Microsoft.VisualBasic")
'Here i am creating an instance of Registry Object
Set objRegistry=objDFComputer.Registry
'The below will retrieve the "Default" Property
print objRegistry.GetValue(registryPath1,"","")

'The below retrieves the property of the regsitry
print objRegistry.GetValue(registryPath1,"Path","")
Set objRegistry=nothing
Set objDFComputer=nothing

Thursday, July 7, 2011

Different ways to invoke a IE browser

'commonly used method
systemutil.Run "iexplore.exe"
wait(10)
Browser("name:=.*").Navigate "www.yahoo.com"

'For QTP backward compatability
invokeapplication "C:\Program Files\Internet Explorer\iexplore.exe http://www.yahoo.com"

Set WShelObj=Createobject("WScript.Shell")
WShelObj.Run Chr(34) & "C:\Program Files\Internet Explorer\iexplore.exe" & Chr(34)&" "&"www.yahoo.com"
or
Set WShelObj=Createobject("WScript.Shell")
WShelObj.Run Chr(34) & "C:\Program Files\Internet Explorer\iexplore.exe" & Chr(34)
Browser("name:=.*").Navigate "www.yahoo.com"
Char(34) is used to append double quotes to the IE application path.

Sunday, July 3, 2011

What test cases to be automated

Following are to name a few common test cases which needs to automated:
1. Test Cases that belongs to core functionality(which is less frequent or no change in functionality) sometimes called regression test cases.
2. Test Cases which needs to executed, but taking long times to execute manually.
3. Identify reusable actions which are used by most of the test cases.
4. The same test case which needs to verify with different values(data driven). The same test case with different environments(compatibility).

Importance of WaitProperty method

We generally use WaitProperty with below syntax like
Object.WaitProperty "visible",1,10000

But assume i have a EditBox, and any data can be populated in this field. QTP should wait until it populated with data, and then proceed further after it populated with data. To handle these situations use below syntax:
Dim vEmpty 'Here vEmpty is uninitilized with any value, so it have empty value.
Object.WaitProperty "text",micNotEqual(vEmpty)

Common comparisons we use here are:
micGreaterThan
micLessThan
micGreaterThanOrEqual
micLessThanOrEqual
micNotEqual
micRegExpMatch

VB Script to find the number of occurences of a char in a string

Method 1:
str="Hello world"
Set regex=new RegExp
regex.pattern="l"
regex.global=true
Set matches=regex.execute(str)
msgbox matches.count

Method 2:
arr=split(str,"l")
msgbox ubound(arr)

Method 3:
counter=0
For i=1 to len(str)
char=mid(str,i,1)
If char="l" Then
counter=counter+1
End If
Next

msgbox counter

Sunday, June 26, 2011

Swap two numbers

Swap two numbers without using any other parameter
a=10
b=20
a=a+b
b=a-b
a=a-b
msgbox a&" "&b

Swap two numbers using some extra parameter
a=10
b=20
temp=a
a=b
b=temp
msgbox a&" "&b

Different Test Case design techniques

1. BVAs
2. ECPs
3. Decision tables
4. State Transition graphs\Cause -Effect graphs
5. Error guessing etc...

Examples for High Severity and Low priority and Low Severity and High Priority

High Severity and Low Priority
a. Any out of scope items
b. Network problems which are intermittent

Low Severity and High Priority
a. Spell mistakes in company names or logos
b. Copyright content used in the application

How to check a value exists in a weblist using QTP

noItems=browser("name:=Web*.*").page("title:=Web*.*").weblist("name:=depart").GetROProperty("items count")
flag=false
For i=1 to noItems
If lcase(browser("name:=Web*.*").page("title:=Web*.*").weblist("name:=depart").GetItem(i))="uday" then
flag=true
end if
Next

If flag=true Then
msgbox "Exists"
else
msgbox "Not Exists"
End If

What is the difference between Smoke testing and Sanity testing

Smoke Testing:

A smoke test is a series of test cases that are run prior to commencing with full-scale testing of an application. The idea is to test the high-level features of the application to ensure that the essential features work. If they do not work, there is no need to continue testing details of the application, so the testing team will refuse to do any additional testing until all smoke test cases pass. This puts pressure on the development team to ensure that the testing team does not waste valuable testing time with code that is not ready to be tested.
Smoke testing can be done for testing the stability of any interim build.

Sanity Testing:

Once a new build is obtained with minor revisions, instead of doing a through regression, sanity is performed so as to ascertain the build has indeed rectified the issues and no further issue has been introduced by the fixes. Its generally a subset of regression testing and a group of test cases are executed that are related with the changes made to the app.
Generally, when multiple cycles of testing are executed, sanity testing may be done during the later cycles after through regression cycles.

Saturday, June 25, 2011

What are limitations of Virtual Objects in QTP



  1. QuickTest does not support virtual objects for analog or low-level recording.
  2. The Web page or application window must be the same size and in the same position when recording and running tests s as it was when you defined the virtual object.
  3. You cannot insert any type of checkpoint on a virtual object.
  4. The virtual object should not overlap other virtual objects in your application or Web page.
  5. You can define virtual objects only for objects on which you can click or double-click and which record a Click or DblClick step. Otherwise, the virtual object is ignored.

Friday, June 24, 2011

Difference between Stored Procedure, Trigger and Functions

Difference between Stored Procedure and Trigger:

A stored procedure is a group of Transact-SQL statements that is compiled one time, and then can be executed many times. This increases performance when the stored procedure is executed because the Transact-SQL statements do not have to be recompiled.

A trigger is a special type of stored procedure that is not called directly by a user. When the trigger is created, it is defined to execute when a specific type of data modification is made against a specific table or column.

A CREATE PROCEDURE or CREATE TRIGGER statement cannot span batches. This means that a stored procedure or trigger is always created in a single batch and compiled into an execution plan.



Difference between a function and a stored procedure:

1. Functions can be used in a select statement where as procedures cannot

2. Functions takes only input parameters, where as Procedure takes both input and output parameters.

3. Functions cannot return values of type text, ntext, image & timestamps where as procedures can.

4. Functions can be used as user defined datatypes in create table but procedures cannot
Eg:-create table (name varchar(10),salary getsal(name))

Difference between truncate and delete in SQL Server

1. Truncate is DDL command
1. Delete is a DML command
2.
Truncate operation cannot be rolled back.
2. Delete operation can be rolled back.
3. By using Truncate operation, it deletes everything and reconstructs the table structure (schema). We can’t retain the values.
3. By using Delete we can retain the deleted values.
4. We cannot use where clause in truncate.
4. Where clause can be used with Delete.
5. By using Truncate operation, all the identities will be deleted
5. By using Delete identities cannot be deleted.

6. The syntax for truncating a table is: truncate table tablename.
6. The syntax for deleting rows from a table is: delete from table or delete from table where condition
7. Truncate table is faster and uses fewer system and transaction log resources than Delete.
7. The Delete statement removes rows one at a time and records an entry in the transaction log for each deleted row.
8. Because Truncate table is not logged, it cannot activate a trigger.
8. It can activate a trigger.




Sunday, June 12, 2011

QTP Script to execute a SQL Query

Dim recordsetObj,commandObj
Dim connectionStr,queryStr

Set commandObj=createobject("ADODB.command")
Set recordsetObj=createobject("ADODB.recordset")
connectionStr="driver=sql server;server=papdsr05;database=test;uid=sa;pwd=sa"
queryStr="select * from employee"

commandObj.activeconnection=connectionStr
commandObj.commandtext=queryStr
Set recordsetObj=commandObj.execute
while not recordsetObj.EOF
empname=recordsetObj.fields("EmpName").value
recordsetObj.movenext
wend
'commandObj.close
recordsetObj.close

Tuesday, May 17, 2011

Error handling in QTP using On Error

By using QTP recovery scenario, we can handle errors.

The other way around handling Errors is using "On Error" statements.

Following code throws an Exception at Line 6, and the execution cannot proceed further.
msgbox "hello"
call funcOne
msgbox "after function call"

function funcOne()
msgbox 1/0
end function
Here the output is "hello", the script never reaches to the second output statement

To proceed further after the exception occured, use "On Error Resume Next" statement, which just ignores the Exception and proceeds.
msgbox "hello"
call funcOne
msgbox "after function call"

function funcOne()
On Error Resume Next
msgbox 1/0
end function
Here the output contains both the messages

To customize the error message displayed, use the Err Object
msgbox "hello"
call funcOne
msgbox "after function call"

function funcOne()
On Error Resume Next
msgbox 1/0
msgbox "Error Message: "&Err.Description&" and Error code: "&Err.Number
end function
Here the output is 3 msgs, including the Error description.

To disable Error Handling mechanism use "On Error Goto 0" statement.
msgbox "hello"
call funcOne
msgbox "after function call"

On Error Goto 0

call funTwo ' here the Error occues as we disabled Error Handling

function funcOne()
On Error Resume Next
msgbox 1/0
msgbox "Error Message: "&Err.Description&" and Error code: "&Err.Number
end function

You can also clear the Error object using Err.clear().

Monday, May 16, 2011

Difference between Driver and Stub

Driver:
1. A software module or application used to invoke a test item and, often, provide test inputs (data), control and monitor execution. A test driver automates the execution of test procedures.
2. Bottom-up testing still requires that test drivers be constructed

Stub:
1. A dummy software component or object used (during development and testing) to simulate the behavior of a real component that was not yet constructed. The stub typically provides test output
2. Top-down testing requires that stubs be created to simulate the actions of called functions that have not yet been incorporated into the system

Difference between Test Strategy and Test Plan

Test Strategy describes about the overall "testing appraoch" of our testing.
Generally prepared by Project Manager or his delegate.
It provides a roadmap that describes the steps to be conducted as part of testing, when these steps are planned and under taken, and how much effort, time and resources will be required. Therefore, any test Strategy must incorporate test planning, test design, test execution, and resultant data collection and evaluation.
This document generally derived from BRD(Business Requirement document)
It is static document, meaning updation of this document is almost minimal.
This document can be organization specific or project specific.


Test plan describes about "how & what we are going to test, who will do what, when to test".
Generally prepared by Test Lead or Test Manager.
It prescibes the scope, appraoch, resources and schedules of our testing activities.
This document is generally derived from Business Requirement Document, Functional Specification Document, Technical Specification Document and any use case document.
It is dynamic document, and needs to be updated as per the needs.
This document is project specific, and based on the project size, some projects have master test plan and individual test plans will be derived from this test plan.
The content of the Test Plan includes:
1. Introduction
a. Overview of the project
b. Purpose of this document
c. Objectives of the testing
2. Scope of testing
a. Features to be tested
b. Out of scope items
3. Test Strategy: Different types of testing
4. Test and System schedules
5. Roles and Responsibilities
6. Environment requirements
7. Resources(H/w,S/w, human)
8. Risks and contingencies
9. Deliverable
10. Approvals

Tuesday, February 15, 2011

Write a statement to select a checkbox existing in a webtable

We can do this by using childitem.

The syntax is Obj.childitem(rowno,colno,ClassOfTheObject,index)

Ex: Here is the example to check a checkbox in 4th row, 2nd col.

set cbObj=browser(browserObj).page(pageObj).webtable
(webtableObj).childitem(4,2,"WebCheckbox",0)

cbObj.set "ON"