Wednesday, October 12, 2011

Many a times you may need to interact with text files using QTP. Interaction can be(but not limited to) in the form of reading input from a file, writing output to a file. This post describe in detail "File handling using QTP".
We use FSO object to do this.
What is FSO?
FSO stands for File System Object. This is used to support text file creation and manipulation through the TextStream object and is contained in the Scripting type library (Scrrun.dll)
The FSO Object Model has a rich set of properties, methods and events to process folders and files.
How to create a file?
We first create a FSO object using CreateObject and then create a text file using CreateTextFile.
For Example: Suppose you want to create a file called "test.txt" located in C:

Dim fso, file, file_location
file_location = "C:\file_location"
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set file = fso.CreateTextFile(file_location, True) // True--> file is to be overwritten if it already exists else false

We would use the same example for the rest of this post.

How to open a file?

Set file= fso.OpenTextFile("C:\file_location", ForWriting, True)
//2nd argument can be ForReading, ForWriting, ForAppending
//3rd argument is "True" if new file has to be created if the specified file doesn’t exist else false, blank signify false.

How to read content from a file?
Use ReadLine() method
For example:

Set file= fso.OpenTextFile("C:\file_location", ForReading, True) //2nd argument should always be "ForReading" in order to read contents from a file
Do while file.AtEndofStream <> True
data = file.ReadLine()
msgbox data
Loop

How to write content to a file?
You can use Write() or WriteLine() Methods to write text into a file. The difference between the Write() and WriteLine() Method is that the latter automatically inserts a new line character while the former doesn’t insert a new line character.
For example:

Set file= fso.OpenTextFile("C:\file_location", ForWriting, True) //2nd argument should always be "ForWriting" in order to write contents to a file
file.Write("This is a place to get all your qtp")
file.Write("questions and answers solved.")
//Output will be:
This is a place to get all your qtp questions and answers solved.
while
file.WriteLine("This is a place to get all your qtp")
file.Write("questions and answers solved.")
//Output will be:
This is a place to get all your qtp
questions and answers solved.

How to delete content?
Use DeleteFile() method to delete a file from a particular location
Foe Example:

file_location = "C:\file_location"
Set fso = CreateObject(“Scripting.FileSystemObject”)
fso.DeleteFile(file_location)

How-QTP-identifies-objects ?

Understanding the Smart Identification Process


If QuickTest activates the Smart Identification mechanism during a run session (because it was unable to identify an object based on its learned description), it follows the following process to identify the object:




1. QuickTest "forgets" the learned test object description and creates a new object candidate list containing the objects (within the object's parent object) that match all of the properties defined in the Base Filter Properties list.




2. QuickTest filters out any object in the object candidate list that does not match the first property listed in the Optional Filter Properties list. The remaining objects become the new object candidate list.



3. QuickTest evaluates the new object candidate list:

o If the new object candidate list still has more than one object, QuickTest uses the new (smaller) object candidate list to repeat step 2 for the next optional filter property in the list.

o If the new object candidate list is empty, QuickTest ignores this optional filter property, returns to the previous object candidate list, and repeats step 2 for the next optional filter property in the list.

o If the object candidate list contains exactly one object, then QuickTest concludes that it has identified the object and performs the statement containing the object.



4. QuickTest continues the process described in steps 2 and 3 until it either identifies one object, or runs out of optional filter properties to use.

If, after completing the Smart Identification elimination process, QuickTest still cannot identify the object, then QuickTest uses the learned description plus the ordinal identifier to identify the object.

If the combined learned description and ordinal identifier are not sufficient to identify the object, then QuickTest stops the run session and displays a Run Error message.



Reviewing Smart Identification Information in the Test Results

If the learned description does not enable QuickTest to identify a specified object in a step, and a Smart Identification definition is defined (and enabled) for the object, then QuickTest tries to identify the object using the Smart Identification mechanism.

If QuickTest successfully uses Smart Identification to find an object after no object matches the learned description, the Test Results receive a warning status and indicate that the Smart Identification mechanism was used.

If the Smart Identification mechanism cannot successfully identify the object, QuickTest uses the learned description plus the ordinal identifier to identify the object. If the object is still not identified, the test or component fails and a normal failed step is displayed in the results.



Walking Through a Smart Identification Example

The following example walks you through the object identification process for an object.

Suppose you have the following statement in your test or component:

Browser("Mercury Tours").Page("Mercury Tours").Image("Login").Click 22,17

When you created your test or component, QuickTest learned the following object description for the Login image:





However, at some point after you created your test or component, a second login button (for logging into the VIP section of the Web site) was added to the page, so the Web designer changed the original Login button's alt tag to: basic login.

The default description for Web Image objects (alt, html tag, image type) works for most images in your site, but it no longer works for the Login image, because that image's alt property no longer matches the learned description. Therefore, when you run your test or component, QuickTest is unable to identify the Login button based on the learned description. However, QuickTest succeeds in identifying the Login button using its Smart Identification definition.

The explanation below describes the process that QuickTest uses to find the Login object using Smart Identification:

1. According to the Smart Identification definition for Web image objects, QuickTest learned the values of the following properties when you recorded the click on the Login image:





2. QuickTest begins the Smart Identification process by identifying the five objects on the Mercury Tours page that match the base filter properties definition (html tag = INPUT and image type = Image Button). QuickTest considers these to be the object candidates and begins checking the object candidates against the Optional Filter Properties list.



3. QuickTest checks the alt property of each of the object candidates, but none have the alt value: Login, so QuickTest ignores this property and moves on to the next one.



4. QuickTest checks the name property of each of the object candidates, and finds that two of the objects (both the basic and VIP Login buttons) have the name: login. QuickTest filters out the other three objects from the list, and these two login buttons become the new object candidates.



5. QuickTest checks the file name property of the two remaining object candidates. Only one of them has the file name login.gif, so QuickTest correctly concludes that it has found the Login button and clicks it.

Step-by-Step Instructions for Configuring a Smart Identification Definition

You use the Smart Identification Properties dialog box, accessible from the Object Identification dialog box, to configure the Smart Identification definition for a test object class.



To configure Smart Identification properties:


1. Choose Tools > Object Identification. The Object Identification dialog box opens.

2. Select the appropriate environment in the Environment list. The test object classes associated with the selected environment are displayed in the Test object classes list.

Note: The environments included in the Environment list are those that correspond to the loaded add-in environments.



3. Select the test object class you want to configure.



4. Click the Configure button next to the Enable Smart Identification check box. The Configure button is enabled only when the Enable Smart Identification option is selected. The Smart Identification Properties dialog box opens:



5. In the Base Filter Properties list, click Add/Remove. The Add/Remove Properties dialog box for base filter properties opens.



6. Select the properties you want to include in the Base Filter Properties list and/or clear the properties you want to remove from the list.

Note: You cannot include the same property in both the base and optional property lists.

You can specify a new property by clicking New and specifying a valid property name in the displayed dialog box.

Tip: You can also add property names to the set of available properties for Web objects using the attribute/ notation. To do this, click New. The New Property dialog box opens. Enter a valid property in the format attribute/ and click OK. The new property is added to the Base Filter Properties list. For example, to add a property called MyColor, enter attribute/MyColor.



7. Click OK to close the Add/Remove Properties dialog box. The updated set of base filter properties is displayed in the Base Filter Properties list.



8. In the Optional Filter Properties list, click Add/Remove. The Add/Remove Properties dialog box for optional filter properties opens.



9. Select the properties you want to include in the Optional Filter Properties list and/or clear the properties you want to remove from the list.

Note: You cannot include the same property in both the base and optional property lists.

You can specify a new property by clicking New and specifying a valid property name in the displayed dialog box.

Tip: You can also add property names to the set of available properties for Web objects using the attribute/ notation. To do this, click New. The New Property dialog box opens. Enter a valid property in the format attribute/ and click OK. The new property is added to the Optional Filter Properties list. For example, to add a property called MyColor, enter attribute/MyColor.



10. Click OK to close the Add/Remove Properties dialog box. The properties are displayed in the Optional Filter Properties list.

11. Use the up and down arrows to set your preferred order for the optional filter properties. When QuickTest uses the Smart Identification mechanism, it checks the remaining object candidates against the optional properties one-by-one according to the order you set in the Optional Filter Properties list until it filters the object candidates down to one object.

regular expression in VB Script

A regular expression is a string that describes or matches a set of strings. It is often called a pattern as it describes set of strings.

Given underneath is one of the most widely used and ever confused BackLash character. The remaining expressions are serialized below that.


Using the Backslash Character
A backslash (\) instructs QuickTest to treat the next character as a literal character, if it is otherwise a special character. The backslash (\) can also instruct QuickTest to recognize certain ordinary characters as special characters. For example, QuickTest recognizes \n as the special newline character.
For example:
w matches the character w
\w is a special character that matches any word character including underscore
For example, in QTP, while entering the URL of a website,
http://mercurytours.mercuryinteractive.com
The period would be mistaken as an indication of a regular expression. To indicate that the period is not part of a regular expression, you would enter it as follows:
mercurytours\.mercuryinteractive\.com Note: If a backslash character is used before a character that has no special meaning, the backslash is ignored. For example, \z matches z.

Expressions & Explanation
Special characters and sequences are used in writing patterns for regular expressions. The following describes the characters and sequences that can be used.


\

Marks the next character as either a special character or a literal. For example, "n" matches the character "n". "\n" matches a newline character. The sequence "\\" matches "\" and "\(" matches "(".

^

Matches the beginning of input.

$

Matches the end of input.

*

Matches the preceding character zero or more times. For example, "zo*" matches either "z" or "zoo".

+

Matches the preceding character one or more times. For example, "zo+" matches "zoo" but not "z".

?

Matches the preceding character zero or one time. For example, "a?ve?" matches the "ve" in "never".

.

Matches any single character except a newline character.

(pattern)

Matches pattern and remembers the match. The matched substring can be retrieved from the resulting Matches collection, using Item [0]...[n]. To match parentheses characters ( ), use "\(" or "\)".

xy

Matches either x or y. For example, "zwood" matches "z" or "wood". "(zw)oo" matches "zoo" or "wood".

{n}

n is a nonnegative integer. Matches exactly n times. For example, "o{2}" does not match the "o" in "Bob," but matches the first two o's in "foooood".

{n,}

n is a nonnegative integer. Matches at least n times. For example, "o{2,}" does not match the "o" in "Bob" and matches all the o's in "foooood." "o{1,}" is equivalent to "o+". "o{0,}" is equivalent to "o*".

{n,m}

m and n are nonnegative integers. Matches at least n and at most m times. For example, "o{1,3}" matches the first three o's in "fooooood." "o{0,1}" is equivalent to "o?".

[xyz]

A character set. Matches any one of the enclosed characters. For example, "[abc]" matches the "a" in "plain".

[^xyz]

A negative character set. Matches any character not enclosed. For example, "[^abc]" matches the "p" in "plain".

[a-z]

A range of characters. Matches any character in the specified range. For example, "[a-z]" matches any lowercase alphabetic character in the range "a" through "z".

[^m-z]

A negative range characters. Matches any character not in the specified range. For example, "[m-z]" matches any character not in the range "m" through "z".

\b

Matches a word boundary, that is, the position between a word and a space. For example, "er\b" matches the "er" in "never" but not the "er" in "verb".

\B

Matches a non-word boundary. "ea*r\B" matches the "ear" in "never early".

\d
-Matches a digit character. Equivalent to [0-9].

\D -
Matches a non-digit character. Equivalent to [^0-9].

\f -
Matches a form-feed character.

\n -
Matches a newline character.

\r

Matches a carriage return character.

\s

Matches any white space including space, tab, form-feed, etc. Equivalent to "[ \f\n\r\t\v]".

\S

Matches any nonwhite space character. Equivalent to "[^ \f\n\r\t\v]".

\t

Matches a tab character.

\v

Matches a vertical tab character.

\w

Matches any word character including underscore. Equivalent to "[A-Za-z0-9_]".

\W

Matches any non-word character. Equivalent to "[^A-Za-z0-9_]".

\num

Matches num, where num is a positive integer. A reference back to remembered matches. For example, "(.)\1" matches two consecutive identical characters.

\n

Matches n, where n is an octal escape value. Octal escape values must be 1, 2, or 3 digits long. For example, "\11" and "\011" both match a tab character. "\0011" is the equivalent of "\001" & "1". Octal escape values must not exceed 256. If they do, only the first two digits comprise the expression. Allows ASCII codes to be used in regular expressions.

\xn

Matches n, where n is a hexadecimal escape value. Hexadecimal escape values must be exactly two digits long. For example, "\x41" matches "A". "\x041" is equivalent to "\x04" & "1". Allows ASCII codes to be used in regular expressions.

Reference:
QTP Documentation-Pattern property

Code optimisation in QTP | Make your QTP scripts perform better

This post refers to a thought provoking question which was asked on Testing Tools forum. In this query jp@QTP is looking for ways to optimize QTP scripts for best performance. Everyone knows we use automated testing tools to optimize our testing process. Unless you make full use of the capability of the tool and unless a tool is used sensibly and with proper planning, it would not yield any results. Just record-and-playback is never the solution for any project. You need to go deep inside to understand the intricacies of any tool. Any software testing tool is only as good as the test engineer using it. On those thoughts, I feel this was one of the best questions asked in the forums of late.
Well, here are some of my tips and tricks to optimize the QTP scripts:

  • Launch QTP using a .vbs file and not the QTP desktop icon. You will notice a substantial increase in speed. [Refer the earlier post on How to open QTP using vbs file? ,you just need the 1st point of that post]
  • For large tests, always define variables, function in an external .vbs file and not inside a reusable action. Attach these files with your test scripts. If you define a variable or a function in an action, on every iteration of your test run, memory(RAM) will be allocated to those variables/functions and would not be released. Now as your script starts consuming more and more RAM, your System Under Test (SUT) will tend to become slower.
  • While running, QTP consumes a lot of memory by itself. It is always advisable to have lots of available RAM( much more than what is recommended by HP) and good processor speed on a system where you intend to install QTP. When you have tests (and hence QTP) running for a prolonged period if time, there are chances of memory leaks. To avoid memory leakage always restart QTP at some intervals of time. Using AOM you can automate this process. [If you want to go into details of effect of RAM on speed of computer read the post on RAM, Memory Usage thoroughly]
  • Avoid using hard coded wait(x) statement. Wait statement waits for full x seconds, even if the event has already occurred. Instead use .sync or exist statement. While using exist statement always have a value inside it.

For ex: .Exist(10) Here QTP will wait max till 10 seconds and if it finds the object at (say) 3 secs , it will resume the execution immediately thereby saving your precious time. On the other hand if you leave the parenthesis blank, QTP would wait for object synchronization timeout you have mentioned under File > Test Settings > Run Tab.

  • Make full use of what HP-QTP has provided you in the tool IDE. Use “Automatically Generate “With” statements after recording” option present under Tools > Options > General Tab. This will not only make your code look neater but also make your scripts perform better.
  • Make your own judgement whether you want to go for Descriptive Programming or Object Repository or mixed approach. Each approach has it own pros and cons that in turn is related to QTP performance.
  • Unless absolutely required, uncheck the options “Save still image capture to results” and “Save movie to results” present under Tools > Options > Run tab. These options definitely have some bearing on QTP run time performance.
  • Make the Run Mode as “fast”. This setting is present under Tool > Options > Run tab. Note: If you intend to run your scripts from QC no need to worry about this option, as the scripts WILL run in fast mode whether you want or not.
  • If you are new to automation or QTP. Read this beginner article on Automation Object Model (AOM). AOM simplifies many aspects of QTP scripting. It can help you in controlling QTP from an external file.

FAQ for QTP | Useful Tips

Sharing some of the useful tips on QTP I used while working and found from sqaforums.I urge the readers to share their experiences/tips they have used while working on QTP. You can use the comments section to do the same.

1) How to add a constant number in a datatable?
This is more to do with MS excel then QTP!! but useful to know because at times it becomes frustrating to the novices.
Just append ' to the number
Ex: if you wish to enter 1234567 in datatable then write it as '1234567

2) How can i check if a parameter exists in DataTable or not?
The best way would be to use the below code:
on error resume next
val=DataTable("ParamName",dtGlobalSheet)
if err.number<> 0 then
'Parameter does not exist
else
'Parameter exists
end if

3) How can i check if a checkpoint passes or not?
chk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))
if chk_PassFail then
MsgBox "Check Point passed"
else MsgBox "Check Point failed"
end if

4) My test fails due to checkpoint failing, Can i validate a checkpoint without my test failing due to checpoint failure?
Reporter.Filter = rfDisableAll 'Disables all the reporting stuff
chk_PassFail = Browser(...).Page(...).WebEdit(...).Check (Checkpoint("Check1"))
Reporter.Filter = rfEnableAll 'Enable all the reporting stuff
if chk_PassFail then
MsgBox "Check Point passed"
else
MsgBox "Check Point failed"
end if

5) What is the difference between an Action and a function?
Action is a thing specific to QTP while functions are a generic thing which is a feature of VB Scripting. Action can have a object repository associated with it while a function can't. A function is just lines of code with some/none parameters and a single return value while an action can have more than one output parameters.

6) Where to use function or action?
Well answer depends on the scenario. If you want to use the OR feature then you have to go for Action only. If the functionality is not about any automation script i.e. a function like getting a string between to specific characters, now this is something not specific to QTP and can be done on pure VB Script, so this should be done in a function and not an action. Code specific to QTP can also be put into an function using DP. Decision of using function/action depends on what any one would be comfortable using in a given situation.

7) When to use a Recovery Scenario and when to us on error resume next?
Recovery scenarios are used when you cannot predict at what step the error can occur or when you know that error won't occur in your QTP script but could occur in the world outside QTP, again the example would be "out of paper", as this error is caused by printer device driver. "On error resume next" should be used when you know if an error is expected and dont want to raise it, you may want to have different actions depending upon the error that occurred. Use err.number & err.description to get more details about the error.

8) How to use environment variable?
A simple defintion could be... it is a variable which can be used across the reusable actions and is not limited to one reusable action.
There are two types of environment variables:
1. User-defined
2. Built-in
We can retrieve the value of any environment variable. But we can set the value of only user-defined environment variables.

To set the value of a user-defined environment variable:
Environment (VariableName) = NewValue

To retrieve the value of a loaded environment variable:
CurrValue = Environment (VariableName)

Example
The following example creates a new internal user-defined variable named MyVariable with a value of 10, and then retrieves the variable value and stores it in the MyValue variable.

Environment.Value("MyVariable")=10
MyValue=Environment.Value("MyVariable")
9) What are the files and subfolders of a QuickTest Professional test?
The files and folders hold binary and text data that are required for the test to run successfully.
The following table provides a description, the type, and comments regarding the files that make up a QuickTest Professional test.

File Name

Description

Type

Comments Regarding File

Test.tsp

Test settings

Binary

Do not edit

Default.xls

Data table parameters

Excel similar

Can be edited using Excel

Parameters.mtr

Parameterization information

Binary

Do not edit

Action

Action folder (See other table)



Default.cfg

Load test configuration file

Text

Do not edit

Default.prm

Load test configuration file

Text

Do not edit

Default.usp

Load test configuration file

Text

Do not edit

.usr

Load test configuration file

Text

Do not edit

Thick_usr.dat

Load test configuration file

Text

Do not edit

Thin_usr.dat

Load test configuration file

Text

Do not edit
Files within Action folder:

File Name

Description

Type

Comments Regarding File

Script.mts

Action script

Text

Edit text preceding the @@ sign only

Resource.mtr

Object Repository

Binary

Do not edit

Snapshots

Active screen files

Folder

Do not edit
There are few more files extensions like
.MTB Batch File
.LCK Locked
10) How to rename a checkpoint (QTP 9.0)?
Example:
Window("Notepad").WinEditor("Edit").Check CheckPoint("Edit")
In the above example, the user would like to change the name of the CheckPoint object from "Edit" to something more meaningful.
Note:
This functionality is new to QuickTest Professional 9.0.This is not available for QTP 8.2 and below.
1. Right-click on the Checkpoint step in the Keyword View or on the Checkpoint object in Expert View.
2. Select "Checkpoint Properties" from the pop-up menu.
3. In the Name field, enter the new checkpoint name.
4. Click . The name of the checkpoint object will be updated within the script.
Example:
Window("Notepad").WinEditor("Edit").Check CheckPoint("NewCheckPointName")
Note:
You must use the QuickTest Professional user interface to change the name of the checkpoint. If you manually change the name of the checkpoint in the script, QuickTest Professional will generate an error during replay. The error message will be similar to the following:
"The "" CheckPoint object was not found in the Object Repository. Check the Object Repository to confirm that the object exists or to find the correct name for the object."
The CheckPoint object is not a visible object within the object repository, so if you manually modify the name, you may need to recreate the checkpoint to resolve the error.

11) Does QuickTest Professional support Internet Explorer 7.0?
QuickTest Professional 9.1
QuickTest Professional 9.1 supports Microsoft Internet Explorer 7.0 Beta 3. Internet Explorer version 7.0 is now certified to work and to be tested with QuickTest Professional version 9.1.
QuickTest Professional 9.0
QuickTest Professional 9.0 supports Internet Explorer 7.0 Beta 2.
QuickTest Professional 8.2 and below
QuickTest Professional 8.2 and below do not include support for Internet Explorer 7.0.
Does QuickTest Professional support Firefox?
QuickTest Professional 9.1 and 9.2
QuickTest Professional 9.1 provides replay support for Mozilla Firefox 1.5 and Mozilla Firefox 2.0 Alpha 3 (Alpha-level support for Bon Echo 2.0a3).
Notes:
QuickTest Professional 9.1 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.
The .Object property for web objects is not supported in FireFox.
QuickTest Professional 9.0
QuickTest Professional 9.0 provides replay support for Mozilla FireFox 1.5.
Notes:
QuickTest Professional 9.0 will not record on FireFox. You can record a test on Microsoft Internet Explorer and run it on any other supported browser, such as FireFox.
The .Object property for web objects is not supported in FireFox.
QuickTest Professional 8.2 and below
QuickTest Professional 8.2 and below do not have support for Firefox.


12) Problem
After Quick Test Professional is started, Windows Media will not start. It returns the error message "wmplayer.exe has generated errors and will be closed by Windows. You will need to restart the program. An error log is being created."
If you start Window's Media Player first, it will continue to work normally after starting QuickTest Professional.
Solution:
Include the Windows Media Player's executable in the NoBBTApps section of the mic.ini file
1. Close QuickTest Professional.
2. Go to \bin\mic.ini.
3. Include wmplayer.exe in the NoBBTApps section of mic.ini file.
Example:
[NoBBTApps]
wmplayer.exe=rek
4. Save the mic.ini file and restart QuickTest Professional.
13) What is the lservrc file in QTP?

The lservrc file contains the license codes that have been installed
The lservrc file contains the license codes that have been installed. Whenever a new license is created, the license code is automatically added to this file. The lservrc file is a text file, with no extension.
File Location:
1) For a Concurrent (Floating) license installation:

C:\Program Files\Common Files\SafeNet\ SafeNet Sentinel\ LM Server\WinN

2) For a Seat (Stand-alone) license installation:

  • QTP 9.2 and below versions: C:\Program Files\Common Files\Mercury Interactive\License Manager\lservrc
  • QTP 9.5 and above versions: C:\Documents and Settings\All Users\Application Data\HP\Functional testing\License
14) What to do if you are not able to run QTP from quality center?
This is for especially for newbies with QTP.
Check that you have selected Allow other mercury products to run tests and components from Tools--> Options--> Run Tab.
Check out QTP and QC guide.

15) Does QuickTest Professional support Macintosh operating systems?
No, QTP is not expected to run on this OS.

Source : Internet

Ways to Launch your application

Four different ways to launch your application are mentioned below:

1)
SystemUtil.Run

SystemUtil.Run (
FileName, Parameters, Path, Operation )
FileName - The name of the file you want to run.
Parameters - If the specified FileName is an executable file, use the Parameters argument to specify any parameters to be passed to the application.
Path - The default directory of the application or file.
Operation - The action to be performed. If this argument is blank (""), the open operation is performed.
The following operations can be specified for the operation argument of the SystemUtil.Run method:
open - Opens the file specified by the FileName parameter. The file can be an executable file, a document file, or a folder. Non-executable files are open in the associated application.
edit - Launches an editor and opens the document for editing. If the FileName argument does not specify an editable document file, the statement fails.
explore - Explores the folder specified by the FileName argument.
find - Initiates a search starting from the specified folder path.
print - Prints the document file specified by the FileName argument. If the specified file is not a printable document file, the statement fails.
Example:SystemUtil.Run "D:\My Music\Breathe.mp3","","D:\My Music\Details","open"

2)
InvokeApplication

This command is now mainly used for the backward compatability ie to use with the lower versions(below QTP 6.0) of QTP.


InvokeApplication("Full URL as Parameter")

Example:InvokeApplication "C:\Program Files\Internet Explorer\IEXPLORE.EXE http://www.yahoo.com"

3)
VBscript to invoke application

1. Create a "WScript.shell" object.

2. Use the "run" object to launch the application. If the path to your executable contains spaces, use Chr(34) to ensure the path is contained within double quotes.
3. When done, set the shell object to nothing to release it.

Example:

Dim oShellSet oShell = CreateObject ("Wscript.shell")'
Example 1 - run a batch file:oShell.run "F:\jdk1.3.1\demo\jfc\SwingSet2.bat"'
Example 2 - run a Java jar file:oShell.run "java -jar F:\jdk1.3.1\demo\jfc\SwingSet2\SwingSet2.jar"'
Example 3 - launch Internet Explorer:oShell.Run Chr(34) & "C:\Program Files\Internet Explorer\IEXPLORE.EXE" & Chr(34)Set oShell = Nothing

4)
Trivial but useful method

If nothing works out you might try this


You can use the Start -> Run dialog of Windows.

1. Add the Windows Start button to the Object Repository using the "Add Objects" button in Object Repository dialog.
2. Open the Run dialog (Start -> Run), and learn the "Open" edit field and the "OK" button into the Object Repository.
3. Switch to the Expert View, and manually add the lines to open the Run dialog.
Example:Window("Window").WinButton("Button").ClickWindow("Window").Type("R")
4. Manually enter the lines to enter the information to launch the application, and click the "OK" button of the Run dialog.

Example:

Dialog("Run").WinEdit("Open:").Type "c:\WINNT\system32\notepad.exe"
Dialog("Run").WinButton("OK").Click

Special Thanks to : Ankur

Can we create the window application with VBScipt?

Can we create the window application with VBScipt?

yes: using HTML Application (HTA)

An HTML Application (HTA) is a Microsoft Windows application written with HTML and Dynamic HTML. The ability to write HTAs was introduced with Microsoft Internet Explorer 5.0.

HTAs can be made from regular HTML files by simply changing the file extension to .hta. A regular HTML file is confined to the security model of the web browser – i.e. to communicating with the server, manipulating the page’s object model (usually to validate forms and / or create interesting visual effects) and reading / writing cookies. An HTA runs as a fully trusted application and therefore has more privileges than a normal HTML file – for example an HTA can create / edit / remove files and registry entries.

To customize the appearance of an HTA, a new tag, with attributes, is introduced: . This tag appears in the …section of an HTA document.

Because an HTA has more privileges than an HTML page, it cannot be executed via http. Rather, the HTA must be downloaded (just like an EXE file) and executed from local file system.

QTP code Generates for a HTML Application

QTP generates the code as similar to the normal web applications, except that it shows window instead of browser

Example: If the HTML Application has a edit box then code will be

Window(..).Webedit(…).set “value”

Sample code :

This example code creates a HTML app with 3 edit boxes.

Name

Address

Phone

For More information on HTML Application Refer:

http://msdn2.microsoft.com/en-us/library/ms536496.aspx

http://www.microsoft.com/technet/scriptcenter/resources/qanda/htas.mspx

References:MSDN

Search for a particular value in Excel

Set appExcel = CreateObject(“Excel.Application”)
appExcel.visible=true
Set objWorkBook = appExcel.Workbooks.Open (filepath)’opens the sheet

Set objSheet = appExcel.Sheets(“Sheet1″)’ To select particular sheet
With objSheet.UsedRange ‘ select the used range in particular sheet
Set c = .Find (“nn”)’ data to find
For each c in objSheet.UsedRange’ Loop through the used range
If c=”nn” then’ compare with the expected data
c.Interior.ColorIndex = 40′ make the gary color if it finds the data
End If
Set c = .FindNext(c)’ next search

next
End With
objWorkBook.save
objWorkBook.close
set appExcel=nothing

How to Download a file using VbScript

Following is the code to download a file using Vbscript, without using QTP

This code uses the HTMLDom and URLDownloadToFile method from urlmon API.

Since VBScript does support calling Native API methods directly, here I am using Excel macro to declare a function for the urlmon API and running the macro by Excel API from VBscript

Step1: Create a new excel and open the visual basic editor, Insert Module and paste the following code the Module, save the excel file

Private Declare Function URLDownloadToFile Lib “urlmon” Alias _
“URLDownloadToFileA” ( _
ByVal pCaller As Long, ByVal szURL As String, _
ByVal szFileName As String, _
ByVal dwReserved As Long, _
ByVal lpfnCB As Long) As Long
Sub FileSave(strUrl, Des)
r = URLDownloadToFile(0, strUrl, Des, 0, a)

End Sub

Step2: Create a VBS and copy the below code and change the file paths

Set ie = CreateObject(“InternetExplorer.Application”)
ie.navigate “www.google.com
ie.Visible = True
WScript.Sleep 3000
ie.document.all.q.Value = “Testing + doc”
ie.document.all.btnG.Click
WScript.Sleep 1000
Set obj = ie.document.getElementsByTagName(“A”)
For i = 0 To obj.Length
If obj(i).innerText = “Testing Document” Then
hr = obj(i).href
Exit For
End If
Next

arrhr = Split(hr, “/”)
fname = arrhr(UBound(arrhr))
If hr <> “” Then
strUrl = hr
Des = “C:\Documents and Settings\Desktop\” & fname
Set objXL = CreateObject(“Excel.Application”)
With objXL.Application
.Visible = False
‘Open the Workbook
.Workbooks.Open “C:\Documents and Settings\Desktop\Download.xls”
‘Include CARMA in menu, run AutoOpen
objXL.Application.DisplayAlerts = False
x = .Run(“FileSave”, strUrl, Des)
End With
Set objXL = Nothing
MsgBox “Download Completed , the location of the saved file is->” & Des
End If

Set ie = Nothing

‘Special Thanks to Chandan Ray

QTP 11: Complete List of New Features

Here is the complete list of new features that are available in QTP 11

XPath and CSS based object identification

Identify objects not only using normal object identification but with XPath and CSS identifier properties. A much awaited and a killer feature

Good Looking and Enhanced Results Viewer

The new improved results viewer provides an executive summary page with summary data, pie charts and statistics for both the current and previous runs and a quick link to the previous run results.











Easy Regular Expressions

You can now create reg ex with the help of syntax hints. Regular Expression Evaluator is available to test regular expressions that you have created. Good One.

Now identify objects not only in relation to each other but in relation to neighboring objects.

With this feature, QTP 11 has moved beyond the unreliability of ordinal identifiers. Objects identified with ordinal identifiers are good only as long as they maintain their relative positions with respect to each other in the new build of application. In case if this position changes or gets interchanged, ordinal identifiers may go for a toss.
HP has now introduced Visual Relation Identifier.

A visual relation identifier is a set of definitions that enable you to identify the object in the application according its neighboring objects in the application. You can select neighboring objects that will maintain the same relative location to your object, even if the user interface design changes. You define visual relations in the Visual Relation Identifier dialog box, which is accessible from the local or shared object repository, and from the Object Properties dialog box.

Load Function Libraries at Run Time

With the help of LoadFunctionLibrary statement. You can now load a function library when a step runs instead of at the beginning of a run session.

Test Your GUI and UI-Less Application Functionality in One Test

Since QTP is integrated with Service Test, you can now test your GUI and non-GUI based apps in a single run.

Record Support

For FireFox is now available.

Much Awaited Log Tracking is available now

QTP 11 is capable of receiving Java or .NET log framework messages from your application which can then be embedded in the run results.

Embed/Run Javascript in web pages

You can use the new EmbedScript/EmbedScriptFromFile and RunScript/RunScriptFromFile functions to embed JavaScripts in all loaded browser pages. You can use these scripts to perform operations on, or retrieve data from, the browser pages in your application.

Manage Test Data

Improved test data management when integrated with Quality Center

Web 2.0 Toolkit Applications Support

QTP 11 now supports Web 2.0 Toolkit Applications out-of-the-box similar to any other add-ins.

Automatically Parameterize Steps

You can instruct QTP 11 to automatically parameterize test steps at the end of record session.

Silverlight Add-in

To test objects in Silverlight 2 and Silverlight 3 applications. [After installation, Silverlight Add-in is displayed in the Add-in Manager as a child add-in under the WPF Add-in]

Extend WPF and Silverlight Support

You can use WPF and Silverlight Add-in Extensibility SDK to develop support for testing third-party and custom WPF and Silverlight controls that are not supported out-of-the-box

Use Extensibility Accelerator for Web Add-in Extensibility Development

Avoid Downtime Due to License Server Failures

Useful for concurrent license users. With redundant license servers you can create failover, so that if your main license server fails, your remaining servers maintain availability of your licenses without causing any downtime or loss of licenses for users.