Skip to main content

QTP Scripts examples...

1. Script for sending a mail using outlook express.

Dim objOutlookMsg,objOutlook
Set objOutlook = CreateObject(”Outlook.Application”)
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
objOutlookMsg.To = “”
objOutlookMsg.CC = “ “
objOutlookMsg.BCC = “”
objOutlookMsg.Subject = “test”
objOutlookMsg.Body = “”
objOutlookMsg.Attachments.Add “C:\Documents and Settings\Desktop\testreport.txt”
objOutlookMsg.Send

2. Script for opening a Notepad file.

In Expert view write a builtin funtion
invokeapplication”c:/whatever the path”
Run

Dim a
Set a = WScript.CreateObject (”WSCript.shell”)
a.run “notepad.exe”

Dim oShell
Set oShell = CreateObject (”WSCript.shell”)
oShell.run “cmd/notepad.exe”
Set oShell = Nothing

DsystemUtil.Run “Notepad.exe”

3. Script for connecting the oracle database

public void connectDB()
{
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adUseClient = 3
Set objCon=CreateObject(”ADODB.Connection”)
Set objRec=CreateObject(” ADODB.Recordset”)
objCon.Open “DRIVER={Oracle in OraHome92};SERVER={Servername};UID={Username};PWD={Password};DBQ={Dbnmae}”
objRec.CursorLocation = adUseClient
objRec.Open “Select {Col name} from tablename”,objCon,adOpenStatic,adLockOptimistic
While(objRec.EOF)
objRec.MoveNext
Msgbox ”Result” & objRec.Fields.Item(”{Col name}”)& vbCrLf
Wend
objRec.Close
objCon.Close
Set objRec=Nothing
Set objCon=Nothing
Msgbox “Executed Sucessfully”
}

Use code only that which is inside the function connectDB

4. Two ways to connect QC with QTP.

Connect manually

1. To connect to TD from QTP follow the steps…
2. Open Qtp ==> Tools ==>
3. Select TestDirector Connection ==>
4. In Server Connction Box Enter TD address(URL of TD) ==>
5. Click Connect==>
6. In project Connection Box Enter the Details Domain,Project,User name and Password ==>
7. Click Connect If you want to reconnect on startup check the reconnect on startup and save password for reconnection on startup.
8. Then close.

Using Script

Set qtApp = CreateObject(”QuickTest.Application”)
qtApp.Launch
qtApp.Visible = True
qtApp.TDConnection. Connect “URL”, “DOMAIN”, “PROJECT”, “USERNAME”, “PASSWORD”, False

5. Retrieve Data from Excel sheet

Dim FilePath, Excelone,ExcelSheet,Val
Set FilePath= CreateObject(”srcfilepath”)
Set ExcelSheet = FilePath.GetSheet(sheetid)
Set Val= ExcelSheet.ActiveSheet.Cells(1,1).value

‘Below script for creating an excel sheet with values 1,2,3
Dim Excel,ExcelSheet
Set Excelone=CreateObject(”Excel.Application”)
Set ExcelSheet=CreateObject(”Excel.Sheet”)
ExcelSheet.Application.visible=true
ExcelSheet.ActiveSheet.Cells(1,1).value=1
ExcelSheet.ActiveSheet.Cells(1,2).value=2
ExcelSheet.ActiveSheet.Cells(1,3).value=3
Excelone.Saveas “E:\tests.xls”
Excelone.quit
Set ExcelSheet=Nothing

6. Some more stuff related to QTP Script.

Set Word = CreateObject(”Word.Application”)
oWord.DisplayAlerts = False
oWord.Visible = False
oWord.documents.open “testWordDoc.doc”
Set Doc = oWord.ActiveDocument
Set Range = oDoc.content
oRange.ParagraphFormat.Alignment = 0
oRange.insertafter vbcrlf ‘& ” ” & vbcrlf
oRange.collapse(0)
oRange.InlineShapes.AddPicture “ImagePath.bmp”, False, True
oWord.ActiveDocument.Save
oWord.Application.Quit True
Set Range = Nothing
Set Doc = Nothing
Set Word = Nothing

‘————————————————————–

Cmd.activeconnection=”Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User ID=sa;Initial Catalog=pubs;

Dim res,cmd,sql
Set Res=createobject(”adodb.recordset”)
Set Cmd=createobject(”adodb.command”)
Cmd.activeconnection=”Provider=SQLOLEDB.1;Password=;Persist Security Info=True;User ID=sa;Initial Catalog=pubs;Data Source=192.168.0.69″
Cmd.CommandType = 1
sql=”select emp_id,fname from dbo.employee”
Cmd.CommandText = sql
Set res = Cmd.Execute()
i=1

While not res.eof
logid = res(”emp_id”).value
logname=res(”fname”).value
print logid
print logname
i=i+1
res.movenext
wend
Set res = nothing
Set cmd.ActiveConnection = nothing
Set Cmd= nothing

‘————————————————————–

Set ExcelObj = CreateObject(”Excel.Application”)
aatype=”F:\templet.xls”
ExcelObj.Workbooks.Open(aatype)
Set NewSheet = ExcelObj.Sheets.Item(2)
Dim rs,sq,pkey
set conn=createobject(”adodb.connection”)
set rs=createobject(”adodb.recordset”)
set rs1=createobject(”adodb.recordset”)
conn.open= “Provider=OraOLEDB.Oracle.1;Password=*;Persist Security Info=True;User ID=*;SERVER=*;Data Source=*;DBQ=*;”
sql=”select * from table”
rs.open sql,conn
i=1
do while not rs.eof
values1=rs(”pkey”)
values2=rs(”name”)
NewSheet.Cells(i+1,1).Value =values1
NewSheet.Cells(i+1,2).Value =values2
i=i+1
rs.movenext
Loop

‘————————————————————–

ExcelObj.ActiveWorkbook.Saveas “F:\data.xls”
ExcelObj.Quit
Set ExcelObj = Nothing
rs.close
set rs=nothing
conn.close
set conn=nothing

‘————————————————————–

Dim Excel,ExcelSheet
Set Excelone=CreateObject(”Excel.Application”)
Set ExcelSheet=CreateObject(”Excel.Sheet”)
ExcelSheet.Application.visible=true
ExcelSheet.ActiveSheet.Cells(1,1).value=1
ExcelSheet.ActiveSheet.Cells(1,2).value=2
ExcelSheet.ActiveSheet.Cells(1,3).value=3
Excelone.Saveas “E:\tests.xls”
Excelone.quit
Set ExcelSheet=Nothing

‘————————————————————–

Set fs=CreateObject(”excel.application”)
fs.Visible=True
Set excelbook=fs.Workbooks.Add
Set excelsheet=excelbook.worksheets(1)
excelsheet.cells(1,1)=”??”
excelsheet.saveas “e:\1.xls”
excelsheet.application.quit
fs.Quit

‘————————————————————–

set fs=createobject(”excel.application”)
fs.visible=true
set excbook=fs.workbooks.open(”f:\1.xls”)
set excsheet=excbook.worksheet(1)
excsheet.cells(1,1).value=”Test”
excbook.save
fs.quit

‘————————————————————–

Dim qtApp ,pDefColl,pDef ,rtParams,rtParam
Set qtApp = CreateObject(”QuickTest.Application”)
qtApp.Launch
qtApp.Visible = True
qtApp.Open “C:\Test1″
Set pDefColl = qtApp.Test.ParameterDefinitions
cnt = pDefColl.Count
Indx = 1
While Indx <= cnt
Set pDef = pDefColl.Item(Indx)
Indx = Indx + 1
Wend
Set rtParams = pDefColl.GetParameters()
Set rtParam = rtParams.Item(”InParam1″)
rtParam.Value = “songfun”
qtApp.Test.Run , True, rtParams
MsgBox rtParams.Item(”OutParam1″).Value

‘————————————————————–

Dim a,b,c
Set a = createobject(”excel.application”)
a.visible = true
Set b = a.workbooks.add
Set c = b.worksheets(1)
c.cells(1,1) = “1″
c.cells(1,2) = “2″
c.cells(1,3) = “3″
c.saveas “e:\testtwo.xls”
c.application.quit
a.quit

‘————————————————————–

set fs=createobject(”excel.application”)
fs.visible=true
set excbook=fs.workbooks.open(”f:\1.xls”)
set excsheet=excbook.worksheet(1)
excsheet.cells(1,1).value=”Test1″
excbook.save
fs.quit

‘————————————————————–

Set alapp=createobject(”Excel.Application”)
alapp.application.visible=true
Set xlbook=alapp.workbooks.open(”e:\test.xls”)
Set xlSheet = xlBook.Worksheets(”Sheet1″)
count1=datatable.GetSheet(”Action1″).getrowcount
For i=1 to count1
alapp.cells(i,1)= datatable.GetSheet(”Action1″).getparameter(”Test1″).valuebyrow(i)
Next
xlSheet.saveas “e:\1.xls”
alapp.quit
Set excel=nothing

Comments

Popular posts from this blog

PDF Automation in QTP

                                                                            The most challenging issue with PDFs is that it could be of any kind, not just a tabular data; it could have plain text, images or even forms to fill up. So this makes a tester’s life a bit difficult, never mind, we will definitely find an easy of do it… Although there are already some better approaches we have to deal with PDF documents but I found many of us are facing so many difficulties using this. There are lots of queries coming at QTP forums asking for an easy way of doing it with PDFs. keeping those in my mind I started c...

Convert JSON to XML using QTP/UFT/VBScript

Sample Code : Dim strPage,strJSON,objIE strPage = "C:\Jay\JLoader.html" Set objIE = CreateObject("InternetExplorer.Application") objIE.Visible = True objIE.Navigate2 strPage While objIE.Busy : Wend strJSON = "{""FirstName"":""Jay"", ""LastName"":""Krishna""}" Set objWin = objIE.document.parentWindow objWin.execScript "var jsonStr2XML = function(strJSON) { return json2xml(JSON.parse(strJSON));};" Msgbox  oWin.jsonStr2XML(strJSON) objIE.Quit In Detail: Converting The most popular data interchange format JSON(JavaScript Object Notation) to XML using QTP/UFT. Parsing JSON in UFT could be a challenge so we will use JavaScript in UFT to make it perfect. SO We need :              Java Script API  - To Convert JSON to XML                         JavaScript Files :  ...

Download Test Resource From QC Using QTP

'########################################################################### '* Function Name: QCGetResource '* Designer: Jay '* Date 09-May-2012 '* This script will Download QC Test Resource to a local dir '########################################################################### Function QCGetResource(resourceName,saveTo)     Set qcConn = QCUtil.QCConnection     Set oResource = qcConn.QCResourceFactory     Set oFilter = oResource.Filter     oFilter.Filter("RSC_FILE_NAME") = resourceName     Set oResourceList = oFilter.NewList     If oResourceList.Count = 1 Then         Set oFile = oResourceList.Item(1)         oFile.FileName = resourceName         oFile.DownloadResource saveTo, True     End If         Set qcConn = Nothing     Set oResource = Nothi...

compare Two Text files using Vb Script

Public Function CompareFiles (FilePath1, FilePath2) Dim FS, File1, File2 Set FS = CreateObject(“Scripting.FileSystemObject”) If FS.GetFile(FilePath1).Size <> FS.GetFile(FilePath2).Size Then CompareFiles = True Exit Function End If Set File1 = FS.GetFile(FilePath1).OpenAsTextStream(1, 0) Set File2 = FS.GetFile(FilePath2).OpenAsTextStream(1, 0) CompareFiles = False Do While File1.AtEndOfStream = False Str1 = File1.Read(1000) Str2 = File2.Read(1000) CompareFiles = StrComp(Str1, Str2, 0) If CompareFiles <> 0 Then CompareFiles = True Exit Do End If Loop File1.Close() File2.Close() End Function Return value: The function returns 0 or False if the two files are identical, otherwise True. Example: File1 = “C:\countries\apple1.jpg” File2 = “C:\countries\apple3.jpg” If CompareFiles(File1, File2) = False Then MsgBox “Files are identical.” Else MsgBox “Files are different.” End If    Source: Mercury Forum’s KB articles

CreateImageFromClipBoard using QTP

'-------------------------------------------------------------------------' Method : CreateImageFromClipBoard' Author : Jai Purpose : It gets the clipboard image and convert as a image file.' Parameters: FileName - String, contains the BMP file name' iIndex - Integer, contains the Worksheet index' Returns : String. The replaced file name it gives.' Caller : - Nil' Calls : - Nil' ------------------------------------------------------------------------- Sub CreateImageFromClipBoard(sFileName) Dim wshShell,ShellReturnCode, sCmdExec Set WshShell = WScript.CreateObject("WScript.Shell") sCmdExec = "D:\autostuff\i_view32.exe /silent /clippaste /convert="& sFileName ShellReturnCode = WshShell.Run(sCmdExec, 1, True) End Sub