Monday, December 21, 2009

Loading Addins at RunTime

'This example opens a test and loads all the add-ins associated with the test.
'There is no unsaved test currently open in QuickTest.
'For more information, see the example for the Test.SaveAs method.

Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim blnNeedChangeAddins ' Declare a flag for indicating whether the test's associated add-ins are currently loaded
Dim arrTestAddins ' Declare the variable for storing the test's associated add-ins

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object

arrTestAddins = qtApp.GetAssociatedAddinsForTest("C:\Tests\Test1") ' Create an array containing the list of addins associated with this test

' Check if all required add-ins are all already loaded
blnNeedChangeAddins = False ' Assume no change is necessary
For Each testAddin In arrTestAddins ' Iterate over the test's associated add-ins list
If qtApp.Addins(testAddin).Status <> "Active" Then ' If an associated add-in is not loaded
blnNeedChangeAddins = True ' Indicate that a change in the loaded add-ins is necessary
Exit For ' Exit the loop
End If

If qtApp.Launched And blnNeedChangeAddins Then
qtApp.Quit ' If a change is necessary, exit QuickTest to modify the loaded add-ins
End If

If blnNeedChangeAddins Then
Dim blnActivateOK
blnActivateOK = qtApp.SetActiveAddins(arrTestAddins, errorDescription) ' Load the add-ins associated with the test and check whether they load successfully.
If Not blnActivateOK Then ' If a problem occurs while loading the add-ins
MsgBox errorDescription ' Show a message containing the error
WScript.Quit ' And end the automation program.
End If
End If

If Not qtApp.Launched Then ' If QuickTest is not yet open
qtApp.Launch ' Start QuickTest (with the correct add-ins loaded)
End If
qtApp.Visible = True ' Make the QuickTest application visible

qtApp.Open "C:\Tests\Test1" ' Open the test
Set qtApp = Nothing ' Release the Application object

Installation Testing Requirements for Client Software

1.Check the required disk space.
2.verify registry changes.
3.Veriy IIS.
4.Verify services.
5.break the installation process in between.
6.Rollback to previous version.
7.test for uninstallation.
8.installation over the network, online installation, patch installation.
9.Database checking on Installation.
10.Shared DLL installation and uninstallation etc.
11.Files or Folders copied.

Thursday, October 29, 2009

Csharp programs compilation

###############start:Compiling a program:start#####################################
csc C:\Gopi\DotNetPgms\HelloWorld.cs
################End:Compiling a library program:End#######################################

###############start:Compiling a library program:start#####################################
csc /target:library /out:MathLibrary.DLL C:\Gopi\DotNetPgms\Add.cs C:\Gopi\DotNetPgms\Mult.cs
################End:Compiling a library program:End#######################################


#################start:Compiling a program which has a dll reference:start###################################
csc /out:TestCode.exe /reference:MathLibrary.DLL C:\Gopi\DotNetPgms\TestCode.cs
################End:Compiling a nunit program:End#######################################


#################start:Compiling a nunitprogram:start###################################
first generate the required dll
csc /target:library /out:bank.DLL C:\Gopi\DotNetPgms\bank.cs
write a nunit code.
add a reference(dll) of actual code,add reference of nunit.framework.dll and add nunit code
csc /target:library /out:accountbank.DLL /reference:nunit.framework.dll,bank.DLL C:\Gopi\DotNetPgms\Arithmetica.cs
################End:Compiling a nunit program:End#######################################

Friday, September 4, 2009

automate the Windows in .Net?

Microsoft Active Accessibility is not a comprehensive solution to automate the Windows UI. There are certain limitations. E.g., using accessibility, we can search for a TextBox control on MS Word Ribbon, but we can not get or set a value in it, which can be done using Microsoft UIA. So, a combination of MSAA and UIA can provide a more promising solution for Windows UI automation.

Random Number Generation within given Range?

Function genRand(upperbound,lowerbound)
msgbox Int((upperbound - lowerbound + 1) * Rnd + lowerbound)
End Function

call genRand(10,1)

Monday, August 17, 2009

Quality Assurance vs Quality Control ?

Product : Process
Reactive : Proactive
Line function : Staff function
Find defects : Prevent defects

QC Vs QA - Examples
Walkthrough : Quality Audit
Testing : Defining Process
Inspection : Selection of tools
Checkpoint review : Training

What is Security Testing ?

* Test by pasting internal url directly into browser address bar without login. Internal pages should not open.
* If you are logged in using username and password and browsing internal pages then try changing url options directly. I.e. If you are checking some publisher site statistics with publisher site ID= 123. Try directly changing the url site ID parameter to different site ID which is not related to logged in user. Access should denied for this user to view others stats.
* Try some invalid inputs in input fields like login username, password, input text boxes. Check the system reaction on all invalid inputs.
* Web directories or files should not be accessible directly unless given download option.
* Test the CAPTCHA for automates scripts logins.
* Test if SSL is used for security measures. If used proper message should get displayed when user switch from non-secure http:// pages to secure https:// pages and vice versa.
* All transactions, error messages, security breach attempts should get logged in log files somewhere on web server.
* Authorization Testing
* Authentication Testing

Friday, August 14, 2009

Sorting the sheets in an Excel file using VB of QTP?

Sub Sort_Sheets()

Dim Sort_Mode_Descending As Boolean
Dim No_of_Sheets As Integer
Dim Outer_Loop As Integer
Dim Inner_Loop As Integer
No_of_Sheets = Sheets.Count
'Change Flag As appropriate
Sort_Mode_Descending = False
For Outer_Loop = 1 To No_of_Sheets
For Inner_Loop = 1 To Outer_Loop
If Sort_Mode_Descending = True Then
If UCase(Sheets(Outer_Loop).Name) > UCase(Sheets(Inner_Loop).Name) Then
Sheets(Outer_Loop).Move Before:=Sheets(Inner_Loop)
End If
End If
If Sort_Mode_Descending = False Then
If UCase(Sheets(Outer_Loop).Name) < UCase(Sheets(Inner_Loop).Name) Then
Sheets(Outer_Loop).Move Before:=Sheets(Inner_Loop)
End If
End If

Next Inner_Loop
Next Outer_Loop

End Sub

Moving to a particular cell in the sheet:
Application.Goto ActiveSheet.Range("A54")

Trunc Function Oracle/PLSQL?

Oracle/PLSQL: Trunc Function (with dates)

In Oracle/PLSQL, the trunc function returns a date truncated to a specific unit of measure.

The syntax for the trunc function is:

trunc ( date, [ format ] )

date is the date to truncate.

format is the unit of measure to apply for truncating. If the format parameter is omitted, the trunc function will truncate the date to the day value, so that any hours, minutes, or seconds will be truncated off.

Below are the valid format parameters:

Unit Valid format parameters
Quarter Q
Week WW
Day DDD, DD, J
Start day of the week DAY, DY, D
Hour HH, HH12, HH24
Minute MI

Applies To:

* Oracle 8i, Oracle 9i, Oracle 10g, Oracle 11g

For example:

trunc(to_date('22-AUG-03'), 'YEAR') would return '01-JAN-03'
trunc(to_date('22-AUG-03'), 'Q') would return '01-JUL-03'
trunc(to_date('22-AUG-03'), 'MONTH') would return '01-AUG-03'
trunc(to_date('22-AUG-03'), 'DDD') would return '22-AUG-03'
trunc(to_date('22-AUG-03'), 'DAY') would return '17-AUG-03'

Thursday, August 13, 2009

Triggers in Oracle PL/SQL ?

Oracle/PLSQL Topics: Creating Triggers

Insert Triggers:



Update Triggers:



Delete Triggers:



Drop Triggers:

Drop a Trigger

Disable/Enable Triggers:

Disable a Trigger

Disable all Triggers on a table

Enable a Trigger

Enable all Triggers on a table


A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation is executed.

The syntax for an BEFORE INSERT Trigger is:

ON table_name
-- variable declarations
-- trigger code
WHEN ...
-- exception handling

trigger_name is the name of the trigger to create.


* You can not create a BEFORE trigger on a view.
* You can update the :NEW values.
* You can not update the :OLD values.

For example:

If you had a table created as follows:

( order_id number(5),
quantity number(4),
cost_per_item number(6,2),
total_cost number(8,2),
create_date date,
created_by varchar2(10)

We could then create a BEFORE INSERT trigger as follows:

CREATE OR REPLACE TRIGGER orders_before_insert
ON orders

v_username varchar2(10);


-- Find username of person performing INSERT into table
SELECT user INTO v_username
FROM dual;

-- Update create_date field to current system date
:new.create_date := sysdate;

-- Update created_by field to the username of the person performing the INSERT
:new.created_by := v_username;


Views in Oracle PL/SQL ?


A view is, in essence, a virtual table. It does not physically exist. Rather, it is created by a query joining one or more tables.
Creating a VIEW

The syntax for creating a VIEW is:

CREATE VIEW view_name AS
SELECT columns
FROM table
WHERE predicates;

For example:

CREATE VIEW sup_orders AS
SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id
and suppliers.supplier_name = 'IBM';

This would create a virtual table based on the result set of the select statement. You can now query the view as follows:

FROM sup_orders;

Updating a VIEW

You can update a VIEW without dropping it by using the following syntax:

SELECT columns
FROM table
WHERE predicates;

For example:

SELECT suppliers.supplier_id, orders.quantity, orders.price
FROM suppliers, orders
WHERE suppliers.supplier_id = orders.supplier_id
and suppliers.supplier_name = 'Microsoft';

Dropping a VIEW

The syntax for dropping a VIEW is:

DROP VIEW view_name;

For example:

DROP VIEW sup_orders;

Frequently Asked Questions

Question: Can you update the data in a view?

Answer: A view is created by joining one or more tables. When you update record(s) in a view, it updates the records in the underlying tables that make up the view.

So, yes, you can update the data in a view providing you have the proper privileges to the underlying tables.

Question: Does the view exist if the table is dropped from the database?

Answer: Yes, in Oracle, the view continues to exist even after one of the tables (that the view is based on) is dropped from the database. However, if you try to query the view after the table has been dropped, you will receive a message indicating that the view has errors.

If you recreate the table (that you had dropped), the view will again be fine.

Saturday, July 25, 2009

Recording modes in QTP?

Analog recording mode records exact mouse and keyboard operations. The track of the operations recorded are stored in an external data file.

Desktop.RunAnalog "Track1" 'event for clicking a button
Desktop.RunAnalog "Track2" 'event for setting text in a text box

'low level
Window("Login").WinObject("Help").Click 9,9 'event for clicking a button
Window("Login").WinObject("Agent Name:1").Click 90,5 'event for setting text in a text box
Window("Login").WinObject("Agent Name:1").Type "gopi" 'event for setting text in a text box

X Optional. An Integer value. The x-coordinate of the click. Note that the specified coordinates are relative to the upper left corner of the object. Default = micNoCoordinate (-9999) -- center of the object.

Y Optional. An Integer value. The y-coordinate of the click. Note that the specified coordinates are relative to the upper left corner of the object. Default = micNoCoordinate (-9999) -- center of the object.

alternative for a wait statement in QTP?

Using Exist Method.


It will wait up to specified time(2sec) when object does not exist.

or increase the global synchronization point

or use WaitProperty

or use Sync() method

Some important properties in QTP?

Property Name Description :

abs_x The object's absolute x-coordinate (left) relative to the screen (in pixels).
abs_y The object's absolute y-coordinate (top) relative to the screen (in pixels).
width The object's width (in pixels).
height The object's height (in pixels).
x The object's x-coordinate (left) relative to the parent window (in pixels).
y The object's y-coordinate (top) relative to the parent window (in pixels).

Wednesday, July 22, 2009

Difference Between Execute() statement and Eval() statement in QTP ?

Evaluates an expression and returns the result.

syntax:[result = ]Eval(expression)

result :
Optional. Variable to which return value assignment is made. If result is not specified, consider using the Execute statement instead.

expression :
Required. String containing any legal VBScript expression.

In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do, result is True; if they are not, result is False. The Eval method always uses the second interpretation, whereas the Execute statement always uses the first.

Sub GuessANumber

Dim Guess, RndNum
RndNum = Int((100) * Rnd(1) + 1)
Guess = CInt(InputBox("Enter your guess:",,0))
If Eval("Guess = RndNum") Then
MsgBox "Congratulations! You guessed it!"
Exit Sub
Guess = CInt(InputBox("Sorry! Try again.",,0))
End If
Loop Until Guess = 0

End Sub

Execute( ) Statement in QTP?

Executes one or more specified statements.

Execute statement
The required statement argument is a string expression containing one or more statements for execution. Include multiple statements in the statement argument, using colons or embedded line breaks to separate them.

In VBScript, x = y can be interpreted two ways. The first is as an assignment statement, where the value of y is assigned to x. The second interpretation is as an expression that tests if x and y have the same value. If they do, result is True; if they are not, result is False. The Execute statement always uses the first interpretation, whereas the Eval method always uses the second.

Note In Microsoft® JScript™, no confusion exists between assignment and comparison, because the assignment operator (=) is different from the comparison operator(==).
The context in which the Execute statement is invoked determines what objects and variables are available to the code being run. In-scope objects and variables are available to code running in an Execute statement. However, it is important to understand that if you execute code that creates a procedure, that procedure does not inherit the scope of the procedure in which it occurred.

Like any procedure, the new procedure's scope is global, and it inherits everything in the global scope. Unlike any other procedure, its context is not global scope, so it can only be executed in the context of the procedure where the Execute statement occurred. However, if the same Execute statement is invoked outside of a procedure (i.e., in global scope), not only does it inherit everything in global scope, but it can also be called from anywhere, since its context is global. The following example illustrates this behavior:

Dim X ' Declare X in global scope.
X = "Global" ' Assign global X a value.
Sub Proc1 ' Declare procedure.
Dim X ' Declare X in local scope.
X = "Local" ' Assign local X a value.
' The Execute statement here creates a
' procedure that, when invoked, prints X.
' It print the global X because Proc2
' inherits everything in global scope.
Execute "Sub Proc2: Print X: End Sub"
Print Eval("X") ' Print local X.
Proc2 ' Invoke Proc2 in Proc1's scope.
End Sub
Proc2 ' This line causes an error since
' Proc2 is unavailable outside Proc1.
Proc1 ' Invoke Proc1.
Execute "Sub Proc2: Print X: End Sub"
Proc2 ' This invocation succeeds because Proc2
' is now available globally.
The following example shows how the Execute statement can be rewritten so you don't have to enclose the entire procedure in the quotation marks:

S = "Sub Proc2" & vbCrLf
S = S & " Print X" & vbCrLf
S = S & "End Sub"
Execute S


execute("func1()") 'output is Hi func2
execute(var1) 'output is Hi func2
execute("Call (" & var1 & ")" ) ''output is Hi func2
eval("func1()") 'output is Hi func2.but always prefer execute statement if there is no return value

assume function library will be like mentioned below..
function func1()
msgbox "Hi func1"
end function
function func1()
msgbox "Hi func2"
end function

Tuesday, July 21, 2009

Regular expressions in QTP?

Regular expressions are mathematical expressions used to match the patterns of property values while running the scripts.
Regular expressions are used to generalize the required property values based on the requirement.

A regular expression is a pattern of text that consists of ordinary characters (for example, letters a through z) and special characters, known as metacharacters. The pattern describes one or more strings to match when searching a body of text. The regular expression serves as a template for matching a character pattern to the string being searched.

Here are some examples of regular expression you might encounter:

JScript VBScript Matches
/^\[ \t]*$/ "^\[ \t]*$" Match a blank line.
/\d{2}-\d{5}/ "\d{2}-\d{5}" Validate an ID number consisting of 2 digits, a hyphen, and another 5 digits.
/<(.*)>.*<\/\1>/ "<(.*)>.*<\/\1>" Match an HTML tag.

The following table contains the complete list of metacharacters and their behavior in the context of regular expressions:

Character Description
\ Marks the next character as either a special character, a literal, a backreference, or an octal escape. For example, 'n' matches the character "n". '\n' matches a newline character. The sequence '\\' matches "\" and "\(" matches "(".
^ Matches the position at the beginning of the input string. If the RegExp object's Multiline property is set, ^ also matches the position following '\n' or '\r'.
$ Matches the position at the end of the input string. If the RegExp object's Multiline property is set, $ also matches the position preceding '\n' or '\r'.
* Matches the preceding subexpression zero or more times. For example, zo* matches "z" and "zoo". * is equivalent to {0,}.
+ Matches the preceding subexpression one or more times. For example, 'zo+' matches "zo" and "zoo", but not "z". + is equivalent to {1,}.
? Matches the preceding subexpression zero or one time. For example, "do(es)?" matches the "do" in "do" or "does". ? is equivalent to {0,1}
{n} n is a nonnegative integer. Matches exactly n times. For example, 'o{2}' does not match the 'o' in "Bob," but matches the two o's in "food".
{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, where n <= m. 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?'. Note that you cannot put a space between the comma and the numbers.
? When this character immediately follows any of the other quantifiers (*, +, ?, {n}, {n,}, {n,m}), the matching pattern is non-greedy. A non-greedy pattern matches as little of the searched string as possible, whereas the default greedy pattern matches as much of the searched string as possible. For example, in the string "oooo", 'o+?' matches a single "o", while 'o+' matches all 'o's.
. Matches any single character except "\n". To match any character including the '\n', use a pattern such as '[.\n]'.
(pattern) Matches pattern and captures the match. The captured match can be retrieved from the resulting Matches collection, using the SubMatches collection in VBScript or the $0…$9 properties in JScript. To match parentheses characters ( ), use '\(' or '\)'.
(?:pattern) Matches pattern but does not capture the match, that is, it is a non-capturing match that is not stored for possible later use. This is useful for combining parts of a pattern with the "or" character (|). For example, 'industr(?:y|ies) is a more economical expression than 'industry|industries'.
(?=pattern) Positive lookahead matches the search string at any point where a string matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?=95|98|NT|2000)' matches "Windows" in "Windows 2000" but not "Windows" in "Windows 3.1". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
(?!pattern) Negative lookahead matches the search string at any point where a string not matching pattern begins. This is a non-capturing match, that is, the match is not captured for possible later use. For example 'Windows (?!95|98|NT|2000)' matches "Windows" in "Windows 3.1" but does not match "Windows" in "Windows 2000". Lookaheads do not consume characters, that is, after a match occurs, the search for the next match begins immediately following the last match, not after the characters that comprised the lookahead.
x|y Matches either x or y. For example, 'z|food' matches "z" or "food". '(z|f)ood' matches "zood" or "food".
[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'.
[^a-z] A negative range characters. Matches any character not in the specified range. For example, '[^a-z]' matches any character not in the range 'a' 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 nonword boundary. 'er\B' matches the 'er' in "verb" but not the 'er' in "never".
\cx Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return character. The value of x must be in the range of A-Z or a-z. If not, c is assumed to be a literal 'c' character.
\d Matches a digit character. Equivalent to [0-9].
\D Matches a nondigit character. Equivalent to [^0-9].
\f Matches a form-feed character. Equivalent to \x0c and \cL.
\n Matches a newline character. Equivalent to \x0a and \cJ.
\r Matches a carriage return character. Equivalent to \x0d and \cM.
\s Matches any whitespace character including space, tab, form-feed, etc. Equivalent to [ \f\n\r\t\v].
\S Matches any non-white space character. Equivalent to [^ \f\n\r\t\v].
\t Matches a tab character. Equivalent to \x09 and \cI.
\v Matches a vertical tab character. Equivalent to \x0b and \cK.
\w Matches any word character including underscore. Equivalent to '[A-Za-z0-9_]'.
\W Matches any nonword character. Equivalent to '[^A-Za-z0-9_]'.
\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.
\num Matches num, where num is a positive integer. A reference back to captured matches. For example, '(.)\1' matches two consecutive identical characters.
\n Identifies either an octal escape value or a backreference. If \n is preceded by at least n captured subexpressions, n is a backreference. Otherwise, n is an octal escape value if n is an octal digit (0-7).
\nm Identifies either an octal escape value or a backreference. If \nm is preceded by at least nm captured subexpressions, nm is a backreference. If \nm is preceded by at least n captures, n is a backreference followed by literal m. If neither of the preceding conditions exists, \nm matches octal escape value nm when n and m are octal digits (0-7).
\nml Matches octal escape value nml when n is an octal digit (0-3) and m and l are octal digits (0-7).
\un Matches n, where n is a Unicode character expressed as four hexadecimal digits. For example, \u00A9 matches the copyright symbol (©).

Monday, July 20, 2009

"Group By" clause in OracleDB?

select dno,count(*) from emp group by dno having count(*)>1;

select * from emp;

UNION operator combines two or more SELECT statements.
used to query data from two or more tables, based on a relationship between certain columns in these tables.

Difference between a "where" clause and a "having" clause.?

Having clause is used only with group functions whereas Where is not used with.

Q: What's the difference between a primary key and a unique key?

A: Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

Unique Key : unique values
Primary Key : Not Null + Unique + nonclustered index

What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table.

Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the indexes

Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete

Delete : (Data alone deleted), Doesn’t perform automatic commit

Retrieve the Top N records from a DataBase Table?

Returning TOP N Records

Returning only the first N records in a SQL query differs quite a bit between database platforms. Here's some samples:

Microsoft SQL Server
SELECT TOP 10 column FROM table

PostgreSQL and MySQL
SELECT column FROM table

SELECT column FROM table

SET rowcount 10
SELECT column FROM table

SELECT FIRST 10 column
FROM table

Due to these differences if you want to keep your code database independent you should use the maxrows attribute in the cfquery tag in ColdFusion. The tradeoffs to database independance is performance, I would expect maxrows to be slower than specifying the rows in the SQL.

SELECT column FROM table

PostgreSQL and MySQL have a cool feature that will let you return an arbitrary range of rows (eg return rows 10-20). This is very handy for displaying pages of records:

SELECT column FROM table
The above query will return rows 20-30

courtesy :

Sunday, July 19, 2009

VBScript Functions..

follow the link :

Do ...Loop statements in VB Script of QTP??

If you don't know how many repetitions you want, use a Do...Loop statement.

The Do...Loop statement repeats a block of code while a condition is true, or until a condition becomes true.

Repeat Code While a Condition is True
You use the While keyword to check a condition in a Do...Loop statement.

Do While i>10
some code

If i equals 9, the code inside the loop above will never be executed.

some code
Loop While i>10

The code inside this loop will be executed at least one time, even if i is less than 10.

Repeat Code Until a Condition Becomes True
You use the Until keyword to check a condition in a Do...Loop statement.

Do Until i=10
some code

If i equals 10, the code inside the loop will never be executed.

some code
Loop Until i=10

The code inside this loop will be executed at least one time, even if i is equal to 10.

Exit a Do...Loop
You can exit a Do...Loop statement with the Exit Do keyword.

Do Until i=10
If i<10 Then Exit Do

The code inside this loop will be executed as long as i is different from 10, and as long as i is greater than 10.

VBScript procedures in QTP?

VBScript Procedures
In VBScript, there are two kinds of procedures:

Sub procedure
Function procedure


VBScript Sub Procedures
A Sub procedure:

is a series of statements, enclosed by the Sub and End Sub statements
can perform actions, but does not return a value
can take arguments
without arguments, it must include an empty set of parentheses ()
Sub mysub()
some statements
End Sub


Sub mysub(argument1,argument2)
some statements
End Sub


VBScript Function Procedures
A Function procedure:

is a series of statements, enclosed by the Function and End Function statements
can perform actions and can return a value
can take arguments that are passed to it by a calling procedure
without arguments, must include an empty set of parentheses ()
returns a value by assigning a value to its name

Function myfunction()
some statements
myfunction=some value
End Function


Function myfunction(argument1,argument2)
some statements
myfunction=some value
End Function


How to Call a Procedure
The line below shows how to call a Function procedure:


Here you call a Function called "findname", the Function returns a value that will be stored in the variable "carname".

Or, you can do like this:

msgbox "Your car is a " & findname()

Here you also call a Function called "findname", the Function returns a value that will be displayed in the message box.

When you call a Sub procedure you can use the Call statement, like this:

Call MyProc(argument)

Or, you can omit the Call statement, like this:

MyProc argument

Variables in VBScript of QTP?

VBScript Variables
As with algebra, VBScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for VBScript variable names:

Must begin with a letter
Cannot contain a period (.)
Cannot exceed 255 characters
In VBScript, all variables are of type variant, that can store different types of data.


Declaring (Creating) VBScript Variables
Creating variables in VBScript is most often referred to as "declaring" variables.

You can declare VBScript variables with the Dim, Public or the Private statement. Like this:

dim x;
dim carname;

Now you have created two variables. The name of the variables are "x" and "carname".

You can also declare variables by using its name in a script. Like this:

carname=some value

Now you have also created a variable. The name of the variable is "carname". However, this method is not a good practice, because you can misspell the variable name later in your script, and that can cause strange results when your script is running.

If you misspell for example the "carname" variable to "carnime", the script will automatically create a new variable called "carnime". To prevent your script from doing this, you can use the Option Explicit statement. This statement forces you to declare all your variables with the dim, public or private statement.

Put the Option Explicit statement on the top of your script. Like this:

option explicit
dim carname
carname=some value


Assigning Values to Variables
You assign a value to a variable like this:


The variable name is on the left side of the expression and the value you want to assign to the variable is on the right. Now the variable "carname" has the value of "Volvo", and the variable "x" has the value of "10".


Lifetime of Variables
How long a variable exists is its lifetime.

When you declare a variable within a procedure, the variable can only be accessed within that procedure. When the procedure exits, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different procedures, because each is recognized only by the procedure in which it is declared.

If you declare a variable outside a procedure, all the procedures on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.


VBScript Array Variables
An array variable is used to store multiple values in a single variable.

In the following example, an array containing 3 elements is declared:

dim names(2)

The number shown in the parentheses is 2. We start at zero so this array contains 3 elements. This is a fixed-size array. You assign data to each of the elements of the array like this:


Similarly, the data can be retrieved from any element using the index of the particular array element you want. Like this:


You can have up to 60 dimensions in an array. Multiple dimensions are declared by separating the numbers in the parentheses with commas. Here we have a two-dimensional array consisting of 10 rows and 6 columns:

Dim x(9,5),z,y
For z = 0 to 9
For y = 0 to 5
x(z,y) = "Row:" & z & space(1) & "Col:" & y

Select Case Statement in VB Script of QTP?

Executes one of several groups of statements, depending on the value of an expression.

Select Case testexpression
[Case expressionlist-n
[statements-n]] . . .
[Case Else expressionlist-n
End Select

Any numeric or string expression.
Required if Case appears. Delimited list of one or more expressions.
One or more statements executed if testexpression matches any part of expressionlist-n.
One or more statements executed if testexpression doesn't match any of the Case clauses.
If testexpression matches any Case expressionlist expression, the statements following that Case clause are executed up to the next Case clause, or for the last clause, up to End Select. Control then passes to the statement following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the elsestatements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values. If no Case expressionlist matches testexpression and there is no Case Else statement, execution continues at the statement following End Select.

Select Case statements can be nested. Each nested Select Case statement must have a matching End Select statement.

The following example illustrates the use of the Select Case statement.

Dim arr(5)
arr(0) = "The"
arr(1) = "World"
arr(2) = "is"
arr(3) = "not"
arr(4) = "good"
arr(5) = "enough"
i=inputbox("enter value for i")

Select Case i
Case 0 :
msgbox arr(0)
Case 1 :
msgbox arr(1)
Case 2 :
msgbox arr(2)
Case 3 :
msgbox arr(3)
Case 4 :
msgbox arr(4)
Case 5 :
msgbox arr(5)
case else :
msgbox "i come if there is no match for your input"

End Select

"on error resume next" or Recovery Scenarios ?

If you can predict that a certain event may happen at a specific point in your test or component, it is recommended to handle that event directly within your test or component by adding steps such as If statements or optional steps or "on error resume next", rather than depending on a recovery scenario. Using Recovery Scenarios may result in unusually slow performance of your tests.They are designed to handle a more generic set of unpredictable events which CANNOT be handled programmatically.

Difference between call by value and call by reference?

Indicates that the argument is passed by value.
Indicates that the argument is passed by reference.

Call Statement
Transfers control to a Sub or Function procedure.

[Call] name [argumentlist]
Optional keyword. If specified, you must enclose argumentlist in

parentheses. For example:
Call MyProc(0)

Required. Name of the procedure to call.
Optional. Comma-delimited list of variables, arrays, or expressions to

pass to the procedure.

You are not required to use the Call keyword when calling a procedure.

However, if you use the Call keyword to call a procedure that requires

arguments, argumentlist must be enclosed in parentheses. If you omit

the Call keyword, you also must omit the parentheses around

argumentlist. If you use either Call syntax to call any intrinsic or

user-defined function, the function's return value is discarded.

var="Hello World"
Call MyFunction(var)
msgbox var
Function MyFunction(byval text)
text = "gopi"
End Function
'output of the above pgm is "Hello World"

var="Hello World"
Call MyFunction(var)
msgbox var
Function MyFunction(byref text)
text = "World is Changed"
End Function
'output of the above pgm is "World is Changed"

Passing by Value is just that. It passes a value to the function to use. It creates a new space to hold this value.

Passing by Reference passes the pointer to the memory space for the variable. This means that anything you do to the variable in the function changes the actual value of the passed variable. This means that if you changed the variable in the function it will be changed outside the function too.

Friday, July 17, 2009

Working with Associated Function Libraries

In QuickTest, you can create function libraries containing functions, subroutines, modules, and so forth, and then associate the files with your test. This enables you to insert a call to a public function or subroutine in the associated function library from that test. (Public functions stored in function libraries can be called from any associated test, whereas private functions can be called only from within the same function library.)

If a test can no longer access a function that was used in a step (for example, if the function was deleted from the associated function library), the icon is displayed adjacent to the step in the Keyword View. When you run the test, an error will occur when it reaches the step using the nonexistent function.

Note: Any text file written in standard VBScript syntax can be used as a function library.

You can specify the default function libraries for all new tests in the Test Settings dialog box (File > Settings > Resources tab). After a test is created, the list of default function libraries is integrated into the test. Therefore any changes to the default function libraries list in the Test Settings dialog box do not affect existing tests.

You can edit the list of associated function libraries for an existing test in the Test Settings dialog box. For more information, see Defining Resource Settings for Your Test.


In addition to the functions available in the associated function libraries, you can also call a function contained in any function library (or VBscript file) directly from any action using the ExecuteFile function. You can also insert ExecuteFile statements within an associated function library. For more information, see Executing Externally-Defined Functions from Your Test.
You cannot debug a file that is called using an ExecuteFile statement, 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 correctly displayed

Library files in QTP are used to declare functions that are needed to be used across actions

A Library File included on the Resource tab are placed in the test’s Global namespace at runtime, and are therefore shared and accessible by all Actions included in the test.

Including a library in a test Action, using the ExecuteFile(“libname”) QTP statement. Libraries included in this manner are placed in the including Action’s namespace, and therefore may only be used by the including Action’s code.

It is also possible to use one or more ExecuteFile(“libname”) statements within a library included via the Test Settings Resource tab as well. In this scenario all library files are placed in the test’s Global namespace.

And also a library file can be included from External VBA file directly by using QTA APPLICATION object.

Most frequent http error codes we see while testing

http error code :400
Its Client Error Code..The request was denied due to a syntax error in the request.

http error code :404
The document that has been requested either no longer exists, or has never existed on the server.

http error code :503
Its Server Error Code.The server is overloaded or down for maintenance and due to this was unable to process the client request.

http error code :502
Server Overload.Bad Gateway; a server being used by this Web server has sent an invalid response.

http error code :200
This is the normal response where a page has been successfully fetched

Monday, June 22, 2009

How to retrieve the tooltip text of images?

We can retireve this using HTML Source file from View -> Source menu.After that for every image the alt tag attribute represents the value of tooltip text(of class tooltips_class32.).

alternatively using HTML DOM :
msgbox Browser("Google").Page("Google").WebEdit("q").Object.title

Sunday, June 21, 2009

procedures in pl/sql in Oracle

1.procedure can use the return statement to return the control back to calling subprogram.
2.function can return a values as well it can be used anywhere in a SQL statement.

create or replace procedure proc_highpayee
varEno NUMBER default 0;
select eno into varEno from emp where sal = (select max(sal)from emp) and rownum =1;
DBMS_OUTPUT.PUT_LINE ('No Data found for SELECT ');

alter (DDL) commands in SQL?

DDL : Create,Drop,Truncate,Alter
DML: Insert,Update, Delete
DCL : Grant,Revoke,Commit,Rollback;
-- retrieving the duplicate name records only
select ename from emp e1 where 1 < (select count(*) FROM emp e2 WHERE e2.ename = e1.ename) --alter:to add ,modify and drop a column alter table add/modify
alter table drop column
select round(11.567, 0) from dual; --12
select round(11.567, 1) from dual; --11.6
select round(11.567, 2) from dual; --11.57
select round(11.567, 3) from dual; --11.567

Subprograms in PL/SQL?

select sal from emp where eno = func_highpayee;

--function declaration
create or replace function func_highpayee
return number
varEno NUMBER default 0;
select eno into varEno from emp where sal = (select max(sal)from emp) and rownum =1;
DBMS_OUTPUT.PUT_LINE ('No Data found for SELECT on ' );

executing a proc or func:

exec proc-name;

Saturday, June 20, 2009

Set an Object Repositories List as Default for All New Actions in QTP?

'This example opens a test, configures an action's object repositories collection
'and saves the test.
'There is no unsaved test currently open in QuickTest.
'For more information, see the example for the Test.SaveAs method.
Dim qtApp 'As QuickTest.Application ' Declare the Application object variable
Dim qtRepositories 'As QuickTest.ObjectRepositories ' Declare an action's object repositories collection variable
Dim lngPosition
' Open QuickTest
Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
qtApp.Launch ' Launch QuickTest
qtApp.Visible = True ' Set QuickTest to be visible
' Open a test and get the "Login" action's object repositories collection
qtApp.Open "C:\Tests\Test1", False, False ' Open a test
Set qtRepositories = qtApp.Test.Actions("Login").ObjectRepositories ' Get the object repositories collection object of the "Login" action
' Add MainApp.tsr if it's not already in the collection
If qtRepositories.Find("C:\MainApp.tsr") = -1 Then ' If the repository cannot be found in the collection
qtRepositories.Add "C:\MainApp.tsr", 1 ' Add the repository to the collection
End If
' If InnerWnd.tsr is moved down the list - place it back at position 1
If qtRepositories.Count > 1 And qtRepositories.Item(2) = "C:\InnerWnd.tsr" Then ' If there's more than one object repository and InnerWnd.tsr is in position 2
qtRepositories.MoveToPos 1, 2 ' Switch between the first two object repositories
End If
' If Debug.tsr is in the collection - remove it
lngPosition = qtRepositories.Find("C:\Debug.tsr") ' Try finding the Debug.tsr object repository
If lngPosition <> -1 Then ' If the object repository was found in the collection
qtRepositories.Remove lngPosition ' Remove it
End If
' Set the new object repository configuration as the default for all new actions
qtRepositories.SetAsDefault ' Set object repositories associated with the "Login" action as the default for all new actions
'Save the test and close QuickTest
qtApp.Test.Save ' Save the test
qtApp.Quit ' Quit QuickTest
Set qtRepositories = Nothing ' Release the action's shared repositories collection
Set qtApp = Nothing ' Release the Application object

Friday, June 19, 2009

Displaying a Sentence(each character) in Reverse Order using QTP VB Scripting

var1 = "Hi how are you?"
msgbox strreverse(var1)

Test and Run-time Object in QTP?

What is the difference between Test Objects and Run Time Objects ?
Test objects are basic and generic objects that QTP recognize. Run time object means the actual object to which a test object maps.

Can i change properties of a test object?
Yes. You can use SetTOProperty to change the test object properties. It is recommended that you switch off the Smart Identification for the object on which you use SetTOProperty function.

Can i change properties of a run time object?
No (but Yes also). You can use GetROProperty(”outerText”) to get the outerText of a object but there is no function like SetROProperty to change this property.
But you can use WebElement().object.outerText=”Something” to change the property.

Write test cases for Login page and Calculator?

First divide the scenarios for types of testing then again derive the sub scenarios for

1.Look and feel
Authorization testing
Authentication testing
sql injection
cross scripting

How to copy the contents of one table to another table in Oracle?

CREATE TABLE newTable AS SELECT * FROM emp WHERE sal > 2000;

insert into newTable SELECT * FROM emp WHERE sal > 2000 ; "to copy the contents"

insert into newTable SELECT * FROM emp WHERE 1> 2 ; "to copy the structure"

with the above statement the contents from the table emp will be copied to temp with the same structure as emp table.

Monday, June 15, 2009

How manys we can write vbscript statements in QTP?

2.Manual writing.
3.Step Generator.
4.Descriptive Programming.

Thursday, June 4, 2009

Working with text filesin QTP ?

Creating Files
There are three ways to create an empty text file (sometimes referred to as a "text stream").

1.The first way is to use the CreateTextFile method. The following example demonstrates how to create a text file using the CreateTextFileMethod method.
Dim fso, f1
Set fso = CreateObject("Scripting.FileSystemObject")
Set f1 = fso.CreateTextFile("c:\testfile.txt", True)

2.The second way to create a text file is to use the OpenTextFile method of the FileSystemObject object with the ForWriting flag set.
Dim fso, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting. FileSystemObject")
Set ts = fso.OpenTextFile("c:\test.txt", ForWriting, True)

3.A third way to create a text file is to use the OpenAsTextStream method with the ForWriting flag set.
Dim fso, f1, ts
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile ("c:\test1.txt")
Set f1 = fso.GetFile("c:\test1.txt")
Set ts = f1.OpenAsTextStream(ForWriting, True)

Adding Data to the File
Once the text file is created, add data to the file using the following three steps:
Open the text file.
Write the data.
Close the file.
To open an existing file, use either the OpenTextFile method of the FileSystemObject object or the OpenAsTextStream method of the File object.
To write data to the open text file, use the Write, WriteLine, or WriteBlankLines methods of the TextStream object, according to the tasks outlined in the following table.
Write data to an open text file without a trailing newline character.
Write data to an open text file with a trailing newline character.
Write one or more blank lines to an open text file.
To close an open file, use the Close method of the TextStream object.
Note The newline character contains a character or characters (depending on the operating system) to advance the cursor to the beginning of the next line (carriage return/line feed). Be aware that the end of some strings may already have such nonprinting characters.
The following example demonstrates how to open a file, use all three write methods to add data to the file, and then close the file:[VBScript]
Sub CreateFile()
Dim fso, tf
Set fso = CreateObject("Scripting.FileSystemObject")
Set tf = fso.CreateTextFile("c:\testfile.txt", True)
' Write a line with a newline character.
tf.WriteLine("Testing 1, 2, 3.")
' Write three newline characters to the file.
' Write a line.
tf.Write ("This is a test.")
End Sub


' Read the contents of the file. Response.Write "Reading file
Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)

s = ts.ReadLine

Response.Write "File contents = '" & s & "'"


Moving, Copying, and Deleting Files
The FSO object model has two methods each for moving, copying, and deleting files, as described in the following table.
Move a file
File.Move or FileSystemObject.MoveFile
Copy a file
File.Copy or FileSystemObject.CopyFile
Delete a file
File.Delete or FileSystemObject.DeleteFile
The following example creates a text file in the root directory of drive C, writes some information to it, moves it to a directory called \tmp, makes a copy of it in a directory called \temp, then deletes the copies from both directories.
To run the following example, create directories named \tmp and \temp in the root directory of drive C:

' Get a handle to the file in root of C:\.

Set f2 = fso.GetFile("c:\testfile.txt")

' Move the file to \tmp directory. f2.Move ("c:\tmp\testfile.txt

' Copy the file to \temp.

f2.Copy ("c:\temp\testfile.txt")

' Get handles to files' current location.

Set f2 = fso.GetFile("c:\tmp\testfile.txt")

Set f3 = fso.GetFile("c:\temp\testfile.txt")

' Delete the files.



Set ts = fso.OpenTextFile("c:\testfile.txt", ForReading)

While not ts.atEndOfLine

s = ts.ReadLine

msgbox s


Working with excel files in QTP using "Excel.Application" class?

Set xlApp = CreateObject("Excel.Application")
Set xlWorkBook = xlApp.workbooks.add 'or Set xlbook=xlapp.activeworkbook
Set xlWorkSheet = xlWorkbook.worksheet.add 'or Set worksheet=xlbook.sheets(3)
xlWorkSheet.Range("A1:B10").interior.colorindex = 34 'Change the color of the cells
xlWorkSheet.Range("A1:A10").value = "text" 'Will set values of all 10 rows to "text"
xlWorkSheet.Cells(1,1).value = "Text" 'Will set the value of first row and first col
rowsCount = xlWorkSheet.Evaluate("COUNTA(A:A)") 'Will count the # of rows which have non blank value in the column A
colsCount = xlWorkSheet.Evaluate("COUNTA(1:1)") 'Will count the # of non blank columns in 1st row
xlWorkbook.SaveAs "C:\Test.xls"
Set xlWorkSheet = Nothing
Set xlWorkBook = Nothing
Set xlApp = Nothing

Getting Child Objects in QTP?

Returns the collection of child objects contained within the object.

We can use description object to get all the objects on the page that matches that specific description. Suppose we have to check all the checkboxes present on a web page. So we will first create an object description for a checkboxe and then get all the checkboxes from the page

Dim obj_ChkDesc
Set obj_ChkDesc=Description.Create
obj_ChkDesc(“html tag”).value = “INPUT”
obj_ChkDesc(“type”).value = “checkbox”
Dim allCheckboxes, singleCheckBox
Set allCheckboxes = Browse(“Browser”).Page(“Page”).ChildObjects(obj_ChkDesc)

For each singleCheckBox in allCheckboxes
singleCheckBox.Set “ON”

Sub ChildObjects_Example()'The following example uses the ChildObjects method to find all the'list objects on a Web page, and then to select an item in each list.

Set oDesc = Description.Create()

oDesc("micclass").Value = "WebList"

Set Lists = Browser("Mercury Interactive").Page("Mercury Interactive").ChildObjects(oDesc)NumberOfLists = Lists.Count()

For i = 0 To NumberOfLists - 1

Lists(i).Select i + 1


End Sub

all the values are interpreted as regular expressions. To turn it off, use

oDesc(“Property1”).RegularExpression = False

type = checkbox
type = radio
class = weblist
class= webedit
class = image

in description object for list,textbox,image we can use micclass in description object

Hierarchy of test description ?

When using programmatic descriptions from a specific point within a test object hierarchy, you must continue to use programmatic descriptions from that point onward within the same statement.

If you specify a test object by its object repository name after other objects in the hierarchy have been described using programmatic descriptions, QuickTest cannot identify the object.

For example, you can use Browser(Desc1).Page(Desc1).Link(desc3), since it uses programmatic descriptions throughout the entire test object hierarchy.

You can also use Browser("Index").Page(Desc1).Link(desc3), since it uses programmatic descriptions from a certain point in the description (starting
from the Page object description).

However, you cannot use Browser(Desc1).Page(Desc1).Link("Example1"), since it uses programmatic descriptions for the Browser and Page objects but
then attempts to use an object repository name for the Link test object (QuickTest tries to locate the Link object based on its name, but cannot
locate it in the repository because the parent objects were specified using programmatic descriptions).

you can only start from OR, and move to DP So this will not work:

How to use Description Object?

Used to create a Properties collection object.
Creates a new, empty description object in which you can add collection of properties and values in order to specify the description object in place of a test object name in a step.

For example, the statements below instruct QuickTest to enter the text: MyName in the first WebEdit object in the Mercury Tours page with the name UserName

Set EditDesc = Description.Create()
EditDesc("Name").Value = "userName"
EditDesc("Index").Value = "0"
Browser("Welcome: Mercury").Page("Welcome: Mercury").WebEdit(EditDesc).Set "MyName"
When working with Properties objects, you can use variable names for the properties or values to generate the object description based on properties or values you retrieve during a run session. You can also create several Properties objects in your test if you want to use programmatic descriptions for several objects.

'Returns the number of Property objects in the Properties collection
PropCount = MyDesc.Count

Dim obj_Desc
Set obj_Desc = Description.Create
obj_Desc("name").value = "q"
obj_Desc("class name").value = "web edit"
browser("Google").Page("Google").WebEdit(obj_Desc).Set "hi"

Working with Dictionary Objects

A Dictionary object is the equivalent of a PERL associative array. Items can be any form of data, and are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.

Dim d ' Create a variable.
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens" '
Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
msgbox d("a") ' retrieves the Athens
a = d.Keys ' Get the keys
b = d.Items ' Get the items.
For i = 0 To d.Count -1 ' Iterate the array.
s = s & a(i) & space(1) & b(i) & vbnewline ' Create return string.
msgbox s

How do we ensure we can close the correct browser?

Environment("env_BrowserHandle") = Browser("Browser).GetROProperty("hwnd")'Then

Browser("hwnd:=" & Environment("env_BrowserHandle")).Close

Select a Radio Button Option

'The following example uses the Select method to check if a radio group
'has the value of "Two", and, if not, selects the "Two" radio button.
Sub Select_Example2()

CurrentValue = Browser("All types of radio buttons").Page("All types of radio buttons").WebRadioGroup("MYRADIO").GetTOProperty("value")
If CurrentValue <> "Two" Then
Browser("All types of radio buttons").Page("All types of radio buttons").WebRadioGroup("MYRADIO").Select "Two"
End If
end sub

'The following example uses the Select method to select the Window
'item in a Web radio group in the seating preference section of
'the Mercury Tours application.
Sub Select_Example1()
Browser("Mercury Tours").Page("Find Flights").WebRadioGroup("seat pref").Select "Window"
End Sub

'selectin radion buttons from google home page
Browser(" - More_2").Page("Google").WebRadioGroup("meta").Select "#0" 'selecting "the web"
Browser(" - More_2").Page("Google").WebRadioGroup("meta").Select "cr=countryIN" ' selecting "pages from india"

'some of the inportant properties
items count
selected item index
all items
type :radio

Checking the status of a checkbox

Browser(" - More_2").Page(" - More").WebCheckBox("ctp").Set "ON"

var_ChkStatus=Browser(" - More_2").Page(" - More").WebCheckBox("ctp").GetROProperty("checked")

msgbox var_ChkStatus '1

Browser(" - More_2").Page(" - More").WebCheckBox("ctp").Set "ON"

var_ChkStatus=Browser(" - More_2").Page(" - More").WebCheckBox("ctp").GetROProperty("checked")

msgbox var_ChkStatus '0

'checking for a particular item in the list box

'checking for a particular item in the list box and select it
var_SearchItem = "Hyderabad"
var_ItemsCount = Browser(" - More").Page(" - More").WebList("loc").GetROProperty("items count")
For i =1 to var_ItemsCount
var_Item = Browser(" - More").Page(" - More").WebList("loc").GetItem(i)
If ucase(var_SearchItem) = ucase(var_Item) Then
msgbox "found"
Exit for
End If

While selecting an item from a list box the index starts from 0
and while getting an item from a list box the index starts from 1

Browser(" - More").Page(" - More").WebList("loc").Select i-1

'some of the important properties of the list object
items count
selected item index
all items
selected items count
value : selected item value

How to chek whether an object exists or not?

var_Exist = Dialog("Login").WinEdit("Agent Name:").Exist
msgbox var_Exist 'Return true if object exists otherwise false

Adding a Parameter to RunTime DataTable in QTP

The following example uses the GetSheet method to return the "MySheet" sheet of the run-time Data Table in order to add a parameter to it.
MyParam=DataTable.GetSheet ("MySheet").AddParameter("Time", "8:00")
You can also use this to add a parameter to the "MySheet" local sheet (note that no value is returned).
DataTable.GetSheet ("MySheet").AddParameter "Time", "8:00"
myparam = DataTable. LocalSheet.AddParameter("Time", "5.45")
MsgBox myparam 'output is 5.45

Displaying a Sentence( of words) in Reverse Order using QTP VB Scripting

str="I'm QuickTestProfessionall.Do you know me?"

arrStrings = Split(str,space(1))

msgbox ubound(arrStrings)


For each arrStr in arrStrings

vstrReverse = strReverse(arrStr) & space(1) & vstrReverse

msgbox arrStr'each string separated by a single space


msgbox vstrReverse


Public Function ReverseString(ByVal InputString As String) _
As String

Dim lLen As Long, lCtr As Long
Dim sChar As String
Dim sAns As String

lLen = Len(InputString)
For lCtr = lLen To 1 Step -1
sChar = Mid(InputString, lCtr, 1)
sAns = sAns & sChar

ReverseString = sAns

End Function

Can we spy on a Virtual Object?

we can't get the properties....? More info yet to get.....?

Disable recognition of vrtual objects while recording?

"Disable recognition of vrtual objects while recording" option can be set from::
Tools-> Options -> General

How do we set Video Record session from QTP?

Tools -> Options -> Run

How do we know current iteration value from Environment variable?

msgbox Environment.Value("ActionIteration")
msgbox Environment.Value("TestIteration")
Indicates which action iteration is currently running.

Conditional loops int QTP?

Do...Loop Statement
Repeats a block of statements while a condition is True or until a condition becomes True.
Do [{While Until} condition]
[Exit Do]
Or, you can use this syntax:
[Exit Do]
Loop [{While Until} condition]
Loop While False
Loop Until True
While...Wend Statement
Executes a series of statements as long as a given condition is True.
While condition
Version [statements]
For...Next Statement
Repeats a group of statements a specified number of times.
For counter = start To end [Step step]
[Exit For]
For Each...Next Statement
Repeats a group of statements for each element in an array or collection.
For Each element In group
[Exit For]
Next [element]

What are the step commands available in QTP?

Step Into
Step Over
Step out
Run to step
Debug from step

Wednesday, June 3, 2009

What is a virtual object?

Virtual object enable you to record and run test on objects that are not normally recognized by QTP. We can teach QTP to recognize any area of your application as an object by defining it as a virtual object. Sometimes QTP may not recognizes some objects, in this kind of situations we use virtual object .It uses the coordinates of the object to map it to Microsoft Standard Objects.

Tuesday, June 2, 2009

When does the descriptive programming preferred?

1.When we start the automation even before the application comes for automation and only some document related to the application available.
2.when object repository size exceeds its maximum size .
3.when there are dynamic objects in the application.
4.execution is faster with descriptive programming .
5.when object repository is read only and we can't add any more objects..

We can write the desc pgmg script on a particular object without adding it to the object repository file by giving the physical description of the object directly in place of the logical name.

Associating a library file to test at RunTime manually in QTP?

If we associate a library file(classes,functions and procedures) at Run time then scope of the variables or objects of that library file will not be available to all the actions except to the only action where execute file statement is executed..

If we want the scope to be across all the actions then we have two ways of doing it:

1.attach that library file manually from File->Settings -> Resources.
2.use the below code which you need to run before qtp tool is open
Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
qtApp.Launch ' Launch QuickTest
qtApp.Visible = True ' Set QuickTest to be visible
' Open a test and get its libraries collection
Set qtLibraries = qtApp.Test.Settings.Resources.Libraries ' Get the libraries collection object
' Add Utilities.vbs if it's not in the collection
If qtLibraries.Find("C:\lib1.vbs") = -1 Then ' If the library cannot be found in the collection
msgbox "not assosiated"
qtLibraries.Add "C:\lib1.vbs", 1 ' Add the library to the collection
End If
Set qtLibraries = Nothing ' Release the test's libraries collection
Set qtApp = Nothing ' Release the Application object
RunAction "Action2", oneIteration

When do we use function or action?

function can be used when have code which you want to reuse across all the projects.
2.when there is no dependency on Object Repository.

other than the above scenarios we go for actions..
1.Actions are project dependent

Validating the Checkpoint result without depending on TestResults Window

v_ChkPntStatus = Browser(…).Page(…).WebEdit(…).Check (Checkpoint(”CheckPointName1″))
Return Value is True if the checkpoint is passed otherwise its false.
if v_ChkPntStatus then
MsgBox “Check Point passed.”
MsgBox “Check Point failed.”
end if

ActiveX Data Objects

Microsoft's ActiveX Data Objects (ADO) is a set of Component Object Model (COM) objects for accessing data sources. It provides a layer between programming languages and OLE DB (a means of accessing data stores, whether they be databases or otherwise, in a uniform manner). ADO allows a developer to write programs that access data without knowing how the database is implemented. You must be aware of your database for connection only. No knowledge of SQL is required to access a database when using ADO, although one can use ADO to execute arbitrary SQL commands. The disadvantage of this (i.e. using SQL directly) is that it introduces a dependency upon the type of database used.

It is positioned as a successor to Microsoft's earlier object layers for accessing data sources, including RDO (Remote Data Objects) and DAO (Data Access Objects). ADO was introduced by Microsoft in October 1996.

ADO is made up of four collections and twelve objects:

ADO collections

This collection contains a set of Field objects. The Collection can be used in either a Recordset object or in a Record object. In a Recordset object, each of the Field objects that make up the Fields collection corresponds to a column in that Recordset object. In a Record object, a Field can be an absolute or relative URL that points into a tree-structured namespace (used for semi-structured data providers like the Microsoft OLE DB Provider for Internet Publishing) or as a reference to the default Stream object associated with that Record object.
An object can have more than one Property object, which are contained in the object's Properties collection.
A Command object can have several Parameter commands to change its predefined behaviour, and each of the Parameter objects are contained in the Command object's Parameters collection
All provider created errors are passed to a collection of Error objects, while the Errors collection itself is contained in a Connection object. When an ADO operation creates an error, the collection is cleared and a new group of Error objects are created in the collection.

ADO objects

The connection object is ADO's connection to a data store via OLE DB. The connection object stores information about the session and provides methods of connecting to the data store. As some data stores have different methods of establishing a connection, some methods may not be supported in the connection object for particular OLE DB providers. A connection object connects to the data store using its 'Open' method with a connection string which specifies the connection as a list of key value pairs (for example: "Provider='SQLOLEDB';Data Source='TheSqlServer'; Initial Catalog='Northwind';Integrated Security='SSPI';"). The start of which must identify the type of data store connection that the connection object requires. This must be one of:
  • an OLE DB provider (for example SQLOLEDB), using the syntax "provider=";
  • a file name, using the syntax "file name=";
  • a remote provider and server (see RDS), using the syntax "Remote provider=" and "Remote server="; or
  • an absolute URL, using the syntax "URL="
After the connection object establishes a session to the data source, instructions are sent to the data provider via the command object. The command object can send SQL queries directly to the provider through the use of the CommandText property, send a parameterised query or stored procedure through the use of a Parameter object or Parameters collection or run a query and return the results to a dataset object via the Execute method. There are several other methods that can be used in the Command object relating to other objects, such as the Stream, RecordSet or Connection objects.
A recordset is a group of records, and can either come from a base table or as the result of a query to the table. The RecordSet object contains a Fields collection and a Properties collection. The Fields collection is a set of Field objects, which are the corresponding columns in the table. The Properties collection is a set of Property objects, which defines a particular functionality of an OLE DB provider. The RecordSet has numerous methods and properties for examining the data that exists within it. Records can be updated in the recordset by changing the values in the record and then calling on the Update or UpdateBatch method. Adding new records is performed through the AddNew function and then by calling on the Update or UpdateBatch method. Records are also deleted in the recordset with the Delete method and then by calling on the Update method. However, if for some reason the deletion cannot occur, such as because of violations in referential integrity, then the recordset will remain in edit mode after the call to the Update method. The programmer must explicitly call on the CancelUpdate function to cancel the update. Additionally, ADO can rollback transactions (if this is supported) and cancel batch updates. Recordsets can also be updated in one of three ways: via an immediate update, via a batch update, or through the use of transactions:
The recordset is locked using the adLockOptimistic or adLockPessimistic lock. The data are updated at the data source after the record is changed and the Update method is called.
The recordset is locked using adLockBatchOptimistic and each time Update is called the data are updated in a temporary buffer. Finally, when UpdateBatch is called the data are completely updated back at the data source. This has the advantage of it all being done in memory, and if a problem occurs then UpdateCancel is called and the updates are not sent to the data source
If the OLE DB provider allows it, transactions can be used. To start the transaction, the programmer invokes the BeginTrans method and does the required updates. When they are all done, the programmer invokes the CommitTrans method. RollbackTrans can be invoked to cancel any changes made inside the transaction and rollback the database to the state before the transaction began
This object represents one record in the database, and contains a fields collection. A RecordSet consists of a collection of Record objects.
A stream, mainly used in a RecordSet object, is a means of reading and writing a stream of bytes. It is mostly used to save a recordset in an XML format, to send commands to an OLE DB provider as an alternative to the CommandText object and to contain the contents of a binary or text file.
A parameter is a means of altering the behaviour of a common piece of functionality, for instance a stored procedure might have different parameters passed to it depending on what needs to be done; these are called parameterised commands.
Each Record object contains many fields, and a RecordSet object has a corresponding Field object also. The RecordSet object's Field object corresponds to a column in the database table that it references.
This object is specific to the OLE DB provider and defines an ability that the provider has implemented. A property object can be either a built-in property — it is a well defined property implemented by ADO already and thus cannot be altered — or can be a dynamic property — defined by the underlying data provider and can be changed
When an OLE DB provider error occurs during the use of ADO, an Error object will be created in the Errors collection. Other errors do not go into an Error object, however. For instance, any errors that occur when manipulating data in a RecordSet or Field object are stored in a Status property.

Friday, May 29, 2009

Connection string in QTP?

connection string is a string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider in order to initiate the connection.

Connections are built by supplying an underlying driver or provider with a connection string, which is a way of addressing a specific database or server and instance as well as user authentication credentials (for example, Server=sql_box;Database=Common;User ID=uid;Pwd=password;). Once a connection has been built it can be opened and closed at will, and properties (such as the command time-out length, or transaction, if one exists) can be set. The Connection String is composed of a set of key/value pairs as dictated by the data access interface and data provider being used.

Client Side and Server Side Applications

Client side scripting languages are Javascript, VbScript, PHP…etc
Client side scripting languages are useful to validate the inputs or user actions from user side or client side.
Client side scripting is good because it won’t send the unwanted input’s to server for validation. From front-end it self it validate the user inputs and restricts the user activities and guides him

Server side Scripting languages are
Perl, JSP, ASP, PHP.etc
Server side Scripting languages are to validate the inputs at server side.

These scripting languages provide security for the application. And also provides dynamic nature to web or client server application

Thursday, May 28, 2009

Whats the difference between HTTP and HTTPS?

http is hyper text transfer protocol which is responsible for transmitting and receiving information across the Internet where as https is secure http, which is used exchanging confidential information with a server, which needs to be secured in order to prevent unauthorized access.

HTTP is Hyper Text Transport Protocol and is transmitted over the wire via PORT 80(TCP). You normally use HTTP when you are browsing the web, it's not secure, and so someone can eavesdrop on the conversation between your computer and the web server. HTTP can support the client asking for a particular file to be sent only if it has been updated after a certain date and time. This would be used if the client has already retrieved a copy of a file by that name from that server, but wants to check to see if it has been updated since then. The server responds either with the updated file, with a message to say the file has not been changed, or with a message that the file no longer exists.

HTTPS (Hypertext Transfer Protocol over Secure Socket Layer or HTTP over SSL) is a Web protocol developed by Netscape and built into its browser that encrypts and decrypts user page requests as well as the pages that are returned by the Web server. HTTPS is really just the use of Netscape's Secure Socket Layer (SSL) as a sub layer under its regular HTTP application layering. (HTTPS uses port 443 instead of HTTP port 80 in its interactions with the lower layer, TCP/IP.) SSL uses a 40-bit key size for the RC4 stream encryption algorithm, new-age browsers use 128-bit key size which is more secure than the former, it is considered an adequate degree of encryption for commercial exchange. HTTPS is normally used in login pages, shopping/commercial sites.

How it Work
Https is not a separate protocol, but refers to the combination of a normal HTTP interaction over an encrypted Secure Sockets Layer (SSL) or Transport Layer Security (TLS) transport mechanism. This ensures reasonable protection from eavesdroppers and (provided it is implemented properly and the top level certification authorities do their job properly) man-in-the-middle attacks.

The default TCP port of an https: URL is 443 (for unsecured HTTP, the default is 80). To prepare a web-server for accepting https connections the administrator must create a public key certificate for the web-server. These certificates can be created for Linux based servers with tools such as Open SSL's ssl or SuSE's gensslcert. This certificate must be signed by a certificate authority of one form or another, who certifies that the certificate holder is who they say they are. Web browsers are generally distributed with the signing certificates of major certificate authorities, so that they can verify certificates signed by them.

When does Test Automation Makes Sense

1.When there is a repetitive task
2.When you want to do load test an application
3.API based testing
4.Human errors will be minimized
6.Number of resources will be reduced
7.Consistency in test results

Tuesday, May 26, 2009

Connect to Oracle DataBase using QTP

'Reference: Microsoft ActiveX Data Objects 2.7 library

'Dim cnn As ADODB.Connection
Set cnn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.RecordSet")

' Open a connection by referencing the ODBC driver in sql server
' cnn.ConnectionString = "driver={SQL Server};&server=MySqlServer;uid=MyUserName;pwd=MyPassword;database=pubs"

' Open a Connection using an ODBC for oracle
cnn.ConnectionString = "DRIVER={Microsoft ODBC for Oracle};DSN=real;UID=gopi;PWD=orcl;"
cnn.ConnectionTimeout = 30

' Find out if the attempt to connect worked.
If cnn.State = adStateOpen Then ' or cnn.State=1
MsgBox "connected to database"
MsgBox "connectin failed.."
End If

'execute sql query
rs.Open "SELECT * FROM promotion.t_p_promo_master WHERE f_promo_id = 60082", cnn

' Create a Recordset by executing an SQL statement.
' Set rs = cnn.Execute("Select * From authors")
'Remember that the returned Recordset object from connection.execute is always a read-only,
'forward-only cursor. If you need a Recordset object with more functionality, you should
'first create a Recordset object with the desired property settings and then use the
'Recordset object's Open method to execute the query and return the desired cursor type.

' Send a Delete statement to the database.
'cnn.Execute ("Delete From authors Where au_id = '011-01-0111'")

' Find out how many rows were affected by the Delete.
'Set rs = cnn.Execute("Select @@rowcount")
' Display the first field in the recordset.
'MsgBox rs(0) & " rows deleted"
'in above the command passed to the data source is a Delete statement. Because no rows are returned, you do not need to explicitly use a Recordset object. How many rows were deleted? You can use the recordsAffected parameter to find out.

'Running stored prcedure
' Create a recordset by running a stored procedure.
' Set rs = cnn.Execute("Exec byroyalty 50")

Do While Not rs.EOF
'copy each field
'Worksheets("Sheet1").Range("A3").End(xlDown).Offset(1, 0) = rs.Fields(0)

'display each field in the record set
For Each Field In rs.Fields
MsgBox Field


' Close the connection.

TestCases on Physical Objects like Pen,Book or Chair etc

Test cases on different objects generally asking are ::Pen, Book,Chair .
In general when we are writing a test case for objects like above, we should consider the objects parameters like
• Look and feel
• Performance
• Usability
• Rigidity
Look and feel means external appearance like outer case must be attractive. Look and feel parameters are, Color, Height, Width, Design Material used for making it, .etc
If you come for performance the important parameters are, Durability, Continuous perfromence...Etc.
Usability: How easy to use that thin Accessibility
Rigidity How strong it is How it is working in abnormal conditions For example if you want to write test cases for a pen Then first start with look and feel.
If you com for software enabled objects Notepad, Yahoo login, For above objects we should check Different menu options are working properly Functionality of buttons, Memory capacities, Look and feel, Speed of operation…etc

Friday, May 22, 2009

Retrieve the nth highest salary from emp table?

SELECT * FROM emp e1 WHERE &N = (SELECT COUNT(DISTINCT (e2.salary)) FROM emp e2 WHERE e2.salary >= e1.salary)


select max(sal) FROM emp where not in(select top n sal from emp)order by sal desc;
N -> Nth highest salary of the month

Reterieving the Top2 salaries from the employee table:
Select * from EMP e where 2>= (select count (*) from EMP e where sal>e.sal) order by desc sal

Thursday, May 21, 2009

Dynamic arrays in QTP?

You can use the Dim statement to declare an array with empty parentheses to declare a dynamic array. You use the Preserve keyword to preserve the data in an existing array when you change the size of the last dimension

Dim a() ' Allocates nothing.we can't declare array as a(2) and resize it to a(4)
ReDim preserve a(0)
a(0) = 0
ReDim preserve a(1)
a(1) = 1
ReDim preserve a(2)
a(2) = 2
ReDim preserve a(3)
a(3) = 3
ReDim preserve a(4) ' to preserve the contents of the array as the resizing takes place.
a(4)= 4
For each ite in a
msgbox ite ' o/p : 0 1 2 3 4

Arrays in QTP

Dim a(3) ' Allocates the fixed storage space. can't be changed dynamically when array size fixed.
a(0) = 0
a(1) = 1
a(2) = 2
a(3) = 3
'a(4)= 4 'subscript out of range error
For each ite in a
msgbox ite ' o/p : 0 1 2 3
Erase a ' Each element is reinitialized and Free memory used by array.

Retrieve the nth highest salrary from an employee table?

Which environments does QTP support?

Windows,Web,Visual Basic : Default Add-ins
NET, Java/J2EE, SAP, Siebel, Oracle, PeopleSoft, , ActiveX, Terminal emulators and Web services.

What is meant by Priority and severity?

Priority means “Importance of the defect w.r.t customer requirement”.And also it indicates how fast theDeveloper should act on it.

Severity means “Seriousness of the defect w.r.t functionality”.How it affects the Testing.

1 - Urgent
2 - High
3 - Medium
4 - Low

Returned for closure

What are the file extensions available in QTP?

.vbs or .qfl :::: for function libraries
.xml or .ini :::: for Environment Variables
.mtr and .tsr :::: for PerAction and Shared Repositories
.mts ::: Script Extensions
.mst ::: ActionTemplate (in dat folder .provides the Header for comments)

How many ways we can parameterize data in QTP?

Test or Action Parameters
Environment Variables
Random Numbers
DataTable Parameters

What is the Diff between Image check-point and Bit map Check point

Image checkpoints enable you to check the properties of a Web image.We dont have Image checkpoint directly available.Navigation is : StandardCheckpoint -> click on image -> edit the check point properties like index, ALT Tag, URL of the image.

You can check an area of a Web page or application as a bitmap using Bitmap Checkpoint....checkpoint-> Bitmap Checkpoint

Bitmap check points checks the image Comparing bit by bit and also you can check the whole image or part of the image.

Main components of Quality Center Tool

Quality Center is a Test Management tool from hp(previously Mercury) which can be opened or accessed using Internet Explorer Web Browser only.It has 4 important components from the all of its components which Tester will have to work with.In this Tool we can write the test cases(in Test Plan tab) and execute the test cases(in Test Lab) and report the mismatches(in Defects tab).
2.Test Plan
3.Test Lab

Difference Between KeywordView and Expert View

The changes that we make in Keyword view will be reflected to Expert View and vice-versa is also very much possible.....

KeywordView will be useful for those who doesn't have the knowledge of VB Scripting and want to generate the VB statements.

Wednesday, May 13, 2009

Difference Between InvokeApplication and SystemUtil.Run

SystemUtil.Run can open the Desktop applications or System Applications without need to specify the full path for system applications.Other thatn this It can open any application provided the full path of the application. It can open non-executable file and executable files.
This will be generated with Recording option while the application is selected from Start Menu।
object.Run file, [params], [dir], [op], [mode]
SystemUtil.Run "iexplore.exe","" ,,,,
We can also close the process by using CloseProcessByName method.

The InvokeApplication statement is supported primarily for backward compatibility. .It can open executable files only.
invokeapplication "C:\Program Files\Internet Explorer\iexplore.exe"
invokeapplication "\Program Files\Internet Explorer\iexplore.exe","C:"

3...alternatively we can also use the following..
Set objshell = createobject("") "notepad.exe"

Tuesday, May 12, 2009

Difference between Client/Server and Web Testing

The following list of testings are performed specifically on Client/Server Applications.

1.Installation Testing.
You will need to aware of clients and servers and their locations in the test scenario.
They may be New Installation,Upgrade.
2.Testing related to LAN, Centralized hardware and software.

The following list of testings are performed specifically on Web Applications.

1.Compatibility Testing(Browser and OS)
2.Load Testing

More to ::
Web systems are one type of client/server. The client is the browser, the server is whatever is on the back end (database, proxy, mirror, etc). This differs from so-called “traditional” client/server in a few ways but both systems are a type of client/server. There is a certain client that connects via some protocol with a server (or set of servers).

Also understand that in a strict difference based on how the question is worded, “testing a Web server” specifically is simply testing the functionality and performance of the Web server itself. (For example, I might test if HTTP Keep-Alives are enabled and if that works. Or I might test if the logging feature is working. Or I might test certain filters, like ISAPI. Or I might test some general characteristics such as the load the server can take.) In the case of “client server testing”, as you have worded it, you might be doing the same general things to some other type of server, such as a database server. Also note that you can be testing the server directly, in some cases, and other times you can be testing it via the interaction of a client.

You can also test connectivity in both. (Anytime you have a client and a server there has to be connectivity between them or the system would be less than useful so far as I can see.) In the Web you are looking at HTTP protocols and perhaps FTP depending upon your site and if your server is configured for FTP connections as well as general TCP/IP concerns. In a “traditional” client/server you may be looking at sockets, Telnet, NNTP, etc.