Thursday, 16 July 2015

QTP REAL TIME VERY IMP SCRIPTS FOR EXPERTS PART2


18. How to  Open an existing word file      

 Steps:
Create object using word application
Make the object visible
Open a new word file with help of open  method

set word = createobject("word.application")
word.visible=true
Word.Documents.Open("C:\Documents and Settings\sachin\My Documents\abc.docx")

 
1 - How to launch a QTP application, open a new test and close QTP through a   
     script.

 Steps:

Declaring the variable

Creating the object for qtp application

Invoke the qtp

Open new test with help of qtp application object

Make qtp application applicable

Relesing the qtp app object

 

Write the code in a notepad file and save with .vbs extension.

 For Execution double click the file



 2 - How to get data from Excel into QTP without importing the Excel.            

 Steps:

Assign the path of excelfile to variable
Assign  the 1 to row,column variables
Declare the function for excel by passing the path,sheet,row,column
Create an object of excel
Open the path of excel file by using workbooks object
Assign the sheet data to variable
Closing the excel object
Relese the excel object
Close the function
Using msgbox function we can view the variables


For this code make sure that you have excel file Book1.xls under c:\ and write some dummy values in its first few cells.

Write the whole above code in a new test in QTP and run it.

3 - How to launch QTP, open a test, run it, display results and close QTP.        



Lets first of all record a simple test and then we will run this test through a automated script.

1. Open QTP and a new blank test.

2. Click on Record. Record and Run Settings window will open. GO to Windows Applications tab and choose the first option "Record and run test on any open Windows-based application". Click Ok.

3. Go to Start-> All Programs-> QuickTest Professional->Sample Application-> Flight.

4. Login window opens.

5. Enter "sach" as Agent Name and "mercury" as Password. Click Ok.

6. Flight Reservation window opens. Go to File->Exit.

7. Save the Test. (I saved the test as Test3 at C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\Test3)

Steps:

Declaring the variables for qtpapp ooject,test object & result object

Creating the application object

Open the test in read only mode

Create the run result options object

Set the results  location
Run the test

Check the status

Relese the application object , test object , results object





  








4 - How to bring data from a text file into QTP data table.         

Steps:

Create object of FSO
Open the text file
Declare an array
Declare the variable by assigning the value 0
Specify the do until loop
Close the file
Export the data to excel sheet










17.How to  Open a new word file   


Steps:

Create object using word application
Make the object visible
Open a new word file with help of add method

set word = createobject("word.application")
word.visible=true
set doc = word.documents.add


5 - How to import excel into datatable in QTP.     


Steps:

Declare the application object variable
Create the application object
Launch the qtp
Open the test
Import the excel sheet data to first sheet of data table
Export the runtime datatable to excel sheet
Specify the qtp object visible
Relese the application object




 6 - How to pass output parameter's value of one test to input parameter of another test.       

 Steps:

' Open a new test and go to File->Settings, Parameters tab.
' Define an input parameter "inpar" as string with a default value of "Dvalue".
' Define one output parameter "outpar" as string.
Assign the input pars to output pars
Testargs("outpar")=Testargs("inpar")

msgbox TestArgs("outpar")
Steps:
' Open a new test and go to File->Settings, Parameters tab.
' Define an input parameter "inpar2" as string with a default value of "Dvalue2".
' write the below line of code in the Expert View of the test and save it as Test-p2
' under C:\Program Files\Mercury Interactive\QuickTest Professional\Tests.

msgbox testargs("inpar2")

' This below code is opening a test called Test-p1, setting its first input parameter to "Hello World" and running the test. Test-p1 is just assigning the input parameter to the output parameter when it is run and that output parameter is displayed in the messagebox. After that the value of the ouput parameter of the Test-p1 is being assigned to "val" so that it can be passed as input parameter to Test-p2. Test-p2 is just displaying the value of inpar2 which it got from Test-p1.







  15( 26) - How to run all tests in a specific folder in QuickTest professional (QTP)?    

 Steps:

Declare the variables for qtpobj,fsoobj,dir,testcollection
Create an object using filesysytemobject
Use the getfolder to returs a folder
Assign the subfolders to testcollcetion variable
Create the object using reunresultsoptions
Setting the location for the run results
Execute the test. Instruct QuickTest Professional to wait for the test to finish executing
Close the qtp by  using close method
Relese the application object,runresults object


'For this script I created three tests tr1, tr2 and tr3. In the Expert View of tr1 I wrote just one line - msgbox ("Test 1"), in the Expert View of tr2 - msgbox ("Test 2") and in the Expert View of tr3 - msgbox ("Test 3"). I went to C:\Program Files\HP\QuickTest Professional and created a folder named "tests1". I then moved folders tr1, tr2 and tr3 which belong to tests I created from C:\Program Files\HP\QuickTest Professional\Tests to tests1 folder (C:\Program Files\HP\QuickTest Professional\tests1) which I created above and gave the same path in the script. Now this code will run all the tests (3 in our case) in that folder.

Dim qtp_app
Dim file_sys
Dim Dir
Dim test_collection

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

' The file_systemObject object is used to access the file system on the server. This object can manipulate files, folders, and directory paths.
Set file_sys = CreateObject("Scripting.filesystemObject")

'GetFolder: Returns a Folder object for a specified path
Set Dir = file_sys.GetFolder( "C:\Program Files\HP\QuickTest Professional\tests1" )

Set test_collection = Dir.SubFolders

'RunResultsOptions:A collection of properties that indicate preferences for the run results.
Set qtResultsObj = CreateObject("QuickTest.RunResultsOptions")

For each t_folder in test_collection
qtp_app. Open t_folder.Path, True, False
'Setting the location for the run results
qtResultsObj.ResultsLocation = t_folder.Path & "\Res1" ' Set the results location
' Execute the test. Instruct QuickTest Professional to wait for the test to finish executing.
qtp_app.Test.Run qtResultsObj, True
qtp_app.Test.Close
Next
qtp_app.Quit
Set test_collection = Nothing
Set Dir = Nothing
Set file_sys = Nothing
Set qtp_app = Nothing

7 - How to copy data from Excel sheet to a Text file?       



A text file sample.txt exists in the C:\ drive. Sample.txt is opened in append mode which is 8. We use writeline to write each line into text file.

An Excel file Book1.xls exists in C:\ drive and it has some text in columns and rows of its sheet1. In the For loop we are transferring data from first three rows of excel sheet to a text file called sample.txt.




 8 - How to count and get the path & name of all the object repositories associated with an action ?  

Steps:

Declare the application object variable
Create the application object
Launch the qtp
Open the test
Retrive the object repositaries of collection of action1
Count the no of object repositary files in the collection
Returns the path of object repossitary file
Extract the obkect repositary file name
Getting the whole path in variable
Returh the specified no of chars
Relese the repositorys object , application object, testobject.
 9 - How to move data from a text file to excel sheet.        

 




10 - How to get all files and folders within a given folder?           

 Steps:

Create the file system object
Create the folder object by using get folder object
Assign the path property for specified file to variable
Create the object by using files property
Create the object by using subfolder property
Using msgbox we can view the data

11.(12) - How to get the count and name of all the Recovery Scenarios associated with the test?        
Steps:
Declare the variables for recovervariable,qtpapp ,array
Create object for qtp application
Open the test

Asign the qtptest recovery variable to recoveryvariable
By using if condition & using count method  write the logic
Relese the application object & recovery object


12 (16) - How to count total number of links on a web page?      


'You must use the Description object to create the programmatic description for the ChildObjects description argument. You cannot enter the programmatic description directly into the argument using the property:=value syntax.


Make sure www.google.com is open and write the below code in a new test and run it. It may show different results than mine, depending on the links on Google page at that time. I have shown my answer below.

Steps:
Create object using description object
Assign link to object using value method
Retrive the collection of all objects & assign to variable
Using msgbox function dispay the data present in variable

Code:
Set Des_Obj = Description.Create
Des_Obj("micclass").Value = "Link"
Set link_col = Browser("name:=Google").Page("title:=Google").ChildObjects(Des_Obj)
msgbox link_col.count

13 (17) - How to get link names and URLs for all the links on a web page?      

 Steps:
Create object using description object
Assign link to object using value method
Using child objects assign to variable
Assigning the data to variable by using child objects
Count the links by using the count function
Use for loop for repeting no of links
Use getroproperty  for capturing the name & url

Set Des_Obj = Description.Create
Des_Obj("micclass").Value = "Link"
Set link_col = Browser("name:=Google").Page("title:=Google").ChildObjects(Des_Obj)
a= link_col.count

For i=0 to a-1
tag = link_col(i).GetROProperty("name")
href = link_col(i).GetROProperty("url")
msgbox tag &" " & href
Next

14( 24) - How to run multiple tests in QuickTest professional (QTP) ?   

 Steps:

Declare the application object variable
Create the application object
Launch the qtp

Declare the array

Put the multiple tests in array
Create the results run object
Open the tests
Assign the tests to variables
Execute the test by using run method
Close the qtp using close method
Relese the application object, teset object


'This is just one of the ways of doing this. I created three tests tr1, tr2 and tr3. In the Expert View of tr1 I wrote just one line - msgbox ("Test 1"), in the Expert View of tr2 - msgbox ("Test 2") and in the Expert View of tr3 - msgbox ("Test 3").
'Write the below code in a text file and Save it with .vbs extension and run it.


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

Dim QTP_Tests(3)
QTP_Tests(1) = "C:\Program Files\HP\QuickTest Professional\Tests\tr1"
QTP_Tests(2) = "C:\Program Files\HP\QuickTest Professional\Tests\tr2"
QTP_Tests(3) = "C:\Program Files\HP\QuickTest Professional\Tests\tr3"

'Creating the RunResultsOptions object. It is a collection of properties that indicate preferences for the run results. E.g. ResultsLocation property as used below which tells the path in which the run results will be stored.

Set res_obj = CreateObject("QuickTest.RunResultsOptions")

For i = 1 to UBound (QTP_Tests)
App.Open QTP_Tests(i), True
Set QTP_Test = App.Test
res_obj.ResultsLocation = QTP_Tests(i) & "\Res1" ' Set the results location
'Using the Run method. Run Method runs the open test or business component and creates results in the specified file or Quality Center path. A Boolean value - true or false can be set. Indicates whether the Test.Run statement waits until the end of the run before performing the next statement in the automation script. Default=True.
QTP_Test.Run res_obj, True
QTP_Test.Close
Next
App.Quit
Set res_obj = nothing
Set QTP_Test = nothing
Set App = nothing

  
16   (XMLUtil-7:)) How to compare two XML files.

Steps:

Assign the xml file to variable
Load the first xml file
Assign the xml file to variable
Load the second xml file
Compare the xml files by using compare method and assigning result to variable
If the result variable is  having value 1 then document same otherwise not match
Below are the two xml files used. There is very small difference between these two XML files. Just try to understand how Compare method gives results. You can always change/modify the code according to your requirements.

XML file-1 - env.xml


XML file-2 - env1.xml






Using different XML files:

Set doc=XMLUtil.CreateXML
doc.LoadFile "C:\ENV.xml"
Set docx=XMLUtil.CreateXML
docx.LoadFile "C:\ENV1.xml"

res = docx.Compare(doc,resultDoc,micXMLValues+micXMLCDataSections)
msgbox resultDoc
if res = 1 then
msgbox "Documents match :)"
else
msgbox "do not match "
end if

Results of running the above code:

 



                                 


Using same XML files:

Set doc=XMLUtil.CreateXML
doc.LoadFile "C:\ENV.xml"
Set docx=XMLUtil.CreateXML
docx.LoadFile "C:\ENV.xml"
res = docx.Compare(doc,resultDoc,micXMLValues+micXMLCDataSections)
msgbox resultDoc
if res = 1 then
msgbox "Documents match :)"
else
msgbox "do not match "
end if

Results of running the above code:

 




 







19. How to  open a new word document and writing text to it and saving it

Steps:

Create object using word application
Make the object visible
Open a new word file with help of add method
Assign the word selection to variable
Write the text by using

set word = createobject("word.application")
word.visible=true
set doc = word.documents.add

Set objectSelection = Word.Selection
objectSelection.TypeText "This is sample text"
doc.saveas("c:\test.docx")


20.How to Appending text to a word file and saving it

'Opening an existing word document and appending text to it and saving it

Const END_OF_STORY = 6
Const MOVE_SELECTION = 0
set word = createobject("word.application")
word.visible=true
Word.Documents.Open "C:\Documents and Settings\sachin\My Documents\abc.docx"

Set objectSelection = Word.Selection
objectSelection.EndKey END_OF_STORY, MOVE_SELECTION
objectSelection.TypeParagraph()
objectSelection.TypeText "This is sample text"
objectSelection.TypeParagraph()
word.documents.save



21.How to Writing formatted text to a word file

'Writing formatted text to a word file

Const Red = 255

Set word = CreateObject("Word.Application")

word.Visible = True
Set objDoc = word.Documents.Add()
Set objectselection = word.Selection

objectselection.Font.color = Red
objectselection.Font.Name = "Arial"
objectselection.Font.Size = "18"
objectselection.Font.underline = True
objectselection.Font.italic = True
objectselection.Font.bold = True
objectselection.TypeText "This is sample text"
objectselection.TypeParagraph()
objectselection.Font.Size = "12"
objectselection.TypeText "This is sample text-2"
objectselection.TypeParagraph()

 22.How to Print a word file            

Steps:

Create object using word application
Open the desired document by using open method
Print the document by using printout method
Close the word document

Set word = CreateObject("Word.Application")
Set objectdocument = word.Documents.Open("c:\test.docx")
objectdocument.PrintOut()
word.Quit
 
24 - How Can I Add Additional Worksheets to an Excel Workbook?   

 Steps:

Create an object for excel application
Assign the visible property as true
Adding a sheet by using workbooks.add method & assigning to variable
Assigning sheet to variable
Adding to the excelsheet

This script adds the nine new worksheets directly after worksheet 1 (thus pushing sheets 2 and 3 to the end of the collection):

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)
Set colSheets = objWorkbook.Sheets
colSheets.Add ,objWorksheet,9

25 - How Can I Import an Excel Spreadsheet Into an Access Database?           


Const acImport = 0
Const acSpreadsheetTypeExcel9 = 8
Set objAccess = CreateObject("Access.Application")
objAccess.OpenCurrentDatabase "C:\Scripts\Test.mdb"
objAccess.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel9, _
"Employees", "C:\Scripts\Employees.xls", True
VBScript - How Can I Insert a Column into a Spreadsheet?            

 26 - How Can I Insert a Column into a Spreadsheet?

Here's a script that writes a column header to columns A, B, and C, then inserts a new, blank column between columns B and C:

Steps:

Create an object for excel application
Assign the visible property as true
Assign the worksheet using workbooks object
Assign the data  to cells using work sheet  methods
Using insert method insert data  by specifying
Const xlShiftToRight = -4161

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Cells(1,1) = "Dataset 1"
objWorksheet.Cells(1,2) = "Dataset 2"
objWorksheet.Cells(1,3) = "Dataset 4"
Set objRange = objExcel.Range("C1").EntireColumn
objRange.Insert(xlShiftToRight)

27 - How Can I Replace Text in an Excel Spreadsheet?  


Steps:

Create an object for excel application
Assign the visible property as true
Assign the excel file to the variable by using workbooks & open function
Focus on particular sheet by using workbook object
With the help of replace method we can replace  the text


Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\Test.xls")
Set objWorksheet = objWorkbook.Worksheets(1)
Set objRange = objWorksheet.UsedRange
objRange.Replace "C:\Test\Image.jpg", "C:\Backup\Image.jpg"

28 – How to Open an Excel Spreadsheet   

Steps:

Declare the variables
Create the object using excel application
Assign the excel file to the variable by using workbooks & open function


Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("C:\Scripts\New_users.xls")

No comments:

Post a Comment