Sunday 30 December 2012

QTP interview questions

1. What is QTP ?
2. What is Session ?
3. What are Add-ins ?
4. What are cookies ?
5. What is GetRoProperty ?
6. What is SetToProperty ?
7. What is Step Generator ?
8. What is Text checkpoint ?
9. What are Virtual Objects ?
10. What is an Optional Step ?
11. What is Analog recording ?
12. What is Object Spy in QTP ?
13. What is Test Fusion Report ?
14. what is keyword driventest ?
15. How to debugging your test ?
16. Explain QTP Testing process ?
17. How to check Bitmaps in QTP ?
18. How to test a date with QTP ?
19. What are limitations of QTP ?
20. What is data driven testing ?
21. What is database check point ?
22. What is Reporter.ReportEvent ?
23. What is smart Identification ?
24. What is Parameterizing Tests ?
25. How to schedule tests in QTP ?
26. How to Test XML pages in QTP ?
27. What is Automation framework ?
28. What are the datatypes in QTP ?
29. How does QTP identify objects ?
30. What is QTP batch testing tool ?
31. What is action conversion Tool ?
32. What is keyword driven testing ?
33. What is descriptive programming ?
34. Where do checkpoints get stored ?
35. What is meant by Source Control ?
36. What is the cost of QTP license ?
37. How to export object repository ?
38. How to handle exceptions in QTP ?
39. What is Accessibility Checkpoint ?
40. What is test object model in QTP ?
41. What is logical name of the object
42. How to Turn Off QTP test results ?
43. How to analyzing QTP test results ?
44. How QTP recognizes Objects in AUT ?
45. How to declare a variables in QTP ?
46. What is the latest version of QTP ?
47. What is Object Spy ? How to Use it ?
48. What you do if QTP license expires ?
49. Which environments supported by QTP ?
50. How to connect to database from QTP ?
51. How to comment block of code in QTP ?
52. How to change name of a checkpoint ?
53. When to use analog recording in qtp ?
54. How will you handle Java tree in QTP ?
55. How can you handle exceptions in QTP ?
56. How to handle dynamic objects in QTP ?
57. What are environment variables in QTP ?
58. How to update database table from QTP ?
59. How do you setup QTP test environment ?
60. How do we record a pop up window in QTP
61. How to develop Test Frame work for QTP ?
62. What is meant by external files in QTP ?
63. What is the use of Regular Expressions ?
64. How to reporting defects in QC from QTP ?
65. How to test dynamic web pages using QTP ?
66. How to import data for data driven test ?
67. How to check for broken links using QTP ?
68. How can we mask data in QTP script file ?
69. What are check points ? Why we need them ?
70. How to test a stored procedure using QTP ?
71. How to record non-standard object in QTP ?
72. What is the limitation of XML Checkpoint ?
73. When should we use virtual object wizard ?
74. How to test flash applications using QTP ?
75. How to add a page checkpoint to your test ?
76. How to write QTP test results to an Excel ?
77. What are the environments supported by QTP ?
78. What is difference between stub and driver ?
79. How many types of Actions are there in QTP ?
80. How to connect to Oracle database from QTP ?
81. How to make QTP recognise activeX controls ?
82. How to check size of the object repository ?
83. How to record Flex (1.0) objects using QTP ?
84. What is keyword view and Expert view in QTP ?
85. What is recovery manager ? Explain in detail.
86. What factors that affect bitmap checkpoints ?
87. How many types of recording are there in QTP ?
88. How do you test oracle application using qtp ?
89. How do you test oracle application using qtp ?
90. What is the scope of a variable in an action ?
91. How to add run-time parameter to a datasheet ?
92. Explain keyword “CreateObject” with an example
93. How to call winrunner script from QTP script ?
94. What will you do to record Java objects in QTP?
95. How to execute qtp script from command prompt ?
96. What is the file extension test script in QTP ?
97. What are the different loops supported in QTP ?
98. How to call from one action to another action ?
99. How to return value from userdefined function ?
100. What is the file extension of function library ?
101. What are different types of Checkpoints in QTP ?
102. How to create dynamic object repository in QTP ?
103. How to write script without using a GUI in QTP ?
104. How to perform cross browser testing using QTP ?
105. Where is the bitmap chekpoint information saved ?
106. How to perform cross platform testing using QTP ?
107. How would you connect to database using vbscript ?
108. How to perform Test Automation feasibility study ?
109. What is the difference between Winrunner and QTP ?
110. What is the difference between VB and VBScripting ?
111. Does QuickTest Professional (QTP) support Unicode ?
112. How to validate dates like today’s date(02/15/06) ?
113. What are the scripting languages supported by QTP ?
114. How to supress warnings from the Test results page ?
115. Explain in brief about QTP Automation Object Model ?
116. What is the use of function and sub function in QTP ?
117. What is the function for loading a repository in QTP ?
118. What are the different types object repository in QTP ?
119. What are the different ways you can enhance QTP script ?
120. Explain about Smart Identification with a simple example
121. How to execute a Parameterized SQL query in QTP script ?
122. How to call a funtion present in dll from a QTP Script ?
123. How is run time data (Parameterization) handled in QTP ?
124. What are the different types of recording modes in QTP ?
125. What is a Run-Time Data Table ? How to view this table ?
126. Have you have used a COM interface in your QTP project ?
127. What is the maximum number of actions supported in QTP ?
128. What are the different dubugging modes available in QTP ?
129. What are the different ways to parameterize data in QTP ?
130. What is the significance of keywords Public and Private ?
131. Can you launch two instances of QTP on the same machine ?
132. What is the difference between qtp script and vb script ?
133. Give one example where you have used Regular Expression ?
134. How to pass parameters from one action to another action ?
135. what is the regular expression for date format of ddmmyy ?
136. How to close all the opened browsers by using QTP script ?
137. What is the Hotkey that can be used for Hitting spacebar ?
138. How can i add a action (external action) programatically ?
139. How to Save your test using QuickTest Professional (QTP) ?
140. How to break a test if one of the bitmap-checkpoint fails ?
141. What is action split and the purpose of using this in QTP ?
142. What are the Features and Benefits of Quick Test Pro(QTP) ?
143. How to open a new test using QuickTest Professional (QTP) ?
144. How to get Class name of a Test Object at run time in QTP ?
145. What are the different types of Test Automation Frameworks ?
146. Will QTP recognize objects in applications like Photo-Shop ?
147. What are the different VBScript function that you have used ?
148. How to pass parameters from one test to another test in QTP ?
149. What is the difference between check point and output value ?
150. What is the difference between functions and actions in QTP ?
151. How would you export a Script from one PC to another in QTP ?
152. What is the extension of script and object repository files ?
153. Which of the check points can be inserted without recording ?
154. How to call external aand built-in-function in a QTP script ?
155. How to find out if a application window is minimized or not ?
156. Which scripting language used by QuickTest Professional (QTP) ?
157. What is the difference between Call to Action and Copy Action ?
158. What is difference between window(” “) and dialog(” “) in QTP ?
159. Which is better Keyword driven testing or Data driven testing ?
160. What are the types of qtp licenses ? Explain each of them briefly
161. What is the default delay time for web based application in QTP ?
162. How to get class name of test object by repository logical name ?
163. How to load the *.vbs or test generating script in a new machine ?
164. How to choose scripting language between JavaScript and VBScript ?
165. Different ways of adding check points to an application using QTP ?
166. Can we record an application running on a remote machine using QTP ?
167. What are different execution modes available in QTP & explain them ?
168. What is the Diff between Image check-point and Bit map Check point ?
169. How to count number of columns of a database table from QTP script ?
170. What are the advantages and disadvantages of Virtual object wizard ?
171. What is the difference detween text and Textarea checkpoints in QTP ?
172. If you were given thousand tests to executed in 3 days what do u do ?
173. How to handle the exceptions using recovery scenario manager in QTP ?
174. What does it mean when a check point is in red color ? what do u do ?
175. What is difference between Analog recording and low level recording ?
176. Is there any function to double click a particular row in a webtable ?
177. What is the use of Text output value in QuickTest Professional (QTP) ?
178. Can we call a QTP script from a main script without making it reusable ?
179. How to insert a check point to a image to check enable property in QTP ?
180. What are the coding standards that you have used for automation using QTP ?
181. How can i import and/or merge an existing repository into my current test ?
182. How to get a text from a list box,a cell from a table,and edit a text box ?
183. What is the difference between test fusion reports and test results in QTP ?
184. What is the difference between Shared Repository and Per Action Repository ?
185. When there are repeatable steps in multiple scripts, what do you do in QTP ?
186. What to do if the tree view of the application is not recognised by the QTP ?
187. How to open notepad without recording nor by running SystemUtil.Run command ?
188. What are the new features available in QTP 11 compared with earlier versions ?
189. What is the difference between debug modes (Stepinto, Stepout, and Stepover) ?
190. During test run option “Run from Step” is not launching browswer window, why ?
191. What are compiled modules ? What is your experience in writing compiled module ?
192. What is synchronization ? What is its relevance with respect to automated tests ?
193. During test execution if error occurs, how to find the object that caused error ?
194. What is the use of command tab in Debug viewer ? Can we execute user defined queries
195. How to change the Object Repository Mode at run time ? i.e., from Shared to PerAction.
196. What are the advantages and disadvantages of global data sheet and local action sheet ?
197. How can an object from a per action repository be called to another per action repository ?
198. What is the size limit for shared object repository ? What would you do if limit is exceeded ?
199. What are the 10 QTP functions that you have frequently ? Explain each of the functions briefly.
200. What are the advantages and disdavantages of shared object repository and per action repository ?
201. What are the challenges you faced with test automation using QTP ? How did you overcome challenges ?
202. How to run multiple instances of an application and how to differentiate 2 instances via QTP script ?
203. How to select particular value from a combo box in current page that was entered in the previous page ?
204. Winrunner and QTP are 2 test automation tools and now from the same company ? Why 2 tools from same company ?
205. Is it possible to change from Shared Object Repository to Per Action Repository and vice verse ? If yes how ?
206. What would be your approach to test a page that displays random questions and s change the order of display ?
207. When tests are run as batch, QTP shows results for last action only, so how to get results for each action of every script ?
208. Do you have any experience in test automation for SAP ? If yes, what are the challenges you faced and how you overcame them ?
209. What are the differences in exception handling between QTP and winrunner ? Which tool provides better exception handling facility ?
210. Do you have any experience in test automation for Mainframe ? If yes, what are the challenges you faced and how you overcame them ?
211. Incase Global Data sheet contains 0 (zero) records and Local Datasheet contains 4 rows of data. How many times will the test iterate ?
212. On trying to record report generation, report is opened in a new window but QTP does not recognize new window at run time, how to make it work ?
213. How to recognize Flex objects using QTP ? When script is recorded, it takes all objects as winobjects whether they are checkboxes or hyperlinks ?
214. External data is imported to datatable of QTP at run time. In this case, how to set number of iterations for first 10% of the rows in the datatable only, how do we set that in run time ?
215. How to instruct QTP to display errors and ther description in the test results instead of halting execution by throwing error in the mid of execution due to an error(for example Object not found) ?
216. How to identify an object from a list of objects that are dynamically generated ? For e.g. on entering 5 in a text box and clicking “Go” button, 5 Dropdown boxes are displayed. How to select value from a particular dropbox ?

Monday 24 December 2012

QTP Scripts


(1)File locating Show Date & Time


Set f1 = CreateObject("Scripting.FileSystemObject")
Set f2 = f1.GetFile("E:\Lak.txt")
S = "File was Created on: "&f2.DateCreated
Msgbox S
####################################################

(2)Folder locating Show Date & Time

Set f1 = CreateObject("Scripting.FileSystemObject")
Set f2 = f1.GetFolder("E:\Lak")
S = "Folder was Created on: "&f2.DateCreated
Msgbox S
######################################################

(3)Counts the sub folders

Set a = CreateObject("Scripting.FileSystemObject")
Set b = a.GetFolder("D:\ssm")
Set c = b.SubFolders
For Each d in c
e=e&d.name&vbnewline
Next
msgbox e

########################################################

(4)Count the Check box in a Page

Set a=Description.Create
a("html tag").value="input"
a("type").value="checkbox"

Set b=Browser("Forms : Check Box - HTML").Page("Forms : Check Box - HTML").childobjects(a)
c=b.count
msgbox c

For i=0 to c-1
b(i).set "on"
Next


(5)Count the RadioButton in a Page(True or False)

Set a=Description.Create
a("html tag").value="input"
a("type").value="radio"

Set b=Browser("Forms : Check Box - HTML").Page("Forms : Radio Button -").childobjects(a)
c=b.count
msgbox c

For i=0 to c-1
b(i)
Next


(6)Creating New Notepad and Write the Data

Set obj=createobject ("scripting.filesystemobject")
Set notepad=obj.createtextfile("e:\\abc.txt")
notepad.writeline("hi sijil")
notepad.writeline("welcome to my blog")


(7)Creating a Folder

Set obj=createobject ("scripting.filesystemobject")
Set folder=obj.createfolder("e:\\kk")


(8)Creating a Folder include a Notepad Data

Set obj=createobject ("scripting.filesystemobject")
Set folder=obj.createfolder("e:\\abc")
Set notepad=obj.createtextfile("e:\\abc\script.txt")
notepad.writeline("hi")
notepad.writeline("welcome to my blog")


(9) Message Box will close by itself in 10seconds so dont click on OK button

Set a=createobject("wscript.shell")
msgbox_message="Message Box will close by itself in 10seconds so dont click on OK button"
msgbox_time="10"
msgbox_title="Testing"
a.popup msgbox_message,msgbox_time,msgbox_title

(10) Script to get count,names of all open browsers and to close them.

Set b=Description.Create
b("micclass").value="Browser"
Set obj=Desktop.ChildObjects(b)
msgbox obj.count
For i=0 to obj.count-1
c=obj(i).getroproperty("name")
msgbox(c)
obj(i).Close
Next

#####################################################################

(11) “Message Box” and “Browser” will close by itself in 10seconds so don't click on OK button

Set a=createobject("wscript.shell")
Set b=Description.Create
b("micclass").value="Browser"
Set obj=Desktop.ChildObjects(b)
For i=0 to obj.count-1
msgbox_message="Message Box and Browser will close by itself in 10seconds so dont click on OK button"
msgbox_time="10"
msgbox_title="Testing"
a.popup msgbox_message,msgbox_time,msgbox_title
obj(i).Close
Next


(12) To Count No. Of Links in WebPage(“A” or “a”[rep hyperlink])

set objlink = description.create
objlink("html tag").value = "A"
set n = browser("Google").page("Google").childobjects(objlink)
c = "Total Links are: "&n.count
msgbox c


(13)To Show the Tool Tip on a Page(Checkbox)

///////////Browser("Google").Page("Google").Link("Images").Click
a=Browser("Google").Page("Google").WebEdit("name:=q").Object.title
msgbox a

(14)To Show the “Links” Tool Tip on a Page

//////Browser("Google").Page("Google").WebEdit("q").Submit
c=Browser("Google").Page("Google").Link("name:=definition").object.title
msgbox c

(15)To Show the “Image” Tool Tip on a Page

b=Browser("Web Templates - Flash").Page("Web Templates - Flash").Image("src:=http://www.templatesbox.com/data/premium.templates/images/full_site/thumbnails/12293353720Zf/12293353720Zf.jpg").getROProperty("alt")
msgbox b
//////////Browser("Web Templates - Flash").Page("Web Templates - Flash").Link("Full Site").Click

(16) To Show Current Date,Time and Date Only

msgbox now
msgbox time
msgbox date

(17)Creating a Word pad and Write the Data

Dim obj
Set obj=Createobject("word.application")
obj.Documents.add
obj.selection.typetext"Welcome"
obj.activedocument.saveas"d:\test.doc"

(18)Creating a Excelsheet and Wirte the Data

Set Excel=createObject("Excel.Application")
Set ExcelSheet=createObject("Excel.sheet")
ExcelSheet.Application.visible=true
Excel.ActiveSheet.cells(1,1).value=1111
Excel.ActiveSheet.cells(1,2).value=2222
Excel.ActiveSheet.cells(2,1).value=3333
Excel.ActiveSheet.cells(2,2).value=4444
ExcelSheet.SaveAs "d:\1.xls"

(19)Taking Value From Excel Sheet with Example

Browser("AutoPallet/AutoLoader™").Page("AutoPallet/AutoLoader™").WebButton("Login").Click

Set ex=createobject("Excel.Application")
Set a=ex.workbooks.open("D:\1.xls")
Set b=a.worksheets("Sheet1")
Dim login
For i=1 to 5
login="UserName: "&b.Cells(i,"A").value
msgbox login
Next
Browser("AutoPallet/AutoLoader™").Page("AutoPallet/AutoLoader™").WebEdit("liUSR").Set "admin"
dim pwd
For i=1 to 5
pwd="Password: "&b.Cells(i,"B").value
msgbox pwd
Next
Browser("AutoPallet/AutoLoader™").Page("AutoPallet/AutoLoader™").WebButton("Login").Click

(20)Counts the value from Excelsheet(initially create a excelsheet with Value)

DataTable.Import("c:\1.xls")
DataTable.SetCurrentRow("1")
For login_id=1 to 3
a=DataTable.Value("login_id")
msgbox a
DataTable.SetNextRow
Next



(21)Creating a Notpad and Write some data

Set f=createobject("scripting.filesystemobject")
Set f1=f.createtextfile("c:/file1.txt")
f1.writeline"aaa bbb"
f1.writeline"ccc ddd"
f1.writeline"eee fff"
f1.writeline"ggg hhh"
f1.writeline"iii jjj"
(22)Display Random Number

x=randomnumber.Value(0,100)
msgbox(x)
(23)Creating a Folder

Set obj=createobject ("scripting.filesystemobject")
Set notepad=obj.createfolder("c:\abc")

(24)Time out Messagebox

Set a=createobject("wscript.shell")
msgbox_message="Message Box will close by itself in 10seconds so dont click on OK button"
msgbox_time="10"
msgbox_title="Testing"
a.popup msgbox_message,msgbox_time,msgbox_title

(25)Value taken from Excel Sheet without Importing

path_of_Excel = "c:\1.xls"
sheet_of_Excel = "sheet1"
row_of_Excel = 1
column_of_Excel = 1
Function value_from_Excel(Excel_path,esheet,erow,ecolumn)
Set excel_object = createobject("Excel.Application")
excel_object.workbooks.open Excel_path
Set my_sheet = excel_object.sheets.item(esheet)
value= my_sheet.cells(erow,ecolumn)
excel_object.application.quit
value_from_Excel=Value
End Function
msgbox value_from_Excel(path_of_Excel, sheet_of_Excel, row_of_Excel ,column_of_excel)

(26)Passing Value From Data table to Notepad(initially create a notepad)

Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Sync
Window("Notepad").Activate
Window("Notepad").Move 352,319
Window("Notepad").WinEditor("Edit").Type "a"
Window("Notepad").WinEditor("Edit").Type micReturn
rc = DataTable.Value("A",dtGlobalSheet)
msgbox rc
Window("Notepad").WinEditor("Edit").SetCaretPos 0,0
Window("Notepad").WinEditor("Edit").Type rc

(27) To Get the Background Color

Var=Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Object.bgcolor
msgbox Var

(28)Create and Store Data into Simple XML File

Set doc = XMLUtil.CreateXML( )
doc.CreateDocument "Values"
Set root = doc.GetRootElement( )
root.AddChildElementByName "variable",""
Set node=root.ChildElements()
Set node=node.item(node.count)
node.AddChildElementByName "name","601A4"
doc.SaveFile "e:\data.xml"

(29)PLSQL Procedure(PLEASE CHECK)

http://www.qaforums.com/cgi-bin/forums/ultimatebb.cgi?ubb=next_topic;f=20;t=006805;go=newer

Public Function sqlRunStoredProcedure (sSProcName, sParameter1, sParameter2, sParameter3)
Set oADO_CMD = CreateObject("ADODB.Command") ' Create the database object
sConnectionStr = Environment("SQL_ConnectionStr") 'Get connection string
oADO_CMD.ActiveConnection = sConnectionStr ' Activate the connection
oADO_CMD.CommandType = 4 ' Set the command type to Stored Procedures
oADO_CMD.CommandText = sSProcName ' Set the command type to Stored Procedures
oADO_CMD.Parameters.Refresh ' Define Parameters for the stored procedure
If "" <> sParameter1 Then
oADO_CMD.Parameters(1).Value = sParameter1 ' Pass FIRST input value [optional]
If "" <> sParameter2 Then
oADO_CMD.Parameters(2).Value = sParameter2 ' Pass SECOND input value [optional]
If "" <> sParameter3 Then
oADO_CMD.Parameters(3).Value = sParameter3 ' Pass THIRD input value [optional]
End If
End If
End If
oADO_CMD.Execute() ' Execute the stored procedure
Set oADO_CMD = Nothing 'Clean up objects
End Function





(30)Creating Perfect XML

Dim objWriter,XmlWriter
Set objWriter = DotNetFactory.CreateInstance("System.Xml.XmlWriter","System.Xml")
set XmlWriter=objWriter.Create("e:\Desktop1234.xml")
XmlWriter.WriteStartElement("Books")
XmlWriter.WriteStartElement("Author")
XmlWriter.WriteAttributeString "Name","“Mohan"
XmlWriter.WriteEndElement()
XmlWriter.WriteStartElement("Title")
XmlWriter.WriteAttributeString "Title1","QTP"
XmlWriter.WriteEndElement()
XmlWriter.WriteFullEndElement()
XmlWriter.close()
Set objWriter =Nothing

(31)Simple creating a file and Read the File

Set oFile = DotNetFactory.CreateInstance("System.IO.File")
oFile.WriteAllText "e:\Test.txt","DotNetFactory works great!!"
strContents = oFile.ReadAllText("e:\Test.txt")
MsgBox strContents,,"File Contents"
Set oFile = Nothing

(32) To get count,names of all open browsers and to close them.

Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Image("Sign-In").Click 21,11
Set b=Description.Create
b("micclass").value="Browser"
Set obj=Desktop.ChildObjects(b)
msgbox obj.count
For i=0 to obj.count-1
c=obj(i).getroproperty("name")
msgbox(c)
obj(i).Close
Next

(33) To Search Particular Value in a Excel Sheet

Set appExcel = CreateObject("Excel.Application")
appExcel.visible=true
Set objWorkBook = appExcel.Workbooks.Open ("c:\1.xls")
Set objSheet = appExcel.Sheets("Sheet1")
With objSheet.UsedRange
Set c = .Find ("user1")
For each c in objSheet.UsedRange
If c="user1" then
c.Interior.ColorIndex = 38
End If
Set c = .FindNext(c)
next
End With

'objWorkBook.save
'objWorkBook.close
'set appExcel=nothing

(34)To OpenFileDialogBox

Set fd=DotNetFactory.CreateInstance("System.Windows.Forms.OpenFileDialog","System.Windows.Forms")
fd.Filter="txt files (*.txt)|*.txt |All files (*.*) |*.*"
fd.FilterIndex=2
fd.ShowDialog()
msgbox fd.FileName

(35) Script for copying a file from One Folder to Another Folder in QTP

Dim f
Set f = CreateObject("Scripting.FileSystemObject")
f.CopyFile "C:\1.xls", "E:\"
Msgbox "File Copied"


(36) The code to copy the contents of a sheet in one excel to another excel sheet

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook1= objExcel.Workbooks.Open("C:\1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("C:\2.xls")
objWorkbook1.Worksheets("Sheet1").UsedRange.Copy
objWorkbook2.Worksheets("Sheet1").Range("A1").PasteSpecial Paste =xlValues
objWorkbook1.save
objWorkbook2.save
'objWorkbook1.close
'objWorkbook2.close
set objExcel=nothing

(37) Comparing two Excel Sheets

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook1= objExcel.Workbooks.Open("C:\1.xls")
Set objWorkbook2= objExcel.Workbooks.Open("C:\2.xls")
Set objWorksheet1= objWorkbook1.Worksheets(1)
Set objWorksheet2= objWorkbook2.Worksheets(1)
For Each cell In objWorksheet1.UsedRange
If cell.Value <> objWorksheet2.Range(cell.Address).Value Then
cell.Interior.ColorIndex = 3
Else
cell.Interior.ColorIndex = 0
End If
Next
set objExcel=nothing

(38) Log on Session Information

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

Set colItems = objWMIService.ExecQuery("Select * from Win32_LogonSession")
For Each objItem in colItems
MsgBox "Authentication Package: " & objItem.AuthenticationPackage
MsgBox "Logon ID: " & objItem.LogonId
MsgBox "Logon Type: " & objItem.LogonType
MsgBox "Start Time: " & objItem.StartTime
Next



(39) List the File System Type

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colDisks = objWMIService.ExecQuery("Select * from Win32_LogicalDisk")
For Each objDisk in colDisks
MsgBox "Device ID: "& vbTab & objDisk.DeviceID
MsgBox "File System: "& vbTab & objDisk.FileSystem
Next

(40) List a Specific Set of Files

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = objWMIService. _
ExecQuery("Select * from CIM_DataFile where FileSize > 1000000")
For Each objFile in colFiles
MsgBox objFile.Name & " -- " & objFile.FileSize
Next

(41) List Detailed Summary Information for a File

Set objShell = CreateObject ("Shell.Application")
Set objFolder = objShell.Namespace ("E:\rec")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim arrHeaders(13)
For i = 0 to 13
arrHeaders(i) = objFolder.GetDetailsOf (objFolder.Items, i)
Next
For Each strFileName in objFolder.Items
For i = 0 to 13
If i <> 9 then
MsgBox arrHeaders(i) _
& ": " & objFolder.GetDetailsOf (strFileName, i)
End If
Next
Next

(42) List Summary Information for a Set of Files

Const FILE_NAME = 0
Set objShell = CreateObject ("Shell.Application")
Set objFolder = objShell.Namespace ("C:\Work BPO")
For Each strFileName in objFolder.Items
MsgBox "File name: " & objFolder.GetDetailsOf _
(strFileName, FILE_NAME)
Next

(43) Compress a Folder

strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFolders = objWMIService.ExecQuery _
("Select * from Win32_Directory where name = 'c: \\new'")
For Each objFolder in colFolders
errResults = objFolder.Compress
Next
(44) 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)

(45) Count number of rows in Excel without opening it.

Set objExcel=CreateObject("Excel.Application")
Set objWB=objExcel.WorkBooks.Open("C:\abc.xls")
Set objSheet=objWB.WorkSheets(1)
msgbox objSheet.usedrange.rows.count
Set objExcel=Nothing

(46) Find the highest number in the array
 
Dim num, i, Length1

num=array(34,12,98,43,89,49,56)
Length1 = UBound(num)    'Find the length of array

For i= 1 to Length1
 If (num(i)>num(0)) Then
    num(0)=num(i)
 End If
Next

MsgBox num(0) 'Highest Number

Arrays in QTP - Part 2


Dynamic Arrays:-

A dynamic array, also called resizable array is a variable-size array that allows elements to be added or removed at runtime. Dynamic arrays are useful when size of the array cannot be determined at the time of decleration.


Dynamic or Variable Sized Array
    2.1. Single dimentional Dynamic Array
    2.2. Multi-dimentional Dynamic Array

Dim myArray()  'create a dynamic array.



It creates an array, which can be resized at runtime. For initial use, it must be initialized with some value i.e. size

This will be done using ReDim.

ReDim myArray(3)   'before using first time

Now you can assign values to array

myArray(0)=43
myArray(1)=90
myArray(2)=34
myArray(3)=76

Dynamic array can be resized n number of times, but remember, if you resize it again using ReDim, all its previous data will lost.
For that purpose, Preserve is used with ReDim.

ReDim Preserve myArray(5)

myArray(4)=67
myArray(5)=82

ReDim Preserve resize the array by keeping existing data safe!!




Dynamic arrays can be Multidimensional but only one of the dimensions (the 'right side') can be changed. Refer the below code..


Dim myArray()
Redim myArray(1,0)
myArray(0,0) = "John"
myArray(1,0) = 21
msgbox (ubound (myArray, 2)) '0
Redim preserve myArray(ubound (myArray, 1), ubound (myArray, 2) + 1)
myArray(0,1) = "Bob"
myArray(1,1) = 21
msgbox (ubound (myArray, 2)) '1

So point to be noted about Dynamic Arrays:-

(i) -   Dynamic Arrays are variable-size arrays that allows elements to be added or removed at runtime

(ii) -  Dynamic Arrays are useful when size of the array cannot be determined at declaration time
  
(iii) - Dynamic Arrays must be initialized with some value i.e. size before using first time

(iv) - Dynamic Arrays can be resized n number of time

(v) - 'Preserve' must be used with ReDim to keep the existing data of Dynamic Arrays

Arrays in QTP - Part 1


Hello Friends! In this post, we'll brush-up our understanding about vbscript arrays and to use arrays in QTP.


What is an Array?

- An array variable is used to store multiple values in a single variable.

- Array can contain a series of values of same data type.

- An array is a memory space referred by a common name.


Please note that VBScript explicitly supports only one data type - ‘Variant’. A variant can store a number as well as a string.

Arrays are of two types..


1. Static or Fixed Sized Array
2. Dynamic or Variable Sized Array


Both type of arrays can be of single dimensional or multi-dimensional. So to make the things simple, we can write this like...


1. Static or Fixed Sized Array
 
    1.1. Single dimensional Static Array   'Exp - Dim myArray(4)
    1.2. Multi-dimensional Static Array   'Exp - Dim myArray(3,4)


2. Dynamic or Variable Sized Array

    2.1. Single dimensional Dynamic Array
    2.2. Multi-dimensional Dynamic Array


Sounds batter? Okey.. great!!


Dim myArray(4)    'declaring array in vbscript


In the above example, an array containing 5 elements is declared:


But why 5? The number shown in the parentheses is 4!!

Ya! But array index actually starts from zero, so this array contains 5 elements. This is a fixed-size array.


You assign data to each of the elements of the array like this:

myArray(0)= 21
myArray(1)= 42
myArray(2)= 51
myArray(3)= 33
myArray(4)= 15


It was one way of declaring and assigning values to an array.
Here is the another way...

Dim myArray
myArray = Array(21,42,51,33,15)   'integer values
myArray = Array("val1","val2","val3","val4","val5")   'string values

It was the VBScript Array Method of Creating Arrays.

Array we have discussed above is Static Array - Single dimensions. A Static Array -

- has a pre-defined number of elements.
- size of a static array cannot be altered at run time.

Multiple dimensions are declared by separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 5 rows and 7 columns:

Dim myArray(4,6)

In the above example, an array containing 5 rows and 7 columns has been declared.

Calculating the Size of Arrays:

ubound method is used to count the length of array. It returns the highest index number of the array.
But remember, the actual size of the array is highest index number plus one!! (since the array starts at index number 0).

Dim myArray(4),len1
len1 = ubound(myArray) '4
msgbox len1+1   '5


ubound method can be used to count the size of a multidimensional array also, but this time it's slightly different..

The dimension number needs to be included in ubound.

Dim myArray(4,6)
msgbox ubound(myArray, 1) 'It''' give highest index of the first dimension - 4
msgbox ubound(myArray, 2) 'It''' give highest index of the second dimension - 6

Tired! me too...!!

Please post your comments and tell me how you find this site!!

Sendkeys Method - Keyboard Oprations in QTP


Hello Friends!

In this post we'll learn how to perform keyboard operation in QTP using vbscript.

What's the need of Sendkeys?


Hmmm... ok.. Refer the blow code.

Set oShell = CreateObject("WScript.Shell")
SystemUtil.Run "D:\ProgramFiles\MercuryInteractive\QuickTestProfessional\samples\flight\app\flight4a.exe"
Dialog("text:=Login").WinEdit("attached text:=Agent Name:").Click
oShell.SendKeys "john"
Dialog("text:=Login").WinEdit("attached text:=Password:").Click
oShell.SendKeys "wrong "
Dialog("text:=Login").WinButton("text:=OK").Click

Copy this code in QTP and run it.

Okie.. Now you can see, because we have entered incorrect password, following error dialog will be displayed.






Now we need to close error dialog and enter correct password in the login window.

If do this using DP code, we need to get the properties of error window and write one more line of code.

Dialog("text:=Flight Reservations").WinButton("text:=OK").Click



Instead of addind more objects in our code and writing extra lines for this, we can simply press escape key (ESC) from keyboard and our job is done!!

How can we do that using QTP?


All you need to do is, create a Wscript object and then you can use Sendkeys for that purpose.

Set oShell = CreateObject("WScript.Shell")
oShell.SendKeys "{ESC}"

Done!!


This thing is very useful when application have no automation interface. And it's quite fast as well. Depends on the need.



Most keyboard characters are represented by a single keystroke. Some keyboard characters are made up of combinations of keystrokes (CTRL+SHIFT+HOME, for example).

Please note:-

- To send a single keyboard character, send the character itself as the string argument. For example,
- To send the letter x, send the string argument "x".
- To send a space, send the string " ".
- You cannot send the PRINT SCREEN key {PRTSC} to an application.



Examples:

  • oShell.SendKeys "{ESC}"    - press escape key
  • oShell.SendKeys "john"    - type john
  • oShell.SendKeys "+^{ESC}"    - press Ctrl + Shift + Esc keys (open Windows Task Manager)
  • oShell.SendKeys "%{F}"    - press Alt + F key (open file menu)


For details of all the characters, please refer the following table.



In case of any queries, please post your comments.

Tuesday 18 December 2012

Run Error: Cannot identify object??

This error indicates that there is no object in the current view of the application that matches the description saved in the object repository for the object.
This error occurs in one of two basic situations:
  • The object is not (or not yet) displayed in the application at the time of the error.
  • The object is present, but the description in your application has changed so that it no longer matches the test object description that QuickTest is using to identify the object.

Run Error: The object is not unique


More than one object within the specified parent object has the same property values as those specified in the test object description for this object.
Determine whether the problem is with an individual object in your application, or whether the same problems apply to all or many of the objects in your application with the same object class.

Run Error: Parent not found

Each object in your component is identified relative to its parent objects.
If you received a Parent not found message, try one of the following solutions:
  • Fix the object description of the problematic parent object using the suggestions below
    • If you find that an object in your component has one or more property values in its description that differs from the corresponding object property in your application, determine whether the problem is with an individual object in your application, or whether the same problems apply to all or many of the objects in your application with the same object class.
  • Find all instances of the old hierarchy in the Expert View and replace it with the correct object hierarchy as described below

Re-recording an Object to Identify Parent Object Description Problems

Follow the instructions below to identify a problem with a parent object.
To identify a problem with a parent object by re-recording the child object:
  1. Open your browser or application to the page containing the object that caused the error.
  2. Select the last step in the component in the Keyword View or place the cursor below the last statement in the Expert View.
  3. Click the Record button or choose Automation > Record.
  4. Click or perform another operation on the object.
  5. Click the Stop button or choose Automation > Stop.
  6. Right-click the new step and select Object Properties.
  7. In the Object Properties dialog box, click Repository. The Object Repository opens with the new object selected. Note the parent hierarchy of the new object.
  8. Find the old (problematic) object in the Object Repository and compare the parent hierarchy of the old object with that of the new object.
Check to see whether the differences are due to one or more parent objects with different descriptions, or whether the actual objects in the parent hierarchy are different.
    • If you find a problem with a parent description, try to fix it using the suggestions for Solving Object Description Problems.
    • If the problem stems from a different set of parent objects in the hierarchy, find all instances of the old hierarchy and replace it with the new object hierarchy as described in the example below.
Example:
Suppose that on a Web site with frames, you recorded a step on an Image object named Poster. In the Object Repository window, you can see that Image object's hierarchy is similar to the following (the object class is listed in parentheses for this example):
MyCompany (Browser)
MyCompany (Page)
Main (Frame)
Poster (Image)
When you later run the component, the Web page looks the same, but you receive a Cannot Identify Object error for the Poster image. When you re-record the step and view the Image object in the Object Repository window, the hierarchy might look like this:
MyCompany (Browser)
MyCompany (Page)
Poster (Image)
Now you can see that the frames have been removed from the Web page, so even though the Poster image still has the same object description, its parent hierarchy is different.
In the object repository, you can see that there are actually two different poster objects: the old one under the obsolete Frame object, and the new one directly under the MyCompany page.
To fix the problem, you can replace the object in the step by clicking Select another object and choosing the required object from the correct location in the hierarchy (tree).
To keep your Object Repository well-organized, you should also delete the obsolete objects from the Object Repository by right-clicking the obsolete object and selecting Delete.

Run Error: Cannot identify item


QuickTest cannot identify a list or tree item specified in a method argument.
Confirm that the specified item exists in the object.
  • If the object does not exist, delete the step or modify the item on which you want to perform the step.
  • If the item exists, its name may have changed. Modify the name as necessary or specify the item using the item's index (for example, "#4"). Note that different test objects and methods may use a different syntax for specifying an item's index.

Run Error: The object's item is not unique


Q: Why this error occurs??
More than one item in a list or tree item has the name specified in the method argument.
Specify the item using the item's index (for example, "#4"). Note that different test objects and methods may use a different syntax for specifying an item's index.

Run Error: Test run failed


Q: Run Error: Test run failed
The run session cannot continue due to an unknown error. Check the step where the failure occurred.
If your component failed while referring to an external file, such as an associated function library, check that the files are accessible from your computer and that the files are saved in the appropriate format.
If your component failed while performing a QuickTest step in a function, refer to the QuickTest Object Model Reference for more information on appropriate usage of the function in your statement.
If your component failed while performing a standard VBScript step in a function, refer to the Microsoft VBScript Reference.

How to use Watch in QTP?


You can view the current value of any variable or VBScript object in your function library by adding it to the Watch tab. As you continue stepping into the subsequent steps in your function library, QuickTest automatically updates the Watch tab with the current value for any object or variable whose value changes. You can also change the value of the variable manually when the function library pauses at a breakpoint.
To add an expression to the Watch tab:
Perform one of the following:
  • Click the expression and choose Debug > Add to Watch
  • Click the expression and press Ctrl+T
  • Right-click the expression and choose Add to Watch from the context menu
  • In the Watch tab, paste or type the name of the object or variable into the Name column and press Enter to view the current value in the Value column
Note: You can add an expression to the Watch tab from a function library (and not from a business component).
Tip: You can also use the Variables tab to view the current values for all variables up to the current step in the function library.

Handling Run Errors in QTP

The Run Error message box displayed during a run session offers a number of buttons for dealing with errors encountered:

  • Stop—Stops the run session.
    The run results are displayed if QuickTest is configured to show run results after the run.
  • Retry—QuickTest attempts to perform the step again.
    If the step succeeds, the run continues.
  • Skip—QuickTest skips the step that caused the error, and continues the run from the next step.
  • Debug—QuickTest suspends the run, enabling you to debug the component and any associated function library that contains a function called by the component.
You can perform any of the debugging operations described in this section. After debugging, you can continue the run session from the step where the component or function library stopped, or you can use the step commands to control the remainder of the run session.
  • Help—Opens the QuickTest troubleshooting Help for the displayed error message. After you review the Help topic, you can select another button in the error message box.
  • Details—Expands the message box to display additional information about the error.

Sunday 16 December 2012

Excel interview questions

Working with Excel Sheets - create, open, modify, save, close!!
Getting value from an existing excel sheet Dim oExcel, oWB, oSheet, getVal Set oExcel=CreateObject("Excel.Application") Set oWB=oExcel.Workbooks.Open("C:\sri.xls") Set oSheet=oWB.WorkSheets("Sheet1") oExcel.Visible=TRUE getVal=oSheet.Cells(1,1).Value print getVal oWB.Close Set oExcel=Nothing Inserting value to an existing excel sheet Dim oExcel, oWB, oSheet, setVal Set oExcel=CreateObject("Excel.Application") Set oWB=oExcel.Workbooks.Open("C:\sri.xls") Set oSheet=oWB.WorkSheets("Sheet1") oExcel.Visible=TRUE setVal="ValueInserted" oSheet.Cells(4,1).Value=setVal print getVal oWB.Save oWB.Close Set oExcel=Nothing Create a new excel sheet, insert values and save it.. Dim oExcel, oWB, oSheet, setVal Set oExcel=CreateObject("Excel.Application") Set oWB=oExcel.Workbooks.Add Set oSheet=oWB.WorkSheets("Sheet1") oExcel.Visible=TRUE setVal="ValueInserted" oSheet.Cells(4,1).Value=setVal print getVal oWB.SaveAs("C:\sri.xls") oWB.Close Set oExcel=Nothing
Working with Excel Sheets - Add new sheet
This code demonstrate how to add new sheet to existing excel file and rename it at runtime
Dim oExcel, oWB,oSheet, getVal
Set oExcel=CreateObject("Excel.Application")
oExcel.visible=True
oExcel.DisplayAlerts= False   'this will not allow alerts to be displayed
Set oWB=oExcel.Workbooks.Open("C:\sri.xls")
Set oSheet1=oWB.Sheets.Add  'a new sheet is added with default name i.e.Sheet4 etc.
oSheet1.Name="QTPSchools" 'rename newly added sheet
oSheet1.cells(1,1).value="Welcome" 'enter value 
oWB.Save
oWB.Close
Set oExcel=Nothing

Using excel sheet as database table

Excel sheet can be used as a database for the parameterization purpose. Following code demonstrate how to connect and consider excel sheet as database table.
This might be usefull while working with databases. You can export database table into excel (one time) and then work on excel as database.
Dim objCon, objRecordSet, strExlFile, colCount, row, i Set objCon = CreateObject("ADODB.Connection") Set objRecordSet =CreateObject("ADODB.Recordset") strExlFile = "C:\abhikansh.xls" objCon.Open "DRIVER={Microsoft Excel Driver(*.xls)};DBQ=" &strExlFile & ";Readonly=True" strSQLStatement = "SELECT * FROM [Sheet2$]" objRecordSet.Open strSQLStatement, objCon 'create recordset colCount = objRecordSet.Fields.count    'No of columns in the table While objRecordSet.EOF=false     row=""     For i=0 to colCount-1         row=row&"    "& objRecordSet.fields(i)     Next         Print row     objRecordSet.moveNext Wend Set objRecordSet = Nothing objCon.Close Set objCon = Nothing
Screen-shots of sample excel and output are following
-
Following code demonstrate how to count number of rows inExcel without opening it - using vbscipt in QTP.
 Set objExcel=CreateObject("Excel.Application")
Set objWB=objExcel.WorkBooks.Open("C:\abc.xls")
Set objSheet=objWB.WorkSheets(1)
msgbox objSheet.usedrange.rows.count
Set objExcel=Nothing
1)Find the 'String' from excel sheet and save to another sheet.But we 
  don't know the string column number and row number?
Option explicit
Dim exo, wbo, wso1, wso2, nor, noc, i, j, x, y
'Open a Excel file
Set exo=CreateObject("excel.application")
exo.Visible=true
Set wbo=exo.Workbooks.Open("C:\sample.xls")
Set wso1=wbo.Worksheets("sheet1")
Set wso2=wbo.Worksheets("sheet2")
nor=wso1.usedrange.rows.count
noc=wso1.usedrange.columns.count
'Varifying excel sheet strings
For i=1 to nor step 1
 For j=1 to noc step 1
  x=wso1.cells(i,j)
  x=cstr(x)
  If strcomp(x,"Testing")=0 Then
   wso2.cells(1,1)=x
  End If
 Next
Next
'Close excel s/w and Destroy the objects
exo.Quit
Set wso1=Nothing
Set wso2=Nothing
Set wbo=Nothing
Set exo=Nothing