Wednesday, February 23, 2011

What is Transactions ?

Sometime you want to know the time script or part of script is taking time to execute in such case Transactions will help to find out.
You define transactions within your test by enclosing the appropriate sections of the test with start and end transaction statements.
How to Inserting Transactions
You define the beginning of a transaction in the Start Transaction dialog box.

·         click the step where you want the transaction timing to start point
·         Insert Start Transaction.
                    


·         The Start Transaction dialog box opens.
·         Enter Transaction name
·         Select radio button as per your need
 To insert a transaction before the current step, select Before current step.
 To insert a transaction after the current step, select After current step.
·         Click OK.
How to Ending Transactions
You define the end of a transaction in the End Transaction dialog box.
·         Click the step where you want the transaction timing to end.
·         Insert End Transaction. The End Transaction dialog box opens.
                         
  • The Name box contains a list of the transaction names you defined in the
Current test. Select the name of the transaction you want to end.
  • Select radio button, where to insert the end of the transaction:
                 To insert a transaction before the current step, select Before current step.
 To insert a transaction after the current step, select After current step.
  • Click OK.

Tuesday, February 22, 2011

What is Exists property in QTP

You can use Exist statements to wait for a window to open or an object to appear.
E.g Browser(“x”).page(“y”).webbutton(“z”).exists

Exists returns Boolean value. Basically, it is used for user define checkpoint

E.g
if Browser(“x”).page(“y”).webbutton(“z”).exists then
            Reporter.Report ,,”pass”
            Else
            Reporter.Report ,,”Fail”
End if

Difference between Exists and Wait
Exists:   Exists will wait till timeout, if object doesn’t exist and return false and start execution
Wait: Wait will wait till default time or user specific time and start execution.

What is Synchronization

Some time running application may not always respond with the same speed. Sometime due to server slow process your response will get late. How to handle such type of situation?

With the use of Synchronization concept in QTP
           
·         Use of Sync property:  You can insert a synchronization point, which tells QTP to pause the test until an object property achieves the value.

E.g. Browser(“x”).page(“y”).webbutton(“z”).sync

  • Use of Wait Statement: You can insert Exist or Wait statements that tell QTP to wait until an object exists or to wait a specified amount of time before continuing the test.
E.g.  
            Wait(10) or Wait // After 10 second, qtp start execution below statement
Browser(“x”).page(“y”).webbutton(“z”).sync

  • Increase timeout time: You can also increase the default timeout settings in the Test Settings and Options dialog boxes in order to tell QTP to allow more time for certain events to occur.
We can set from here File >> Settings >> Run, Increase Object Synchronization timeout limit.

Thursday, February 17, 2011

How to write in Excel Sheet


set xlapp = createobject("Excel.Application")
set wb = xlapp.workbooks.open("D:\test.xls")
set sh = xlapp.worksheets(1)
rc = sh.usedrange.rows.count
for j = 2 to rc

     ' write must be bases on condition
     sh.cells(j,2) = "pass"

Next

xlapp.Visible = True
wb.close
xlapp.quit
set xlapp = nothing

Friday, February 11, 2011

Execution of .vbs or .txt files in qtp

To execute the .vbs or .txt files in qtp, user has to associate those file in qtp

Associate library files in qtp

Concept behind this association of library file is that the script is written in separate library file like .vbs or .txt file and to run script you need to associate those files if you want to use them. After Association of the file, File will place in File -> settings -> resource.

There are two way to execute those files in qtp

1.       ExecuteFile key word
2.       Associate in Library

1.       ExecuteFile keyword:

ExecuteFile "File path" ( E.g: ExecuteFile “C:\test.vbs” )
In this concept, user has to call the function defined the .vbs file. Here library file will not be placed in File -> settings -> resource. But still user can access function defile in the file.
2.       Associate in Library:
Here, run time association of the file will be placed in File -> settings -> resource path in qtp.
Now user can access the function by calling it.

Example:

Set App = CreateObject("QuickTest.Application")
App.Launch
App.Visible = True
App.Test.Settings.Resources.Libraries.RemoveAll
App.Test.Settings.Resources.Libraries.Add "D:\test1.vbs”
App.Test.Settings.Resources.Libraries.Add "D:\test2.vbs"
Set App = Nothing

Note:    Associate file concept will help users to debug in file while run time however ExecuteFile will not be help in debugging.


Thursday, February 10, 2011

Data Table Object Details


1 AddSheet Method

Adds the specified sheet to the run-time Data Table 
      Syntax: DataTable.AddSheet(SheetName)
      Example:
      Variable=DataTable.AddSheet ("Sheet1").AddParameter("Name", "Neeraj")

2.    DeleteSheet Method

Deletes the specified sheet from the run-time Data Table.
Syntax: DataTable.DeleteSheet SheetID
Example: DataTable.DeleteSheet "Sheet1“

3.    Export Method

Saves a copy of the run-time Data Table in the specified location.
Syntax: DataTable.Export(FileName)
Example: DataTable.Export ("C:\FileName.xls")

4.    ExportSheet Method

Exports a specified sheet of the run-time Data Table to the specified file.
Syntax: DataTable.ExportSheet(FileName, DTSheet)
Example: DataTable.ExportSheet "C:\FileName.xls" ,1

5.    GetCurrentRow Method

Returns the current (active) row in the run-time global data sheet.

6.    GetRowCount Method

Returns the total number of rows in the longest column in the global data sheet or in the specified data sheet of the run-time Data Table.
Example:
rowcount = DataTable.GetSheet("Sheet1").GetRowCount

7.    GetSheet Method

Returns the specified sheet from the run-time Data Table.
Example:MyParam=DataTable.GetSheet ("Sheet1").AddParameter("Name", "Neeraj")

8.    GetSheetCount Method

Returns the total number of sheets in the run-time Data Table.

9.    Import Method

Imports the specified Microsoft Excel file to the run-time Data Table.
Syntax: DataTable.Import(FileName)
Example: DataTable.Import ("C:\FileName.xls")

10. ImportSheet Method

Imports a sheet of a specified file to a specified sheet in the run-time Data Table.
Syntax:  DataTable.ImportSheet(FileName, SheetSource,SheetDest)
Example: DataTable.ImportSheet "C:\FileName.xls,1 ,"name"

11. SetCurrentRow Method

Sets the specified row as the current (active) row in the run-time Data Table.
Example: DataTable.SetCurrentRow (2)

12. SetNextRow Method

Sets the row after the current (active) row as the new current row in the run-time Data
Table.

13. SetPrevRow Method

Sets the row above the current (active) row as the new current (active) row in the run-time
Data Table.

14. GlobalSheet Property

Returns the Global sheet of the run-time Data Table.
Example:
DataTable.GlobalSheet.AddParameter "Name", "Neeraj"

15. LocalSheet Property

Returns the current (active) local sheet of the run-time Data Table.
Example:
MyParam=DataTable.LocalSheet.AddParameter("Name ", " Neeraj ")

16. RawValue Property

Retrieves the raw value of the cell in the specified parameter and the current row of the run-time
Data Table.
Syntax: DataTable.RawValue ParameterID [, SheetID]
SheetID can be the sheet name, index or dtLocalSheet, or dtGlobalSheet.

17. Value Property

Retrieves or sets the value of the cell in the specified parameter and the current row of the run-time Data Table.
Syntax:DataTable.Value(ParameterID [, SheetID])

How to use sendkey in QTP script


Definition:
Sends one or more keystrokes to the active window (as if typed on the keyboard).

Syntax:
object.SendKeys(string)

Special character

plus sign       "+",
caret             "^",
percent sign "%",
and tilde       "~"

Send these characters by enclosing them within braces "{}".
For example, to send the plus sign, send the string argument "{+}". Brackets "[ ]" have no special meaning
when used with SendKeys, but you must enclose them within braces to accommodate applications that
do give them a special meaning (for dynamic data exchange (DDE) for example).

To send bracket characters, send the string argument "{[}" for the left bracket and "{]}" for the right one.
To send brace characters, send the string argument "{{}" for the left brace and "{}}" for the right one.
Some keystrokes do not generate characters (such as ENTER and TAB).
Some keystrokes represent actions (such as BACKSPACE and BREAK).
To send these kinds of keystrokes, send the arguments shown in the following table:


Key                                 Argument
BACKSPACE                  {BACKSPACE}, {BS}, or {BKSP}
BREAK                          {BREAK}
CAPS LOCK                  {CAPSLOCK}
DEL or DELETE          {DELETE} or {DEL}
DOWN ARROW          {DOWN}
END                          {END}
ENTER                          {ENTER} or ~
ESC                                  {ESC}
HELP                          {HELP}
HOME                          {HOME}
INS or INSERT          {INSERT} or {INS}
LEFT ARROW          {LEFT}
NUM LOCK                  {NUMLOCK}
PAGE DOWN                  {PGDN}
PAGE UP                  {PGUP}
PRINT SCREEN          {PRTSC}
RIGHT ARROW           {RIGHT}
SCROLL LOCK          {SCROLLLOCK}
TAB                                  {TAB}
UP ARROW                   {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}

Example



Const iNormalFocus = 1
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "mmc.exe",iNormalFocus

Wscript.Sleep 300

objShell.AppActivate "Console1"
Wscript.Sleep 100
objShell.SendKeys "^m"
Wscript.Sleep 100
objShell.SendKeys "{TAB}"
Wscript.Sleep 100
objShell.SendKeys "{TAB}"
Wscript.Sleep 100
objShell.SendKeys "{ENTER}"



Wednesday, February 9, 2011

Script to get local drive utilization

'get local drive utilization
dim objFSO,collDrv
dim fs,d

set objFSO=wscript.CreateObject("Scripting.FileSystemObject")
set collDrv=objFSO.Drives

  for each drv in collDrv
        if drv.DriveType=2 then  'check fixed drives only
                Set fs = CreateObject("Scripting.FileSystemObject")
                Set d = fs.GetDrive(fs.GetDriveName(drv))
                 t = FormatNumber(d.TotalSize/(1024*1024), 0)
                 f = FormatNumber(d.FreeSpace/(1024*1024), 0)
                 u = 100-FormatNumber(f/t,2)*100
                 s= s & drv & "  " & drv.VolumeName & " (" & drv.FileSystem & ")" & vbtab & t & " MB 
                      Total"& vbtab & f & " MB Free" & vbtab &  u & "% Utilized" & vblf
       end if
  next

wscript.echo s

set objFSO=Nothing
set collDrv=Nothing
set fs=Nothing
set d=Nothing
wscript.quit

Script to Get Folder Properties

'Get Folder Properties
On Error Resume Next
dim objFSO
dim objFldr

'Specify folder you want information about
strFldr="c:\Neeraj"

set objFSO=CreateObject("Scripting.FileSystemObject")

'get a reference to the folder
set objFldr=objFSO.GetFolder(strFldr)

'list out properties
wscript.Echo "Folder Name:" & vbtab & objFldr.Name
wscript.Echo "Short Folder Name:" & vbtab & objFldr.ShortName
wscript.Echo "Folder Path:" & vbtab & objFldr.Path
wscript.Echo "Date Created:" & vbtab & objFldr.DateCreated
wscript.Echo "Date Last Accessed:" & vbtab & objFldr.DateLastAccessed
wscript.Echo "Date Last Modified:" & vbtab & objFldr.DateLastModified
wscript.Echo "Folder Size (bytes):" & vbtab & objFldr.Size
wscript.Echo "Folder Attributes:"

if objFldr.Attributes AND 0 then wscript.Echo " Normal"
if objFldr.Attributes AND 1 then wscript.Echo " Read-only"
if objFldr.Attributes AND 2 then wscript.Echo " Hidden"
if objFldr.Attributes AND 4 then wscript.Echo " System"
if objFldr.Attributes AND 8 then wscript.Echo " Volume"
if objFldr.Attributes AND 16 then wscript.Echo " Directory"
if objFldr.Attributes AND 32 then wscript.Echo " Archive Bit is set"
if objFldr.Attributes AND 1024 then wscript.Echo " Alias"
if objFldr.Attributes AND 2048 then wscript.Echo " Compressed"

set objFldr=Nothing
set objFSO=Nothing

Scrip to Get File Properties

'Get File Properties
On Error Resume Next
dim objFSO
dim objFile

strFile="c:\file.txt"

set objFSO=CreateObject("Scripting.FileSystemObject")
set objFile=objFSO.GetFile(strFile)

wscript.Echo "File Name:" & vbtab & objFile.Name
wscript.Echo "Short File Name:" & vbtab & objFile.ShortName
wscript.Echo "File Path:" & vbtab & objFile.Path
wscript.Echo "Date Created:" & vbtab & objFile.DateCreated
wscript.Echo "Date Last Accessed:" & vbtab & objFile.DateLastAccessed
wscript.Echo "Date Last Modified:" & vbtab & objFile.DateLastModified
wscript.Echo "File Size:" & vbtab & objFile.Size
wscript.Echo "File Attributes:"

if objFile.Attributes AND 0 then wscript.Echo " Normal"
if objFile.Attributes AND 1 then wscript.Echo " Read-only"
if objFile.Attributes AND 2 then wscript.Echo " Hidden"
if objFile.Attributes AND 4 then wscript.Echo " System"
if objFile.Attributes AND 8 then wscript.Echo " Volume"
if objFile.Attributes AND 16 then wscript.Echo " Directory"
if objFile.Attributes AND 32 then wscript.Echo " Archive Bit is set"
if objFile.Attributes AND 1024 then wscript.Echo " Alias"
if objFile.Attributes AND 2048 then wscript.Echo " Compressed"

set objFile=Nothing
set objFSO=Nothing

Script to get Drive Properties

'Get Drive Properties
On Error Resume Next
dim objFSO
dim objDrv
'drive we want to know about
strDrv="c:\"
set objFSO=CreateObject("Scripting.FileSystemObject")
'get reference to drive
set objDrv=objFSO.GetDrive(strDrv)
'list properties
'if volume name isn't defined then state that
if objDrv.VolumeName="" then
 wscript.Echo "Volume Name:" & vbtab & "NOT DEFINED"
else
 wscript.Echo "Volume Name:" & vbtab & objDrv.VolumeName
end if
wscript.Echo "Serial Number:" & vbtab & objDrv.SerialNumber
Select Case objDrv.DriveType
 Case 0  strType="Unknown"
 Case 1  strType="Removable"
 Case 2  strType="Fixed"
 Case 3  strType="Remote"
 Case 4  strType="CDROM"
 Case 5  strType="RamDisk"
 Case Else strType="Unknown"
end Select
wscript.Echo "Drive Type:" & vbtab  & strType
wscript.Echo "Is Ready:" & vbtab & objDrv.IsReady
wscript.Echo "File System:" & vbtab & objDrv.FileSystem
wscript.Echo "Total Size (bytes):" & vbtab & objDrv.TotalSize
wscript.Echo "Available Space (bytes):" & vbtab & objDrv.AvailableSpace
wscript.Echo "Free Space (bytes):" & vbtab & objDrv.FreeSpace

set objFSO=Nothing
set objDrv=Nothing

Script to Create a folder and delete a folder

'Create FolderOn Error Resume Next
dim objFSO

'new folder to create.  The parent folder must already exists
strFldr="C:\Neeraj"

set objFSO=CreateObject("Scripting.FileSystemObject")
objFSO.CreateFolder(strFldr)

set objFSO=Nothing

'Delete folder
'ANY FILES OR SUBDIRECTORIES WILL ALSO BE DELETED

On Error Resume Next
dim objFSO
'folder to delete
strFldr="C:\Neeraj"

set objFSO=CreateObject("Scripting.FileSystemObject")
objFSO.DeleteFolder(strFldr)

set objFSO=Nothing

Script to Write a text in a file

'Write to existing text file
On Error Resume Next
dim objFSO
dim objFile

Const ForWriting=2
'specify filename and path for file to open
strFile="c:\file.txt"

set objFSO=CreateObject("Scripting.FileSystemObject")
'if file already exists, value of TRUE forces overwriting file
set objFile=objFSO.OpenTextFile(strFile,ForWriting)
objFile.WriteLine Now & " this is a new line"

objFile.Close

set objFile=Nothing
set objFSO=Nothing

Script to read text from file

'Read Text File
On Error Resume Next
dim objFSO
dim objFile

Const ForReading=1
strFile="C:\file.txt"

set objFSO=CreateObject("Scripting.FileSystemObject")
set objFile=objFSO.OpenTextFile(strFile,ForReading)

'read in each line of data until you reach the end of the file
do While objFile.AtEndOfStream<>True
      strEntry=objFile.ReadLine
      'you can now do what ever you want with the line
      'as referenced with the strEntry variable such as
      'echoing it back (e.g. wscript.Echo strEntry) or passing it
      'as a variable to a function of subroutine (e.g. MyFunction strEntry)
     wscript.Echo strFile
loop

'close file
objFile.Close

set objFSO=Nothing
set objFile=Nothing

Script to Move a file from one Place to another

'Move File
On Error Resume Next
dim objFSO
dim objFile

'specify filename and path for file to move
strFile="c:\file.txt"
'specify target destination
strDest="c:\Neeraj\"

set objFSO=CreateObject("Scripting.FileSystemObject")
'move will fail if file already exists in target destination
objFSO.MoveFile strFile,strDest

if err.number=0 then
       wscript.Echo "Successfully moved " & strFile & " to " & strDest
else
       wscript.Echo "Failed to move " & strFile & " to " & strDest
end if

err.Clear
set objFSO=Nothing

Script to Copy File from one Place to another

'Copy File from one Place to another
On Error Resume Next
dim objFSO
dim objFile

'specify filename and path for file to copy
strFile="c:\file.txt"
'specify target destination
strDest="c:\Neeraj\"

set objFSO=CreateObject("Scripting.FileSystemObject")
'set last parameter to TRUE if you want to overwrite
'an existing file with the same name
objFSO.CopyFile strFile,strDest,TRUE

if err.number=0 then
      wscript.Echo "Successfully copied " & strFile & " to " & strDest
else
      wscript.Echo "Failed to copy " & strFile & " to " & strDest
end if

set objFSO=Nothing

Script to Check if file exists or not

'Check if file exists
On Error Resume Next
dim objFSO

strFile="c:\file.txt"
set objFSO=CreateObject("Scripting.FileSystemObject")

if objFSO.FileExists(strFile) then
   wscript.Echo strFile & " exists"
   'insert any other code you want to execute if file exists
else
   wscript.Echo "Cannot find " & strFile
   'insert any other code or error handling you want to execute
   'if file does not exist
end if

set objFSO=Nothing

Append to an existing text file

'Append to an existing text file
On Error Resume Next
dim objFSO
dim objFile

Const ForAppending=8
'specify filename and path for file to open
strFile="c:\file.txt"

set objFSO=CreateObject("Scripting.FileSystemObject")
set objFile=objFSO.OpenTextFile(strFile,ForAppending)
objFile.WriteLine Now & " this is an appended line"
objFile.Close

set objFile=Nothing
set objFSO=Nothing

Script to Delete a file from system

'Delete file
On Error Resume Next
dim objFSO

'specify filename and path for file to create
strFile="c:\file.txt"

set objFSO=CreateObject("Scripting.FileSystemObject")
'to force deletion, set to TRUE otherwise set to FALSE
objFSO.DeleteFile strFile,TRUE





Create a text file example

'create a text file example
On Error Resume Next
dim objFSO
dim objFile

'specify filename and path for file to create
strFile="c:\file.txt"
set objFSO=CreateObject("Scripting.FileSystemObject")
'if file already exists, value of TRUE forces overwriting file
set objFile=objFSO.CreateTextFile(strFile,TRUE)
objFile.WriteLine "This is an entry into my logfile"
'write 3 blank lines
objFile.WriteBlankLines(3)
objFile.WriteLine "Here is the last line of my logfile"
wscript.Echo "See " & strFile & " for results"
'close file
objFile.Close
set objFSO=Nothing
set objFile=Nothing

Write Log Report in QTP with the help of Class


' Calling class method.
dim fineName
set objLogger = new Logger fileName = objLogger.createLogFile()
objLogger.getInput "1",Date,"Login","User can Login","Login successfully","Pass"
objLogger.writeLogDetails fileName

' Class defination


Class Logger
           dim slNo
           dim dtTime
           dim functionName
           dim expectedResult
           dim actualResult
           dim status
           dim path

             Function createLogFile()

                            path = inputbox("Enter the log path:")
                            driveName = "d:\" 
                            Fullpath = driveName & path 
                            set fso = CreateObject("Scripting.FileSystemObject")
                            set f1 = fso.CreateTextFile(FullPath, True)

                             If (fso.FileExists(Fullpath)) Then
                                    msgbox Fullpath & " exists."                            
                             Else
                                    msgbox = Fullpath & " doesn't exists."
                             End If                            
                             createLogFile=Fullpath
            End Function

  Function getInput(VslNo,VdtTime,VfunctionName,VexpectedResult,VactualResult,Vstatus)      
                            slNo = Vslno
                            dtTime = VdtTime
                             functionName = VfunctionName 
                             expectedResult = VexpectedResult
                             actualResult = VactualResult
                             status = Vstatus
            End Function 

            Function writeLogDetails(fpath)
                            f1.writeLine = slNo
                            f1.writeLine = dtTime
                            f1.writeLine = functionName
                            f1.writeLine = expectedResult
                            f1.writeLine = actualResult
                            f1.writeLine = status
                           msgbox "write Done"
           End function
End Class

Tuesday, February 8, 2011

What is Output Values and types of Output Values ?

An output value is a step in which one or more values are captured at a specific point in your test or component and stored for the duration of the run session. The values can later be used as input at a different point in the run session.

Output values are stored only for the duration of the run session. When the run session is repeated, the output values are reset.

You can insert an output value by using commands on the Insert menu or by clicking the arrow beside the Insert Checkpoint button on the Test toolbar. This displays a menu of options that are relevant to the selected step in the test tree.

Types of Output Values

1: Page Output Values:
You can create a page output value from a Web page property value. When you run the test,
QuickTest retrieves the current value of the property and stores it in the run-time Data Table as an
output value.

2: Text Output Values:
QuickTest allows you to create text output values by adding one of the following to your test:
     Text Output Value—enables you to output the text displayed in a screen or Web page, according to 
              specified criteria. It is supported for all environments.
     Standard Output Value—enables you to output an object’s text property. This is the preferred way of
             outputting the text displayed in many Windows applications.
     Text Area Output Value—enables you to output the text string displayed within a defined area of a
            Windows-application screen, according to specified criteria. It is supported for Standard
            Windows, Visual Basic, and ActiveX environments.

3: Standard Output Values:
You can create a standard output value from an object property value. When you run the test, QuickTest
retrieves the current value of the property and enters it in the run-time Data Table as an output value.

4: Image Output Values:
You can create an image output value from the property value of a Web image. When you run the test,
QuickTest retrieves the current value of the property and enters it in the run-time Data Table as an output
value.

5: XML Output Values:
You can create an XML output value from an element value or attribute of an XML file or Web page/frame.
When you run the test, QuickTest retrieves the current value of the element or attribute and enters it in the
run-time Data Table as an output value.

When you run your test, you can view summary results of the XML output value in the Test Results window.
You can also view detailed results by opening the XML Output Value Results window.

6: Table Output Values:
You can create a table output value from the contents of a table cell. When you run the test, QuickTest
retrieves the current value of a table cell and enters it in the run-time Data Table as an output value.

7: Database Output Values:
You can create a database output value from the contents of a database cell. When you run the test,
QuickTest retrieves the current value of a database cell and enters it in the run-time Data Table as an output
value.

Types of environment variables in QTP

There are three Types of Environment Variables in qtp
 1: User-Defined Internal
2: User-Defined External
3: Build-in

1: User-Defined Internal

User defined internal variables are the variables that you define within the test. They are saved with the test and accessible only within the test in which they were defined.

        • In the Edit value section of the Object Properties, Object Repository, Method Arguments, or 
          Checkpoint Properties dialog box, click Other as the type of parameter you want to use.
       • Click the Edit Parameter Options button next to the parameter type box. The Parameter Options

         dialog box opens.
       • Select Environment in the Parameter Types box.
       • Accept the default name or enter a new name to add a new user-definedinternal environment

          parameter, or select an existing environment variable name from the Name box. If you select an 
         existing internal parameter, you can modify the value.
       • If you created a new parameter or selected an existing user-defined-internal parameter, enter the value

         for the parameter in the Value box.
       • Select the Regular Expression check box if needed and Enter the regular expression
       • Click OK to save your changes and close the dialog box.

2: User-Defined External

User defined external variables are the variable that you pre-defined in the active external environment variables file. You can create as many files as you want and select an appropriate file for each test. Note that external environment variable values are designated as read-only within the test.

To define these variables create an external environment variables file
To select the active external environment-variables file:
      • Choose Test > Settings to open the Test Settings dialog box.
      • Click the Environment tab.
      • Select the Load variables and values from external file (reloaded each test run) check box.
      • Use the browse button or enter the full path of the external environment- variables file you want to use
         with your test.

3: Build-in



Built-in variables, such as Test path and Operating system. They are accessible from all tests, and are designated as read-only.
Steps to add or modify environment variable parameters:       

What is Parameterization in qtp and Types of Parameterize ?

A parameter is a variable that is assigned a value from various data sources or generators.

Types of Parameter :

Test, Actions and component parameters enable you to use values passed from your test or component, or values from other actions in your test.


Environment variable parameters enable you to use variable values from other sources during the run session.
Random number parameters enable you to insert random numbers as values in your test or component.

How to do User-defined checkpoint in QTP

Dim OuterHTMLPro

OuterHTMLPro = Browser("BrowserName").Page("PageName").WebEdit("Editboxname").GetROProperty("outerHTML")

If OuterHTMLPro <> "name=neeraj" Then
       Reporter.ReportEvent micPass, "Property mached", "Property is Same"
Else
       Reporter.ReportEvent micFail, "Property mached", "Property is not Same"
End If

Monday, February 7, 2011

Close all open browser before start execution

Public Function CloseAllBrowsers()


     'Create a description for browser
      Set oBrowser = Description.Create
      oBrowser("micclass").Value = "Browser"
      Set oPage = Description.Create
      oPage("micclass").Value = "Page"
      'Get all browsers
      Set allBrowser = Desktop.ChildObjects(oBrowser)
      Dim i, iCount
      iCount = allBrowser.Count - 1
      For i = 0 To iCount
            'Get the page object from the browser
            Set oPg = allBrowser(i).ChildObjects(oPage)(0)
            allBrowser(i).Close
     Next

End Function

Fucntion to create folder and check if the folder is exists or not

' Fucntion to create folder and check if the folder is exists or not.
'This Function can help to create run time Framework Folder.
Function CreateFolderStruct(FolderPath)

      'Create Folder
      On Error Resume Next
      dim objFSO
      strFldr=FolderPath
      set objFSO=CreateObject("Scripting.FileSystemObject")
      if isFolderExists(FolderPath) = "False" then
              objFSO.CreateFolder(strFldr)
     end if
     set objFSO=Nothing

End Function

Function isFolderExists(FolderPath)
      On Error Resume Next
      dim objFSO
      set objFSO=CreateObject("Scripting.FileSystemObject")
      if objFSO.FolderExists(FolderPath) then
            isFolderExists = "True"
      else
            isFolderExists = "False"
      end if
      set objFSO=Nothing
End Function

Vbscript code to send a mail in QTP


Function SendMail()

       Set objMessage = CreateObject("CDO.Message")
       objMessage.Subject = "This is for Subject text" ' Subject details
       objMessage.From = "abc@gmail.com" ' From Email ids
       objMessage.To = "abc@gmail.com;All@gmail.com" ' To Email ids
       objMessage.CC = "abc@gmail.com;All@gmail.com" ' CC Email ids
       objMessage.BCC = "abc@gmail.com;All@gmail.com" ' BCC Email ids
       'objMessage.TextBody ="Place Normal text body" ' For Text format
       objMessage.HTMLBody = "Place HTML code for body text"  For HTML body
       objMessage.AddAttachment "C:\abc.txt" ' Path for Attachment
       objMessage.Send
 
End Function

Friday, February 4, 2011

XML Web Service Automation Testing

Below code show the web service testing without qtp Add-in

Click here for webService XML file Weather Forecast Web Service Link
For Excel file Mail me.. neerajlad171@gmail.com

Dim counter
counter = 1
Dim CommonfilePath, ExcelSheetName, DataSheetNo, DataSheetName
CommonfilePath = "D:\QTP_Practive\WebServices\SampleData_1.xls"
DataSheetName = "OutputWeatherFC"
DataSheetNo = DataTable.GetSheetCount + 1
ExcelSheetName = "OutputWeatherFC"
Call ImportData(CommonfilePath, ExcelSheetName, DataSheetNo, DataSheetName)

Dim xmldoc
Set xmldoc = CreateObject("msxml2.domdocument")
xmldoc.Load ("D:\QTP_Practive\WebServices\Response_WeatherByPlaceName.xml")
dtTopNode = DataTable.Value("TAGNAME", DataSheetName)
dtTags = DataTable.Value("TAGS", DataSheetName)
dtTagName = GetdtNodeName(dtTopNode)
Set TopNode = xmldoc.documentElement
MsgBox TopNode.nodeName
Call TreeTravel(TopNode, dtTagName, dtTags)
 
Function TreeTravel(TopNode, dtTagName, dtTags)
    If dtTags = "END" Then
       counter = counter + 1
       DataTable.SetCurrentRow (counter)
       dtTopNode = DataTable.Value("TAGNAME", DataSheetName)
      dtTags = DataTable.Value("TAGS", DataSheetName)
      dtTagName = GetdtNodeName(dtTopNode)
    Else
      If TopNode.nodetype = 1 Then
           If TopNode.nodeName = dtTagName And dtTags = "" Then
                  MsgBox TopNode.nodeName & " <=> " & TopNode.Text
           End If
           Set child = TopNode.childNodes
           ' msgbox "TopNode Name: " &TopNode.nodename
          For i = 0 To child.length - 1
                 If child.Item(i).nodetype <> 3 Then
                          counter = counter + 1
                          DataTable.SetCurrentRow (counter)
                          dtTopNode = DataTable.Value("TAGNAME", DataSheetName)
                          dtTags = DataTable.Value("TAGS", DataSheetName)
                          dtTagName = GetdtNodeName(dtTopNode)
                         Call TreeTravel(child.Item(i), dtTagName, dtTags)
                End If
           Next
     End If
  End If
End Function

Generic Function for button, Edit box, Combo box and Radio button

'########## button ##############
Function buttonclick(obutton)
     sobjname = obutton.tostring
     sstepname = "Buttonclick"
     bexists = obutton.Exist(0)

     If bexists Then
              smsg = sobjname&" Exists"
              reporter.ReportEvent micPass,sstepname,smsg
     else
              smsg = sobjname&" does not Exists"
               reporter.ReportEvent micFail,sstepname,smsg
               Exittest
     End If

     bdisabled = obutton.getroproperty("disabled")
     If bdisabled = 0 Then
         smsg = sobjname&" is enabled"
         reporter.ReportEvent micPass,sstepname,smsg
     else
         smsg = sobjname&" is disabled"
         reporter.ReportEvent micFail,sstepname,smsg
         Exittest
     End If

     smsg = "clicking on "&sobjname
     reporter.ReportEvent micPass,sstepname,smsg
     obutton.click
End Function

' ########## Edit box ###########
Function edit_set(oedit,sinputtext)
     sobjname = oedit.tostring
     sstepname = "EditSet"
     bexists = oedit.Exist(0)
     If bexists Then
          smsg = sobjname&" Exists"
          reporter.ReportEvent micPass,sstepname,smsg
    else
          smsg = sobjname&" does not Exists"
          reporter.ReportEvent micFail,sstepname,smsg
          Exittest
    End If

    bdisabled = oedit.getroproperty("disabled")
    If bdisabled = 0 Then
        smsg = sobjname&" is enabled"
        reporter.ReportEvent micPass,sstepname,smsg
    else
        smsg = sobjname&" is disabled"
        reporter.ReportEvent micFail,sstepname,smsg
        Exittest
    End If

    smsg = "Entering "&sinputtext&" into "&sobjname
    reporter.ReportEvent micPass,sstepname,smsg
    oedit.set sinputtext
End Function

' ########## Combo box ###########
Function itemselect(olist,sitemtoselect)
      sobjname = olist.tostring
      sstepname = "itemselect"
      bexists = olist.Exist(0)
      If bexists Then
            smsg = sobjname&" Exists"
            reporter.ReportEvent micPass,sstepname,smsg
      else
            smsg = sobjname&" does not Exists"
            reporter.ReportEvent micFail,sstepname,smsg
            Exittest
      End If
      bdisabled = olist.getroproperty("disabled")
      If bdisabled = 0 Then
           smsg = sobjname&" is enabled"
           reporter.ReportEvent micPass,sstepname,smsg
      else
            smsg = sobjname&" is disabled"
            reporter.ReportEvent micFail,sstepname,smsg
            Exittest
      End If
      bitemfound = false
      sallitems = olist.getroproperty("all items")
      allitems = split(sallitems,";")
      For i = 0 to ubound(allitems)
             av = allitems(i)
             If lcase(av) = lcase(sitemtoselect) Then
                 bitemfound = true
                 Exit for
             End If
      Next
      If bitemfound Then
         smsg = "Item "&sitemtoselect&" is found in "&sobjname
         Reporter.ReportEvent micPass,sstepname,smsg
      Else
           smsg = "Item "&sitemtoselect&" is not found in "&sobjname
           Reporter.ReportEvent micPass,sstepname,smsg
           Exittest
      End If
      smsg = "Selecting "&sitemtoselect&" from "&sobjname
      reporter.ReportEvent micPass,sstepname,smsg
      olist.select sitemtoselect

End Function

' ########## Radio Button ###########
Function selectRadioBtn(orbgroup,srbtoselect)
      sobjname = orbgroup.tostring
      sstepname = "selectRadioBtn"
      bexists = orbgroup.Exist(0)
      If bexists Then
          smsg = sobjname&" Exists"
           reporter.ReportEvent micPass,sstepname,smsg
      else
           smsg = sobjname&" does not Exists"
           reporter.ReportEvent micFail,sstepname,smsg
           Exittest
      End If
      bdisabled = orbgroup.getroproperty("disabled")
      If bdisabled = 0 Then
         smsg = sobjname&" is enabled"
          reporter.ReportEvent micPass,sstepname,smsg
     else
          smsg = sobjname&" is disabled"
          reporter.ReportEvent micFail,sstepname,smsg
          Exittest
      End If
      bitemfound = false
      sallitems = orbgroup.getroproperty("all items")
      allitems = split(sallitems,";")
      For i = 0 to ubound(allitems)
           av = allitems(i)
          If lcase(av) = lcase(srbtoselect) Then
                 bitemfound = true
                 Exit for
         End If
      Next
      If bitemfound Then
           smsg = "Item "&srbtoselect&" is found in "&sobjname
           Reporter.ReportEvent micPass,sstepname,smsg
      Else
           smsg = "Item "&srbtoselect&" is not found in "&sobjname
           Reporter.ReportEvent micPass,sstepname,smsg
           Exittest
      End If
       smsg = "Selecting "&srbtoselect&" from "&sobjname
       reporter.ReportEvent micPass,sstepname,smsg
       orbgroup.select srbtoselect
End Function

Thursday, February 3, 2011

Find the number of lines in text file


Function NoOfLineInTextFile() As Integer
      Dim objFSO, strTextFile, strData, arrLines, LineCount
      Const ForReading = 1
      strTextFile = "d:\StringFile.txt"
      Set objFSO = CreateObject("Scripting.FileSystemObject")
      strData = objFSO.OpenTextFile(strTextFile, ForReading).ReadAll
      arrLines = Split(strData, vbCrLf)
      LineCount = UBound(arrLines) + 1
      Set objFSO = Nothing
      MsgBox "Number of lines available in : " & LineCount
      NoOfLineInTextFile = LineCount
End Function

Read a Flat file and updated specific word.

Problem: Find the ‘QQ’ word and next word should replace with user input

Logic:
  1. Read Line by Line from text file and storing into Array
  2. Updating array if QQ word found
  3. Writing into File again
StringFile.txt contains:

11;12;xxxxxxxx;6666;77777;7777777;uuuu;ayex345;QQ;yyy;w434;ccc;
1q5;9s9;2f; 
' ################ Function call #########################
call ReadFromFile()

' ############### Function defination #####################
Function ReadFromFile()

          Const ForReading = 1
          Set objFSO = CreateObject("Scripting.FileSystemObject")
          Set objFile = objFSO.OpenTextFile("d:\StringFile.txt", ForReading)
          Dim arrFileLines()
          i = 0
          Do Until objFile.AtEndOfStream
                ReDim Preserve arrFileLines(i)
                 arrFileLines(i) = objFile.ReadLine
                i = i + 1
         Loop
         objFile.Close

         Call UpdateArrayValue(arrFileLines) ' Update array
         Call WriteArrIntoFiles(arrFileLines) ' writing file

End Function

Function UpdateArrayValue(arrFileLines)
     
       For K = 0 to Ubound(arrFileLines)
               NewArr = Split(arrFileLines(K), ";")
               For j = 0 To UBound(NewArr)
                        If NewArr(j) = "QQ" Then
                                    NewArr(j + 1) = "xxx"   ' xxx is user input value
                        End If
               Next
               UpdatedNewArr = Join(NewArr, ";")
               arrFileLines(K) = UpdatedNewArr
      Next
End Function

Function WriteArrIntoFiles(Arr)

              Const ForWriting = 2
              Set objFSO = CreateObject("Scripting.FileSystemObject")
              Set f = objFSO.GetFile("d:\StringFile.txt")
              Set Ln = f.OpenAsTextStream(ForWriting)
              For j = 0 To UBound(Arr)
                    Ln.WriteLine (Arr(j))
              Next
              Ln.Close
End Function