QTP Script to send Keyboard Input to an Application

Sending Keyboard Input to an Application
The example below uses the PressKey method to send keyboard input to an application.

'An example that presses a key using DeviceReplay.

Set obj = CreateObject("Mercury.DeviceReplay")

Window("Notepad").Activate

obj.PressKey 63

The PressKey method uses the ASCII value for the key.
63 is the ASCII value for F5.

ASCII values for other keys:
F1 - 59
F2 - 60
F3 - 61
F4 - 62
F5 - 63
F6 - 64
F7 - 65
F8 - 66
F9 - 67
F10 - 68
F11 - 87
F12 - 88

QuickTest Professional script for Message Boxes That Close Automatically

Using Message Boxes That Close Automatically
The function below shows a message box that disappears after the specified timeout (in seconds). The script execution then continues.

Public Sub MsgBoxTimeout (Text, Title, TimeOut)

Set WshShell = CreateObject("WScript.Shell")

WshShell.Popup Text, TimeOut, Title

End Sub

If TimeOut is 0, it behaves just like a normal message box. If TimeOut is greater than 0, the dialog box disappears after the specified number of seconds.

QuickTest Professional script Debugging using File Operations

The following are some file operations which are useful for debugging scripts in QTP. The following examples can be downloaded from here.

' Creates a specified file and returns a TextStream object that can be used to read from or write to the file.

' Example of usage:

' Set f = CreateFile("d: emp\beenhere.txt", True)

' f.WriteLine Now

' f.Close

Function CreateFile(sFilename, bOverwrite)

Set fso = CreateObject("Scripting.FileSystemObject")

Set CreateFile = fso.CreateTextFile(sFilename, bOverwrite)

End Function

' Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.

' iomode: 1 - ForReading, 2 - ForWriting, 8 - ForAppending

' Example of usage

' Set f = OpenFile("d: emp\beenhere.txt", 2, True)

' f.WriteLine Now

' f.Close

Function OpenFile(sFilename, iomode, create)

Set fso = CreateObject("Scripting.FileSystemObject")

Set OpenFile = fso.OpenTextFile(sFilename, iomode, create)

End Function

' Appends a line to a file.

' Example of usage:

' AppendToFile "d: emp\beenhere.txt", Now

Function AppendToFile(sFilename, sLine)

Const ForAppending = 8

If sFilename = "" Then

sFilename = Environment("SystemTempDir") & "\QTDebug.txt"

End If

Set f = OpenFile(sFilename, ForAppending, True)

f.WriteLine sLine

f.Close

End Function

' Writes a line to a file.

' Destroys the current content of the file .

' Example of usage:

' WriteToFile "d: emp\beenhere.txt", Now

Function WriteToFile(sFilename, sLine)

Const ForWriting = 2

If sFilename = "" Then

sFilename = Environment("SystemTempDir") & "\QTDebug.txt"

End If

Set f = OpenFile(sFilename, ForWriting, True)

f.WriteLine sLine

f.Close

End Function

QTP Script sample - Normalizing Strings

The NormalizeString function receives a string and returns the equivalent string in a regular expression.

Function NormalizeString(OrgStr)

Dim TempStr

TempStr = Replace(OrgStr, "\", "\\")

TempStr = Replace(TempStr, "*", "\*")

TempStr = Replace(TempStr, "+", "\+")

TempStr = Replace(TempStr, ".", "\.")

NormalizeString = Replace(TempStr, "?", "\?")

End function

msgbox NormalizeString ("a+b*c.d?e")

Considerations for Debugging Tests and Function Libraries in QTP

  • You must have the Microsoft Script Debugger installed to run tests in debug mode. If it is not installed, you can use the QuickTest Additional Installation Requirements Utility to install it. (Select Start > Programs > QuickTest Professional > Tools > Additional Installation Requirements.)
  • While the test and function libraries are running in debug mode, they are read-only. You can modify the content after you stop the debug session (not when you pause it). If needed, you can enable the function library for editing (File > Enable Editing) after you stop the session. For more information, see Editing a Read-Only Function Library. After you implement your changes, you can continue debugging your test and function libraries.
  • If you perform a file operation (for example, you open a different test or create a new test), the debug session stops.

  • If a file is called using an ExecuteFile statement, you cannot debug the file or any of the functions contained in the file. In addition, when debugging a test that contains an ExecuteFile statement, the execution marker may not be displayed correctly.
  • In QuickTest, when you open a test, QuickTest creates a local copy of the external resources that are saved to your Quality Center project. Therefore, any changes you apply to any external resource that is saved in your Quality Center project, such as a function library, will not be recognized in the test until the test is closed and reopened. (An external resource is any resource that can be saved separately from the test, such as a function library, a shared object repository, or a recovery scenario.)
  • In contrast with this, any changes you apply to external resources saved in the file system, such as function libraries, are implemented immediately, as these files are accessed directly and are not saved as local copies when you open your test.

Debugging QTP Tests and Function Libraries

About Debugging Tests and Function Libraries
After you create a test or function library (including registered user functions), you should check that they run smoothly, without errors in syntax or logic. To debug a function library, you must first associate it with a test and then debug it from that test.

QuickTest Professional provides different options that you can use to detect and isolate defects in a test or function library. For example:

  • You can control the run session using the Pause command, breakpoints, and various step commands that enable you to step into, over, and out of a specific step.
  • If QTP displays a run error message during a run session, you can click the Debug button on the error message to suspend the run and debug the test or function library.
  • When a run session is paused (suspended), you can use the Debug Viewer to check and modify the values of VBScript objects and variables and to manually run VBScript commands.
  • You can use the Debug from Step command to begin (and pause) your debug session at a specific point in your test. You can also use the Run to Step command to pause the run at a specific point in your test. You can set breakpoints, and then enable and disable them as you debug different parts of your test or function library.
  • You can also use the Run from Step command to run your test from a selected step. This enables you to check a specific section of your application or to confirm that a certain part of your test or function library runs smoothly.

Programming the FileSystemObject in QTP

To program with the FileSystemObject (FSO) object model:

  • Use the CreateObject method to create a FileSystemObject object.
  • Use the appropriate method on the newly created object.
  • Access the object's properties.
The FSO object model is contained in the Scripting type library, which is located in the Scrrun.dll file. Therefore, you must have Scrrun.dll in the appropriate system directory on your Web server to use the FSO object model.

Creating a FileSystemObject Object
First, create a FileSystemObject object by using the CreateObject method.

The following code displays how to create an instance of the FileSystemObject:

[VBScript]
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
[JScript]
var fso;
fso = new ActiveXObject("Scripting.FileSystemObject");

In both of these examples, Scripting is the name of the type library and FileSystemObject is the name of the object that you want to create. You can create only one instance of the FileSystemObject object, regardless of how many times you try to create another.

Using the Appropriate Method
Second, use the appropriate method of the FileSystemObject object. For example, to create a new object, use either CreateTextFile or CreateFolder (the FSO object model doesn't support the creation or deletion of drives).

To delete objects, use the DeleteFile and DeleteFolder methods of the FileSystemObject object, or the Delete method of the File and Folder objects. You can also copy and move files and folders, by using the appropriate methods.

Accessing Existing Drives, Files, and Folders
To gain access to an existing drive, file, or folder, use the appropriate "get" method of the FileSystemObject object:

  • GetDrive
  • GetFolder
  • GetFile
To gain access to an existing file:

[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.GetFile("c:\test.txt")
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
f1 = fso.GetFile("c:\\test.txt");

Do not use the "get" methods for newly created objects, since the "create" functions already return a handle to that object. For example, if you create a new folder using the CreateFolder method, don't use the GetFolder method to access its properties, such as Name, Path, Size, and so forth. Just set a variable to the CreateFolder function to gain a handle to the newly created folder, then access its properties, methods, and events.

To set a variable to the CreateFolder function, use this syntax:

[VBScript]
Sub CreateFolder
Dim fso, fldr
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.CreateFolder("C:\MyTest")
Response.Write "Created folder: " & fldr.Name
End Sub
[JScript]
function CreateFolder()
{
var fso, fldr;
fso = new ActiveXObject("Scripting.FileSystemObject");
fldr = fso.CreateFolder("C:\\MyTest");
Response.Write("Created folder: " + fldr.Name);
}

Accessing the Object's Properties
Once you have a handle to an object, you can access its properties. For example, to get the name of a particular folder, first create an instance of the object, then get a handle to it with the appropriate method (in this case, the GetFolder method, since the folder already exists).

Use this code to get a handle to the GetFolder method:

[VBScript]
Set fldr = fso.GetFolder("c:\")
[JScript]
var fldr = fso.GetFolder("c:\\");
Now that you have a handle to a Folder object, you can check its Name property.

[VBScript]
Response.Write "Folder name is: " & fldr.Name
[JScript]
Response.Write("Folder name is: " + fldr.Name);
To find out the last time a file was modified, use the following syntax:

[VBScript]
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
' Get a File object to query.
Set f1 = fso.GetFile("c:\detlog.txt")
' Print information.
Response.Write "File last modified: " & f1.DateLastModified
[JScript]
var fso, f1;
fso = new ActiveXObject("Scripting.FileSystemObject");
// Get a File object to query.
f1 = fso.GetFile("c:\\detlog.txt");
// Print information.
Response.Write("File last modified: " + f1.DateLastModified);

QTP & The FileSystemObject (FSO) object model

The FileSystemObject (FSO) object model allows you to use the familiar object.method syntax with a rich set of properties, methods, and events to process folders and files.

Use this object-based tool with:

  • HTML to create Web pages
  • Windows Scripting Host to create batch files for Microsoft Windows
  • Script Control to provide a scripting capability to applications developed in other languages
Because use of the FSO on the client side raises serious security issues about providing potentially unwelcome access to a client's local file system, this documentation assumes use of the FSO object model to create scripts executed by Internet Web pages on the server side. Since the server side is used, the Internet Explorer default security settings do not allow client-side use of the FileSystemObject object. Overriding those defaults could subject a local computer to unwelcome access to the file system, which could result in total destruction of the file system's integrity, causing loss of data, or worse.

The FSO object model gives your server-side applications the ability to create, alter, move, and delete folders, or to detect if particular folders exist, and if so, where. You can also find out information about folders, such as their names, the date they were created or last modified, and so forth.

The FSO object model also makes it easy to process files. When processing files, the primary goal is to store data in a space- and resource-efficient, easy-to-access format. You need to be able to create files, insert and change the data, and output (read) the data. Since storing data in a database, such as Access or SQL Server, adds a significant amount of overhead to your application, storing your data in a binary or text file may be the most efficient solution. You may prefer not to have this overhead, or your data access requirements may not require all the extra features associated with a full-featured database.

The FSO object model, which is contained in the Scripting type library (Scrrun.dll), supports text file creation and manipulation through the TextStream object. Although it does not yet support the creation or manipulation of binary files, future support of binary files is planned.

Reading PDF file using QTP

Yesterday I receive a query from a reader of this website.

I have report in PDF file and I need to capture and validate data from PDF file. Could you please let me know how to retrieve data from PDF file using QTP 9.5 ?


Well so far, I know two methods to do it:
1. You can use a 3rd party API for that.
2. Other method to use some DOS tools like PSVIEW which can convert PDF image to text.


For third party API:
If you have Acrobat Writer installed you use ArcoExch object to manipulate pdf files.

Function GetPDFPageCount(filename)
Dim pdfFile,Acroapp,pdf
'PDF File preparations
Set Acroapp = CreateObject("AcroExch.App")
Set pdf = CreateObject("AcroExch.PDDoc")
pdf.Open filename,"temp"
Set pdfFile = pdf.GetPDDoc
GetPDFPageCount = pdfFile.GetNumPages
Set pdffile = nothing
Acroapp.Exit
End Function

Other option is, there is a free library for PDF manipulation is available :
http://www.topshareware.com/Quick-PDF-Library-(public-beta)-download-67987.htm

I never used it, but I think it may help you.
Hope it helps.

QTP Tests Using Keyword-Driven Testing

Keyword-driven testing advantages include the following:

1. In QTP, Keyword-driven testing enables you to design your tests at a business level rather than at the object level. For example, QTP may recognize a single option selection in your application as several steps: a click on a button object, a mouse operation on a list object, and then a keyboard operation on a list sub-item. You can create an appropriately-named function to represent all of these lower-level operations in a single, business-level keyword.

2. By incorporating technical operations, such as a synchronization statement that waits for client-server communications to finish, into higher level keywords, tests are easier to read and easier for less technical application testers to maintain when the application changes.

3. Keyword-driven testing naturally leads to a more efficient separation between resource maintenance and test maintenance. This enables the automation experts to focus on maintaining objects and functions while application testers focus on maintaining the test structure and design.


4. When you record tests, you may not notice that new objects are being added to the local object repository. This may result in many testers maintaining local object repositories with copies of the same objects. When using a keyword-driven methodology, you select the objects for your steps from the existing object repository. When you need a new object, you can add it to your local object repository temporarily, but you are also aware that you need to add it to the shared object repository for future use.

5. When you record a test, QTP enters the correct objects, methods, and argument values for you. Therefore, it is possible to create a test with little preparation or planning. Although this makes it easier to create tests quickly, such tests are harder to maintain when the application changes and often require re-recording large parts of the test.

6. When you use a keyword-driven methodology, you select from existing objects and operation keywords. Therefore, you must be familiar with both the object repositories and the function libraries that are available. You must also have a good idea of what you want your test to look like before you begin inserting steps. This usually results in well-planned and better-structured tests, which also results in easier long-term maintenance.

7. Automation experts can add objects and functions based on detailed product specifications even before a feature has been added to a product. Using keyword-driven testing, you can begin to develop tests for a new product or feature earlier in the development cycle.

QTP Answers to Tricky Questions

Answer 1: In QTP point of view we automation applications where there is proper addin.There are few cases where we can use win32 API and shell programming to acheive.

EX use win32 query to get the handle or processid of the app and use some api to act on it...this will be a work around not a solution.

Answer 2: Ans: use DHTML properties ....uses object.attributes...u will get all DHTML properties of that particular element in a collection.

Answer 3: Disadvantages of Smart Identification: There are many out of which is time consuming it eats lot of time and some times it yields wrong results also in case of dynamic environment.
If u enable smart identification when particular object description is mismatched it will take much time to
recognize that object.And for identifying which object decryption is mismatched we have to verify the qtp results.

If disable smart identification qtp will through error in that particular statement
Answer 4: I think Space and time may be the constraints, because i never used it. it is pretty waste of time to use it.

Answer 5: HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\QuickTest Professional\Configuration_UI\ScriptMgr

Create a new String value with name AltProgID and value "Mercury.JSScriptMgr" and change the value of "Create" to 1

Create a new child key inside the key
HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\QuickTest Professional\Configuration_UI\ScriptConstants
{0ECD5785-BE7D-11d4-8EAF-11135659EC56}

Repeat the same steps for the below key
HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\QuickTest Professional\Configuration

Open
C:\Program Files\Mercury Interactive\QuickTest Professional\bin\QTEditor.ini
Add the below parameter to [General options]
AllowJavaScript = 1
DisableVBScript = 1

Answer 7: U can record but not as a web application but a standard windows application

ex:
Window("Mozilla Firefox").WinObject("MozillaWindowClass").Type "naveen"

Answer 8: Repository parameters enable you to specify that certain property values should be parameterized, but leave the actual parameterization to be defined in each test that is associated with the object repository that contains the parameterized test object property values.
Repository parameters are useful when you want to create and run tests on an object that changes dynamically


repositoriescollection is a collection object that enables you to programmatically manage the run-time collection of shared object repository files associated with the current action

for more details refere QTP Help file.

Answer 9: checkout for .VOT files in dat foler of the installation

Answer 10: NO



Tricky QTP questions for all !!!

1. How will you automate a window which while spying is not returning any property value ??

2. How do you find the color and font of all the links on the page???

3. what are the disadvantages of smart identification.??

4.what are the disadvantages of recovery scenario??

5.How can you execute javascript on qtp??

6.What are the basic prerequisites required in automating an infragistics controls based application?


7.Can i record a web based application on Mozilla??

8.What is the difference between Repository Parameter and Repositories Collection ??

9.How to copy Virtual Object Manager from one computer to another computer??

10.Can we use GetRoProperty method to get index or location of link in web application??

Click here for Answers.