Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Articles On Testing

Wecome to http://www.articlesontesting.com !!!

Showing posts with label QTP. Show all posts
Showing posts with label QTP. Show all posts

Accessibility Checkpoint In QTP

What is accessibility checkpoint in QTP :

Checkpoints is one of the most important of the many features QTP has in it.  Among the many well known checkpoints we have one lesser known and less frequently used checkpoint called Accessibility checkpoint. It is one of the most sought after query in any Automation testing interview rounds during QTP technical questions. In very broad sense we can conclude that accessibility checkpoint is nothing but a 508 standard compliance of any website in terms of its standardization usage of various tags. However let us explore in details as to what this 508 compliance refers to.

HTML 508 Compliance :
(a)    A text equivalent for every non-text element shall be provided (e.g., via "alt", "longdesc", or in element content).
(b)   Equivalent alternatives for any multimedia presentation shall be synchronized with the presentation.
      (c)     Web pages shall be designed so that all information conveyed with color is also available without color, for example from context or markup.
      d)    Documents shall be organized so they are readable without requiring an associated style sheet.
      e)    Redundant text links shall be provided for each active region of a server-side image map.
      f)     Client-side image maps shall be provided instead of server-side image maps except where the regions cannot be defined with an available geometric shape.
      g) Row and column headers shall be identified for data tables.
      h) Markup shall be used to associate data cells and header cells for data tables that have two or more logical levels of row or column headers.
      i) Frames shall be titled with text that facilitates frame identification and navigation.
      j)     Pages shall be designed to avoid causing the screen to flicker with a frequency greater than 2 Hz and lower than 55 Hz.
      k) A text-only page, with equivalent information or functionality, shall be provided to make a web site comply with the provisions of this part, when compliance cannot be accomplished in any other way. The content of the text-only page shall be updated whenever the primary page changes.
      l)     When pages utilize scripting languages to display content, or to create interface elements, the information provided by the script shall be identified with functional text that can be read by assistive technology.
      m) When a web page requires that an applet, plug-in or other application be present on the client system to interpret page content, the page must provide a link to a plug-in or applet that complies with §1194.21(a) through (l).
      n)   When electronic forms are designed to be completed on-line, the form shall allow people using assistive technology to access the information, field elements, and functionality required for completion and submission of the form, including all directions and cues.
      o)    A method shall be provided that permits users to skip repetitive navigation links.
      p)    When a timed response is required, the user shall be alerted and given sufficient time to indicate more time is required.
      q)    When software is designed to run on a system that has a keyboard, product functions shall be executable from a keyboard where the function itself or the result of performing a function can be discerned textually.
      r)     Applications shall not disrupt or disable activated features of other products that are identified as accessibility features, where those features are developed and documented according to industry standards. Applications also shall not disrupt or disable activated features of any operating system that are identified as accessibility features where the application programming interface for those accessibility features has been documented by the manufacturer of the operating system and is available to the product developer.
      (s)    A well-defined on-screen indication of the current focus shall be provided that moves among interactive interface elements as the input focus changes. The focus shall be programmatically exposed so that assistive technology can track focus and focus changes.
      (t)     Sufficient information about a user interface element including the identity, operation and state of the element shall be available to assistive technology. When an image represents a program element, the information conveyed by the image must also be available in text.
      (u)   When bitmap images are used to identify controls, status indicators, or other programmatic elements, the meaning assigned to those images shall be consistent throughout an application's performance.
      (v)    Textual information shall be provided through operating system functions for displaying text. The minimum information that shall be made available is text content, text input caret location, and text attributes.
      (w)  Applications shall not override user selected contrast and color selections and other individual display attributes.
      (x)    When animation is displayed, the information shall be displayable in at least one non-animated presentation mode at the option of the user.
      (y)    Color coding shall not be used as the only means of conveying information, indicating an action, prompting a response, or distinguishing a visual element.
      (z)    When a product permits a user to adjust color and contrast settings, a variety of color selections capable of producing a range of contrast levels shall be provided.
       a)Software shall not use flashing or blinking text, objects, or other elements having a flash or blink frequency greater than 2 Hz and lower than 55 Hz.
(      b)                       When electronic forms are used, the form shall allow people using assistive technology to access the information, field elements, and functionality required for completion and submission of the form, including all directions and cues.

Log on to below url for more on the same :
http://webaim.org/standards/508/checklist

For more on QTP automation testing log on to QTP Testing




BlockInput Feature In QTP

Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature whioch has been discussed in this very articles on automation testing using QTP which is Blockinput feature.


 QTP provides BlockInput method to prevent keyboard and mouse input events from reaching applications.
UnblockInput method Re-enables keyboard and mouse input events after a BlockInput statement was used to block them.
'The following example uses the BlockInput method to block keyboard
'and mouse input to the QuickTest Professional computer during the run session.
SystemUtil.BlockInput
Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").WebEdit("userName").Set "mercury"
Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").WebEdit("password").SetSecure "4082986e39ea4ssdd0dbf8c5a29429fe138c6efc"
Browser("Welcome: Mercury Tours").Page("Welcome: Mercury Tours").Image("Sign-In").Click 2, 2
SystemUtil.UnblockInput

These two methods of the SystemUtil class is genuinely used to block the user from entering data through keyboard while the script is in execution mode.
Genuinely for security concerns this utility method is utilised at the best level.



For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP 


 

QTP Reusable Functions Codes 5

QTP Reusable Function Codes :


Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort..


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, this trick somehow is related to the simple concept applied in excel, however that we can deal separately.
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) 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.
4) 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



Debug Run


   1. Step Into

      Choose Debug > Step Into, click the Step Into button, or press F11 to run only the current line of the active test or component. If the current line of the active test or component calls another action or a function, the called action/function is displayed in the QuickTest window, and the test or component pauses at the first line of the called action/function.

   2. Step Out

      Choose Debug > Step Out or click the Step Out button, or press SHIFT+F11 only after using Step Into to enter a action or a user-defined function. Step Out runs to the end of the called action or user-defined function, then returns to the calling action and pauses the run session.

   3. Step Over

      Choose Debug > Step Over or click the Step Over button, or press F10 to run only the current step in the active test or component. When the current step calls another action or a user-defined function, the called action or function is executed in its entirety, but the called action script is not displayed in the QuickTest window.

'Example of How to use functions.

' Example use DSN created for database of Flight sample application.


SQL="SELECT * FROM ORDERS"
connection_string="QT_Flight32"

isConnected = db_connect ( curConnection ,connection_string )

If isConnected = 0 then
   ' execute the basic SQL statement
   set myrs=db_execute_query( curConnection , SQL )
   ' report the query and the connection string
   Reporter.ReportEvent micInfo ,"Executed query and created recordset ","Connection_string is ==> " & connection_string & " SQL   
query is ===> " & SQL    ' show the number of rows in the table using a record set
   msgBox " Quantity of rows in queried DB ( db_get_rows_count )==> " & db_get_rows_count( myrs )
   ' show the number of rows in the table using a new SQL statement
   msgBox " Quantity of rows in queried DB (db_get_rows_count_SQL ) ==> " & db_get_rows_count_SQL( curConnection , "SELECT COUNT(*) FROM ORDERS" )
   ' change a value of a field in an existing row
   rc = db_set_field_value (curConnection, "ORDERS" , "Agents_Name" , "test", "Agents_Name", "AGENT_TESTER")
   ' examples of how to retrieve values from the table
   msgBox "val row 0 col 0: " & db_get_field_value( myrs , 0 , 0 )
   msgBox "val row 0 col 1: " & db_get_field_value( myrs , 0 , 1 )
   msgBox "val row 1 col Name: " & db_get_field_value( myrs , 1 , "Agents_Name" )
   msgBox "val SQL row 1 col Name: " & db_get_field_value_SQL( curConnection , "ORDERS" , 1 , "Agents_Name" )
   db_disconnect curConnection
End If

' Database Functions library

'db_connect

' The function creates a new connection session to a database.
' curSession - the session name (string)
' connection_string - a connection string
' for example the connection_string can be "DSN=SQLServer_Source;UID=SA;PWD=abc123"

Function db_connect( byRef curSession ,connection_string)

   dim connection
   on error Resume next
   ' Opening connection
   set connection = CreateObject("ADODB.Connection")
    If Err.Number <> 0 then
   db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
   err.clear
   Exit Function
   End If
   connection.Open connection_string
   If Err.Number <> 0 then
   db_connect= "Error # " & CStr(Err.Number) & " " & Err.Description
   err.clear
   Exit Function
   End If
   set curSession=connection
   db_connect=0
End Function

' db_disconnect

' The function disconnects from the database and deletes the session.
' curSession - the session name (string)

Function db_disconnect( byRef curSession )

   curSession.close
   set curSession = Nothing
End Function

' db_execute_query

' The function executes an SQL statement.
' Note that a db_connect for (arg1) must be called before this function
' curSession - the session name (string)
' SQL - an SQL statement

Function db_execute_query ( byRef curSession , SQL)

   set rs = curSession.Execute( SQL )
   set db_execute_query = rs
End Function

' db_get_rows_count

' The function returns the number of rows in the record set
' curRS - variable , contain record set , that contain all values that retrieved from DB by query execution

Function db_get_rows_count( byRef curRS )
   dim rows
   rows = 0
   curRS.MoveFirst
   Do Until curRS.EOF
   rows = rows+1
   curRS.MoveNext
   Loop
   db_get_rows_count = rows
End Function

' db_get_rows_count_SQL

' The function returns the number of rows that are the result of a given SQL statement
' curSession - the session name (string)
' CountSQL - SQL statement

Function db_get_rows_count_SQL( byRef curSession ,CountSQL )
   dim cur_rs
   set cur_rs = curSession.Execute( CountSQL )
   db_get_rows_count_SQL = cur_rs.fields(0).value
End Function

' db_get_field_value_SQL

' curSession - variable denote current active connection
' tableName - name of the table , where value should be retrieved
' rowIndex - row number
' colName - the column name.

Function db_get_field_value_SQL( curSession , tableName , rowIndex , colName )

   dim rs
   SQL = " select " & colName & " from " & tableName
   set rs = curSession.Execute( SQL )
   rs.move rowIndex
   db_get_field_value_SQL = rs.fields(colName).value
End Function

' db_get_field_value

' The function returns the value of a single item of an executed query.
' Note that a db_execute_query for (arg1) must called before this function
' curRecordSet - variable , contain record set , that contain all values that retrieved from DB by query execution
' rowIndex - the row index number (zero based)
' colIndex - the column index number (zero based) or the column name.
' returned values
' -1 - requested field index more than exists in record set

Function db_get_field_value( curRecordSet , rowIndex , colIndex )

   dim curRow
   curRecordSet.MoveFirst
   count_fields = curRecordSet.fields.count-1
   If ( TypeName(colIndex)<> "String" ) and ( count_fields < colIndex ) then
   db_get_field_value = -1 'requested field index more than exists in recordset
   Else
   curRecordSet.Move rowIndex
   db_get_field_value = curRecordSet.fields(colIndex).Value
   End If
End Function

' db_set_field_value

' The function changes the value of a field according to a search criteria.
' We search for a certain row according to a column name and the desired vale, then we change a value in that row according
' to a desired columns
' curConnection - the session name (string)
' tableName - name of the table , where value should be retrieved
' colFind - the column we search the criteria in
' colFindValue - the value we search in the column
' colChange - the column were we want to change the value
' colChangeValue - the new value ' returned values

' -1 - requested field index that doesn't exists in the recordset

Function db_set_field_value(
curConnection, tableName , colFind , colFindValue, colChange, colChangeValue)
   dim curRow
   dim updateSQL
   dim checkSQL
   checkSQL = "select * from Details"
   set myrs1 = db_execute_query( curConnection , SQL )
   myrs1.MoveFirst
   count_fields = myrs1.fields.count
   If ( TypeName(colFind)<> "String" ) or ( TypeName(colChange)<> "String" ) then
   db_set_field_value = -1 'requested field index that doesn't exists in the record set
   Else
   updateSQL = "UPDATE " & tableName & " SET " & colChange & "='" & colChangeValue & "' WHERE " & colFind & "='" & colFindValue &    "'"
   set myrs1 = db_execute_query( curConnection , updateSQL )
   db_set_field_value = 1 'operation suceeded
   End If
End Function

' db_add_row

' The function adds a new row to the desired table

' curConnection - variable , contains a recordset , that contains all the values to be retrieved from DB by query execution
' tableName - name of the table , where value should be retrieved from
' values - array that contains values to be entered in a new row to the table.
' Note: the function must receive values for all the columns in the table!
' returned values
' -1 - the number of values to be entered to the table doesn't fit the number of columns
' 1 - execution of the query succeed and the data was entered to the table

Function db_add_row(curConnection, tableName , byRef values)

   dim i
   dim updateSQL
   dim myrs1
   updateSQL = "INSERT INTO " & tableName & " VALUES ("
   arrLen = UBound (values) - LBound (values) + 1
   set myrs1=db_execute_query( curConnection , SQL )
   myrs1.MoveFirst
   count_fields = myrs1.fields.count
   ' check if numbers of values fit the numbers of columns
   If arrLen <> count_fields then
   db_add_row = -1
   Else
   For i = 0 to arrLen-1
   updateSQL = updateSQL & values (i)
   If i <> arrLen-1 then
   updateSQL = updateSQL & ","
   End If
   Next
   updateSQL = updateSQL & ")"
   set myrs1 = db_execute_query( curConnection , updateSQL )
   db_add_row = 1
End If
End Function

' represent_values_of_RecordSet

' the function reports all the values on fields in a record set
' curRS - variable , contains the recordset , that contains all the values that were retrieved from the DB by the query execution

Function represent_values_of_RecordSet( myrs)

dim curRowString
myrs.MoveFirst
reporter.ReportEvent 4,"Fields quantity" , myrs.fields.count
count_fields = myrs.fields.count-1
curRow=0
Do Until myrs.EOF
   curRowString= ""
   curRow = curRow+1
   For ii=0 to count_fields
   curRowString = curRowString& "Field " &"==> " & myrs.fields(ii).Name &" : Value ==>" & myrs.fields(ii).Value & vbCrLf
   Next
   myrs.MoveNext
   reporter.ReportEvent 4,"Current row"& curRow , curRowString
Loop
End Function





Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP

QTP Reusable Functions Codes 4


QTP Reusable Function Codes :


Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort.

1. Can I change the Active Screen which is shown on every new test?

You can change the Active Screen to any valid HTML page. The page can be located either locally or on the network.

For example, if you want your entire organization to view the same Active Screen when opening QuickTest Professional, open the NewTest.inf file located in QuickTest Professional\dat\SnapShots folder and add the following line:

FileName1= "any full path to an HTML file"

For example:
FileName1=\mercury\public\MainPage.html

2. How do I create an action template?

If you want to include one or more statements in every new action in your test, you can create an action template. For example, if you always enter your name as the author of an action, you can add this comment line to your action template. An action template applies only to actions created on your computer.

To create an action template, create a text file containing the comments, function calls, and other statements that you want to include in your action template. The text file must be in the structure and format used in the Expert View.

Save the text file as ActionTemplate.mst in your QuickTest Professional\dat folder. All new actions you create contain the script lines from the action template.

3. How can I configure the report to show only errors by default?

You can configure the report to show only errors by default by adding the following section to the QTReport.ini file in your QuickTest Professional\bin folder.

[FilterDialog]

ReportAppDefaultFilter=1 # for error only

ReportAppDefaultFilter=3 # shows all messages (default)

4. How do I use environment variables?

QuickTest supports using environment variables. Environment variables can be either system variables or user-defined variables.

You can define the user-defined variables in an external file QuickTest reads when it is launched.

5. I have a Microsoft Access database that contains data I would like to use in my test. How do I do this?

The Expert View enables you to access databases using ADO and ODBC. Below is a sample test that searches for books written by an author in the "Authors" table of the database.

Dim MyDB
Dim MyEng
Set MyEng = CreateObject("DAO.DBEngine.35")
Dim Td
Dim rs
' Specify the database to use.
Set MyDB = MyEng.OpenDatabase("BIBLIO.MDB")
' Read and use the name of the first 10 authors.
Set Td = MyDB.TableDefs("Authors")
Set rs = Td.OpenRecordset
rs.MoveFirst
For i = 1 To 10
   Browser("Book Club").Page("Search Books").WebEdit("Author Name").Set rs("Author")
   Browser("Book Club").Page("Search Books").WebButton("Search").Click
Next

6. How do I add a manual wait step to my test?

A manual wait (think time) can be added to a QuickTest Professional test using the following command:

Call Wait()

7. How do I make the test prompt the user for input while it is running?

The VBScript InputBox function enables you to display a dialog box that prompts the user for input and then continues running the test. You can use the value that was entered by the user later in the test. For more information on the InputBox function, refer to the VBScript Reference.

The following example shows the InputBox function used to prompt the user for a password.

Browser("Mercury Tours").Page("Mercury Tours").WebEdit("username").Set "administrator"

Passwd = InputBox ("Enter password", "User Input")

Browser("Mercury Tours").Page("Mercury Tours").WebEdit("password").Set Passwd

8. How can I configure the report to show only errors by default?

You can configure the report to show only errors by default by adding the following section to the QTReport.ini file in your QuickTest Professional\bin folder.

[FilterDialog]

ReportAppDefaultFilter=1 # for error only

ReportAppDefaultFilter=3 # shows all messages (default)

9. How can I remove test result files from old tests?

You can use the Test Results Deletion Tool to view a list of all the test results in a specific location in your file system or in a Quality Center project. You can then delete any test results that you no longer require.

The Test Results Deletion Tool enables you to sort the test results by name, date, size, and so forth, so that you can easily identify the results you want to delete.

You can find this utility in Start > Programs > QuickTest Professional > Tools > Test Results Deletion Tool.

10. How can I launch a new browser from a test?

A new browser window (and any other application) can be launched from within a test by adding the following step to your test:

SystemUtil.Run "iexplore.exe", "http://www.testingfaqs.co.in"

11. How can I record on nonstandard menus?

You can modify how QuickTest behaves when it records menus.

The options that control this behavior are located in the Advanced Windows Applications Options dialog box. (Tools > Options > Windows Applications > Advanced).

12. How can I terminate an application that is not responding?

You can terminate any standard application while running a test in QuickTest by adding one of the following steps to the test:

SystemUtil.CloseProcessByName "app.exe"
SystemUtil.CloseProcessByWndTitle "Some Title"

13. Can I copy and paste to and from the Clipboard during a test run?

You can use the Clipboard object to copy, cut, and paste text during a QuickTest test run.

The object has the same methods as the Clipboard object available in Visual Basic:

Clear
GetData
GetFormat
GetText
SetData
SetText

Below is an example of Clipboard object usage:

Set MyClipboard = CreateObject("Mercury.Clipboard")
MyClipboard.Clear
MyClipboard.SetText "TEST"
MsgBox MyClipboard.GetText

14. How do I close QuickTest after "n" test runs when running from Quality Center?

When running multiple QuickTest tests from Quality Center, you can specify that you want to close QuickTest after a specified number of tests are executed.

To do so, add the following lines to the end of the mic.ini file, located in your QuickTest Professional\bin folder:
[RemoteAgent]
CloseToolAfterRuns= (number)

15. Adding Defects to Quality Center

Connects to Quality Center (TestDirector) from a QuickTest test and adds a bug to the database.

Dim TDConnection
Set TDConnection = CreateObject("TDApiOle.TDConnection")
TDConnection.InitConnection "http://yovav/tdbin" ' URL for the DB
TDConnection.ConnectProject "TD76","bella","pino" ' Valid login information
If TDConnection.Connected Then
MsgBox("Connected to " + chr (13) + "Server " + TDConnection.ServerName _
+ chr (13) +"Project " + TDConnection.ProjectName )
Else
MsgBox("Not Connected")
End If
'Get the IBugFactory
Set BugFactory = TDConnection.BugFactory
'Add a new empty bug
Set Bug = BugFactory.AddItem (Nothing)
'Fill the bug with relevant parameters
Bug.Status = "New"
Bug.Summary = "Connecting to TD"
Bug.Priority = "4-Very High" ' depends on the DB
Bug.AssignedTo = "admin" ' user that must exist in the DB's users list
Bug.DetectedBy = "admin" ' user that must exist in the DB's users list
'Post the bug to database (commit)
Bug.Post

16. Using Message Boxes That Close Automatically

The function below shows a message box that disappears after the specified timeout (in seconds). The script execution then continues.

Public Sub MsgBoxTimeout (Text, Title, TimeOut)
   Set WshShell = CreateObject("WScript.Shell")
   WshShell.Popup Text, TimeOut, Title
End Sub

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

17. Using Microsoft Word Spell Check

The following code shows a function for checking the number of spelling and grammar errors in a string. This function is also used to check the accuracy of a specific property in all the objects of a given application.

Function NumberOfSpellErrors(strText)
Dim objMsWord
Set objMsWord = CreateObject("Word.Application")
objMsWord.WordBasic.FileNew
objMsWord.WordBasic.Insert strText
NumberOfSpellErrors = objMsWord.ActiveDocument.SpellingErrors.Count
objMsWord.Documents.Close (False)
objMsWord.Quit ' close the application
Set objMsWord = Nothing' Clear object memory
End Function

' The following function uses the Spell errors function to check a specific property
' of all the objects with a given description which are under a given parent

Sub CheckAllObjects(ParentObj, ObjDesc, PropName)
Dim ObjCol, idx, PropValue, OldReportMode
OldReportMode = Reporter.Filter
Reporter.Filter = 2 ' Report only errors
If (IsNull(ParentObj)) Then
Set ObjCol = Desktop.ChildObjects(ObjDesc)
Else
Set ObjCol = ParentObj.ChildObjects(ObjDesc)
End If
For idx=0 to ObjCol.count-1
PropValue = ObjCol.Item(idx).GetROProperty(PropName)
RetVal = NumberOfSpellErrors(PropValue) ' The actual spell check result
If (RetVal > 0) Then
ReportText = "Object #" & idx+1 & ": The '" & PropName & "' Property has " & RetVal & " spell errors (" & PropValue & ")"
Reporter.ReportEvent 1, "Spell Check", ReportText
End If
Next
Reporter.Filter = OldReportMode
End Sub

'''''''''''''''''''''''''''''''''''''
' An example of usage:
' Go over all the static objects in the Login window of the Flight Application
' and for each object check the text for spelling and grammatical errors
'''''''''''''''''''''''''''''''''''''

' Go over all the links in the page and report all the ones that fail the spellcheck
Set Desc = Description.Create()
Desc("nativeclass").Value = "Static"
Set Obj = Dialog("nativeclass:=#32770", "text:=Login")
' Invoke the Flight Application before calling the function
CheckAllObjects Obj, Desc, "text"


18. Using Microsoft Outlook to Send Email

The code below illustrates two methods for sending email using the VBScript code in QuickTest Professional, and two different COM objects.

' Example 1

Function SendMail(SendTo, Subject, Body, Attachment)
Set ol=CreateObject("Outlook.Application")
Set Mail=ol.CreateItem(0)
Mail.to=SendTo
Mail.Subject=Subject
Mail.Body=Body
If (Attachment <> "") Then
Mail.Attachments.Add(Attachment)
End If
Mail.Send
ol.Quit
Set Mail = Nothing
Set ol = Nothing
End Function

' Example 2

Function SendMail(SendFrom, SendTo, Subject, Body)
Set objMail=CreateObject("CDONTS.Newmail")
ObjMail.From = SendFrom
ObjMail.To = SendTo
ObjMail.Subject = Subject
ObjMail.Body = Body
ObjMail.Send
Set objMail = Nothing
End Function

19. DP Example

SetEditBox "userID", 0, "Sairam"

Sub SetEditBox(ObjName, index, TestData)
strHandle = Window("RegExpWndClass:=IEFrame","index:=0" ).GetROProperty("hWnd")
Set gobjBrowser = Browser("hWnd:=" & strHandle)
Set gobjPage = gobjBrowser.Page("index:=0")
Set objDescription = Description.Create()
objDescription("Class Name").Value = "WebEdit"
objDescription("html tag").Value = "INPUT"
objDescription("name").Value =ObjName
objDescription("index").Value = index
gobjPage.WebEdit(objDescription).Set TestData
set gobjBrowser = nothing
Set gobjPage = nothing
End Sub

20. SaveAs Excel file with QTP

Set xl = CreateObject("Excel.Application")
xl.visible = True
xl.Application.Workbooks.open "C:\sai.xls"
xl.Worksheets(1).Activate
xl.Application.Visible = True
xl.Cells(1,1).Value = "mum"
xl.Cells(1,2).Value = "dad"
xl.activeworkbook.SaveAs("C:\sai1.xls")
xl.Application.Quit


Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP



QTP Reusable Functions Codes 3

QTP Reusable functions :


Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort..
 
1. BEEP from QTP

' Three methods of issuing a BEEP from QTP

' Method 1
Extern.Declare micLong,"MessageBeep","User32","MessageBeep",micLong
retVal = Extern.MessageBeep(&HFFFFFFFF)
MsgBox retVal 'The return value should be 1.

' Method 2
Err.Number = 0
On Error Resume Next
Extern.Declare micLong,"MessageBeep","User32","MessageBeep",micLong
Extern.MessageBeep(&HFFFFFFFF)
If (Err.Number <> 0) Then
MsgBox Err.Description
End If

' Method 3
Extern.Declare micLong,"Beep","Kernel32","Beep",micLong,micLong
retVal = Extern.Beep(1000,250) 'The first number is frequency the second is duration.

MsgBox extract_number("This user belongs to 10 groups")
MsgBox extract_number("206 features assigned to the user.")

2. Check for Required URL

startURL = "www.google.com" ' Amend this to your required URL

' If no browser open, open browser and navigate to required URL
If Not Browser("CreationTime:=0").Exist Then
   Call launch(startURL)
Else

' Get the URL of the current open browser
currentURL=Browser("CreationTime:=0").GetROProperty("OpenURL")
' If not correct URL navigate to required URL
If Not currentURL = "www.google.com" Then
   Call launch(startURL)
End If
End If

Function launch(startURL)
 ' Create IE object and navigate
 ' to required URL
 set IE = CreateObject("InternetExplorer.Application")
 IE.Visible = true
 IE.Navigate startURL
End function

3. Close QTP with QTP script

Private Function CloseQTP
   Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
   Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'QTPro.exe'")
   For Each objProcess in colProcess
    objProcess.Terminate()
   Next
   Set objWMIService = Nothing
   Set colProcess = Nothing
End Function

4. Open any Appllication through QTP

   ' Function OpenApp
   ' ------------------
   ' Open a specified application
   ' Parameter: application - the application full name (including location)
   '@Description Opens an application
   '@Documentation Open the application.

   Function OpenApp (application)
     systemUtil.Run application
    End Function

5. Adding any information to QTP Results

   ' AddToTestResults
   ' --------------
   ' Add a Report.Event step to the Test Results
   'Parameters:
   ' status - Step status (micPass, micFail, micDone or micWarning)
   ' StepName - Name of the intended step in the report (object name)
   ' details - Description of the report event    '
   '@Description Reports an event to the Test Results
   '@Documentation Report an event to the Test Results.

   Public Function AddToTestResults (status, StepName, details)
       Reporter.ReportEvent status, StepName, details
   End Function

6. Enable Doubleclick Event in QTP

Enable the ondblclick event in the Web Event Recording Configuration

To enable special event handling, use the Web Event Recording Configuration utility.
1. Go to Tools -> Web Event Recording Configuration.
2. Click .
3. Expand the Standard Objects branch.
4. Select the object you want to configure.
5. Go to Event -> Add -> ondblclick. The event will be added to the list on the right.
6. Select "If Handler" in the Listen column.
7. Select "Enabled" in the Record column.
8. Click to close the dialogs.

7. DSN - Less Connection

Public sconn
uid = "UID"
pwd = "PWD"
ServerName = "Server Name"

Connection()

Function Connection()
Set sconn = CreateObject("ADODB.connection")
sconn.Open "Driver=Microsoft ODBC for Oracle;Server="& ServerName &";Uid="& uid &";Pwd="& pwd &""
End Function

8. High-Level Automation Framework Information

At a very high level the framework components can be divided into two categories software part and documentation part. Here is my list of components ? you can add your item if anything is missing.

---------------------------------------------
All software code part
---------------------------------------------
Supporting libraries for Logging, error handling, Execution management
1. Tool specific code
2. Setup and configuration scripts
3. Test management code
4. Test data and Test data management code
5. Platform/OS specific scripts

---------------------------------------------
Non software part
---------------------------------------------
Folder structure
Documents
i. Coding guidelines
ii. Procedure for creating scripts
iii. Planning, design and review procedures
iv. Approach for automation
v. Approach for Testing automation code
vi. Automation documentation - how scripts work
vii. Setup and implementation procedures
viii. Defect tracking procedure for Automation scripts
ix. Source control procedures
x. Project plan
xi. Templates for effort estimation
xii. Template for test case categorization
xiii. Template for ROI calculation

9. Get Input Parameter Data and Use in Script

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object
Set pDefColl = qtApp.Test.ParameterDefinitions
Set pDef = pDefColl.Item(1)
MsgBox pDef.DefaultValue

10. Pass Test Data from MQC to QTP?

1) Create Test parameters in QTP (via file>Settings>Parameters) [These are the parameters that you see in QC, on the automated tab of the Configuration page in the Test Instance Propertirs.]

2) Create action parameters (Action Properties> Parameters)

3)Link action & test parameters together. To do this, go into Action Call Properties>Parameters. You'll see your action parameters here. Click in the Value column for a parameter and press the Configure Value button. This will open up the Value Configuration Options dialogue. In the parameter drop down list, select Test/action parameter and then, from the following Test parameters; Parameter drop down list, select the Test parameter that you want to link to your Action parameter.

This should then link the Test parameters to the Action parameters.

Then in your script, you'll use the parameters as follows: -

Browser("Browser_Name").Page("Page_Name").WebEdit("Edit_Name").Set Parameter("Parameter_Name")

11. Get the Attachement from QC to local machine

To get attachment from test

Public Function GetTestAttachmentPath(TDAttachmentName) 'Returns File Path
'Test Director TDAPIOLELib object variables
Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
Dim otaAttachment 'As TDAPIOLELib.Attachment
Dim otaAttachmentList 'As TDAPIOLELib.List
Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
Dim otaExtendedStorage 'As TDAPIOLELib.ExtendedStorage
Dim strPath 'As String

Set otaAttachmentFactory = QCUtil.CurrentTest.Attachments
Set otaAttachmentFilter = otaAttachmentFactory.Filter
otaAttachmentFilter.Filter("CR_REFERENCE") = "'TEST_" & QCUtil.CurrentTest.Id & "_" & TDAttachmentName & "'"
Set otaAttachmentList = otaAttachmentFilter.NewList
If otaAttachmentList.Count = 1 Then
Set otaAttachment = otaAttachmentList.Item(1)
otaAttachment.Load True, ""
strPath = otaAttachment.FileName
ElseIf otaAttachmentList.Count > 1 Then
Reporter.ReportEvent micFail, "Failure in library function 'GetTestAttachmentPath'", _ "Found more than one attachment '" & TDAttachmentName & "' in test '" & _ QCUtil.CurrentTest.Name & "'."
strPath = ""
ElseIf otaAttachmentList.Count < 1 Then
Reporter.ReportEvent micFail, "Failure in library function 'GetTestAttachmentPath'", _ "Found 0 attachments '" & TDAttachmentName & "' in test '" & _ QCUtil.CurrentTest.Name & "'."
strPath = ""
End If

GetTestAttachmentPath = strPath
Set otaAttachmentFactory = Nothing
Set otaAttachment = Nothing
Set otaAttachmentList = Nothing
Set otaAttachmentFilter = Nothing

End Function

To get attachment from folder

Public Function GetFolderAttachmentPath(TDAttachmentName, TDFolderPath) 'Returns File Path

'Test Director TDAPIOLELib object variables
Dim otaAttachmentFactory 'As TDAPIOLELib.AttachmentFactory
Dim otaAttachment 'As TDAPIOLELib.Attachment
Dim otaAttachmentList 'As TDAPIOLELib.List
Dim otaAttachmentFilter 'As TDAPIOLELib.TDFilter
Dim otaTreeManager 'As TDAPIOLELib.TreeManager
Dim otaSysTreeNode 'As TDAPIOLELib.SysTreeNode
Dim otaExtendedStorage 'As TDAPIOLELib.TreeManager
Dim intNdId
Dim strPath 'As String
Set otaTreeManager = QCUtil.TDConnection.TreeManager
Set otaSysTreeNode = otaTreeManager.NodeByPath(TDFolderPath)
Set otaAttachmentFactory = otaSysTreeNode.Attachments
Set otaAttachmentFilter = otaAttachmentFactory.Filter
intNdId = otaSysTreeNode.NodeID
otaAttachmentFilter.Filter("CR_REFERENCE") = "'ALL_LISTS_" & intNdId & "_" & TDAttachmentName & "'"
Set otaAttachmentList = otaAttachmentFilter.NewList
If otaAttachmentList.Count > 0 Then
Set otaAttachment = otaAttachmentList.Item(1)
otaAttachment.Load True, ""
strPath = otaAttachment.FileName
Else
Reporter.ReportEvent micFail,"Failure in library function 'GetFolderAttachmentPath'", _ "Failed to find attachment '" & TDAttachmentName & "' in folder '" & TDFolderPath & "'."
End If
GetFolderAttachmentPath = strPath
Set otaAttachmentFactory = Nothing
Set otaAttachment = Nothing
Set otaAttachmentList = Nothing
Set otaAttachmentFilter = Nothing
Set otaTreeManager = Nothing
Set otaSysTreeNode = Nothing

End Function




Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP

QTP Reusable Functions Codes 2

QTP Reusable function Codes :
Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort.

1. Getting Number from String

Function extract_number(msg)
   Dim re, matches, item, result
   Set re = New RegExp
   re.pattern = "[A-Za-z -.]*(\d+).*"
   Set matches = re.Execute(msg)
   If matches.Count > 0 Then
      Set item = matches(0)
      If item.SubMatches.Count > 0 Then
         result = item.SubMatches(0)
      Else
         result = -1
      End If
   Else
           result = -1
   End If
   extract_number = result
End Function

MsgBox extract_number("This user belongs to 10 groups")
MsgBox extract_number("206 features assigned to the user.")

2. Close All the opened Browsers Except QC opened browser

On Error Resume Next
Dim intWndCnt
Dim oDesc, oWnd
'Create Object description
Set oDesc = Description.Create '
Set oWnd = Desktop.ChildObjects(oDesc)
intWndCnt = oWnd.Count
For i = 0 to intWndCnt - 1
Set TmpObj = oWnd.item(i)
strTmpTitle = oWnd.item(i).GetROProperty("Text")
If instr(1,strTmpTitle, "Microsoft Internet Explorer",1) > 0 Then
   If instr(1,strTmpTitle, "Mercury Quality Center",1) > 0 Then
       'msgbox "Title :" & oWnd.item(i).GetROProperty("Text")
   Else
       'msgbox "Close :" & oWnd.item(i).GetROProperty("Text")
       oWnd.item(i).close
   End if
End If
Next
'Clean up
Set oDesc = nothing
Set oWnd = nothing

3. Close all opened Excel files

Public Function fn_close_all_excel_files()
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colProcessList = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'EXCEL.EXE'")
For Each objProcess in colProcessList
   objProcess.Terminate()
Next
End Function

4. Excel sheet column count

Public Function dtGetColCount (sSheetName)
   On Error Resume Next
   Do
   i = i + 1
   sColName = DataTable.GetSheet(sSheetName).GetParameter(i).Name
   Loop While 0 = Err.Number
   'GetParameter throws an error when using an index that is out of bounds ...
   'We can use this functionality to ASSUME that it's an unused column.
   'We've come to the end of our USED columns
   dtGetColCount = i - 1
   On Error GoTo 0
End Function

5. Count Number of files in any Folder

iFileCount = 0
Set objFileSysOb = CreateObject("Scripting.FileSystemObject")
Set colFolderName = objFileSysOb.GetFolder("C:\Automation") ' Folder Path
Set vFiles =colFolderName.Files
For each vFileItem in vFiles
   print vFileItem
   iFileCount = iFileCount + 1
Next
print iFileCount

6. Create Dynamic Array

For i = 0 to 20
   Redim Preserve arrFileLines(i)
   arrFileLines(i) = "test" & i
Next

7. Close Dialog box

Function DialogClose (obj)
If obj.Dialog("nativeclass:=#32770").Exist(0) Then
   obj.Dialog("nativeclass:=#32770").WinButton("nativeclass:=Button","index:=0").Click
End If
RegisterUserFunc "Browser", "DialogClose", "DialogClose"
End Function

8. Create Dynamic Value

iDynamicValue = now
iDynamicValue = replace(iDynamicValue,"/","")
iDynamicValue = replace(iDynamicValue,":","")
iDynamicValue = replace(iDynamicValue," ","")
iDynamicValue = replace(iDynamicValue,"PM","")
iDynamicValue = replace(iDynamicValue,"AM","")
msgbox iDynamicValue

9. Get QTP file path

Set qtApp = CreateObject("QuickTest.Application") ' Create the Application objectqtpApp.Test.Location
TestLoc = qtApp.Test.Location
MsgBox TestLoc

10. IS QC Connected?

Set qtApp = CreateObject("QuickTest.Application")
If qtApp.TDConnection.IsConnected Then
   msgbox "QC"
Else
   msgbox "Local"
End If

(or)

if QCUtil.IsConnected then
   Reporter.ReportEvent 0, "Connected", "Connected to server: " + QCUtil.QCConnection.ServerName + chr (13) +"Project: " +
   QCUtil.QCConnection.ProjectName + chr (13) + "Domain: " + QCUtil.QCConnection.DomainName
else
   Reporter.ReportEvent 1, "Not connected", "Not connected to Quality Center"
end if

11. Keyboard Key Press through QTP Script

'Create Shell Object
Set WshShell = CreateObject("WScript.Shell")
'Send any Functinal Keys
' ALT = %
' F4 = {F4}
WshShell.SendKeys "%{F4}"
' Set shell object to Null
Set WshShell=nothing

12. QTP9.0 Futurs

- Open and edit multiple Object Repositories
- Easy conversion to/from XML
- Multiple object repositories per test asset
- Leveraging the automation assets across multiple groups
- Missing resources panel
- Pass parameters between Actions





Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP

QTP Reusable Functions Codes

Automation testing using QTP has always been talked upon the most in the testing industry. There are numerous features available within this very toolset, but most of us might not be aware of this very feature which has been discussed in this very articles on automation testing using QTP which is functions created in Vbscript , and is very useful in code customization to meet our automation testing requirements , as it reduces the script maintenance effort.


1. Action Template 

If you need any default Template to be loaded whenever you create a new Action, just follow these steps.

  1. Design the template with all the statements and comments in a text file.
  2. Save the text file as "ActionTemplate.mst" to the "QuickTest Installation Folder" under \dat folder.
  3. Start QTP and whenever you create new Actions, you can find the template by default.

2. ADO Connection Function - Open the ADO connection through QTP

Public Function BIP_sqlDBConnect(sConnectionStr)
   ' Create the Connection Object.
   Set objADOConnection = CreateObject("ADODB.Connection")
   ' Set the Connection String.
   objADOConnection.Open (sConnectionStr)
   'ReturnADO object reference
   Set BIP_sqlDBConnect = objADOConnection
End Function

3. Close QTP - Closing the QTP after Execution

Private Function CloseQTP
   Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
   Set colProcess = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = 'QTPro.exe'")
   For Each objProcess in colProcess
   objProcess.Terminate()
   Next
   Set objWMIService = Nothing
   Set colProcess = Nothing
End Function

4. Open Application

' Open a specified application
' Parameter: application - the application full name (including location)
'@Description Opens an application
'@Documentation Open the application.

Function OpenApp (application)
   systemUtil.Run application
End Function

5. Add Test Results

' Add a Report.Event step to the Test Results
'Parameters:
' status - Step status (micPass, micFail, micDone or micWarning)
' StepName - Name of the intended step in the report (object name)
' details - Description of the report event
'@Description Reports an event to the Test Results
'@Documentation Report an event to the Test Results.

Public Function AddToTestResults (status, StepName, details)
   Reporter.ReportEvent status, StepName, details
End Function

6. Verify Object Is Enabled

' Add a Report.Event step to the Test Results
'Parameters:
' status - Step status (micPass, micFail, micDone or micWarning)
' StepName - Name of the intended step in the report (object name)
' details - Description of the report event
'@Description Reports an event to the Test Results
'@Documentation Report an event to the Test Results.

Public Function VerifyEnabled (obj)
   Dim enable_property
   'Get the enabled property from the test object
   enable_property = obj.GetROProperty("enabled")
   If enable_property <> 0 Then ' The value is True (anything but 0)
     Reporter.ReportEvent micPass, "VerifyEnabled Succeeded", "The test object is enabled"
     VerifyEnabled = True
   Else
     Reporter.ReportEvent micFail, "VerifyEnabled Failed", "The test object is NOT enabled"
     VerifyEnabled = False
   End If
End Function

7. Verify Object Is Disabled

' Add a Report.Event step to the Test Results
'Parameters:
' status - Step status (micPass, micFail, micDone or micWarning)
' StepName - Name of the intended step in the report (object name)
' details - Description of the report event
'@Description Reports an event to the Test Results
'@Documentation Report an event to the Test Results.

Public Function VerifyDisabled (obj)
   Dim enable_property
   'Get the enabled property from the test object
   enable_property = obj.GetROProperty("disabled")
   If enable_property = 0 Then ' The value is False (0) - Enabled
     Reporter.ReportEvent micPass, "VerifyDisabled Succeeded", "The test object is enabled"
     VerifyDisabled = True
   Else
     Reporter.ReportEvent micFail, "VerifyDisabled Failed", "The test object is NOT enabled"
     VerifyDisabled = False
   End If
End Function

8. Get Value Property

' Return the object 'Value' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetValueProperty (obj)
   GetValueProperty = obj.GetROProperty("value")
End Function

9. Get Text Property

' Return the object 'Text' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetTextProperty (obj)
   GetTextProperty = obj.GetROProperty("text")
End Function

10. Get Position Property

' Return the object 'position' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetPositionProperty (obj)
   GetPositionProperty = obj.GetROProperty("position")
End Function

11. Get Selection Property

' Return the object 'selection' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetSelectionProperty (obj)
   GetSelectionProperty = obj.GetROProperty("selection")
End Function

12. Get Checked Property

' Return the object 'checked' property
'@Description Returns the Object value
'@Documentation Return the 'Test object name' 'test object type' value.

Public Function GetCheckedProperty (obj)
   GetCheckedProperty = obj.GetROProperty("checked")
End Function



Learn More On QTP Reusable Function creation codes :

QTP-reusable-functions-codes-5
QTP-reusable-functions-codes-4
QTP-reusable-functions-codes-3
QTP-reusable-functions-codes-2
QTP-reusable-functions-codes-1


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP


File system handling using Vbscript in QTP


File system handling using Vbscript in QTP is another example of AOM model that is utilized to suit our needs to write logs especially to generate the customized result files. Scripting.Filesystem object is the claas which is utilized to cater to the needs of the object creation and hence its property access.

How to Create a new text file ?
How to Check if a specific file exist ?
How to write data to a file ?
How to Read line from file ?
How to Read Entire Text file ?

How to Close an open file ?
How to Open a specified file and returns an object that can be used to read from, write to, or append to the file ?
How to Copy a file ?
How to Delete a file ?
How to Create a Folder if it does not Exists ?
How to Count Number of Lines in file ?
dim objFso
' creating the file system object
set objFso = CreateObject ("Scripting.FileSystemObject")

' Create a new txt file

' Parameters:
' FilePath - location of the file and its name

Function CreateFile (StrFilePath)

   ' variable that will hold the new file object
   dim NewFile
   ' create the new text File
   set NewFile = objFso.CreateTextFile(StrFilePath, True)
   set CreateFile = NewFile
End Function

' Check if a specific file exist

' Parameters:
' FilePath - location of the file and its name

Function CheckFileExists (StrFilePath)

   ' check if file exist
   CheckFileExists = objFso.FileExists(StrFilePath)
End Function

' Write data to file

' Parameters:
' FileRef - reference to the file
' str - data to be written to the file

Function WriteToFile (byref FileRef,str)

   ' write str to the text file
   FileRef.WriteLine(str)
End Function

' Read line from file

' Parameters:
' FileRef - reference to the file

Function ReadLineFromFile (byref FileRef)

   ' read line from text file
   ReadLineFromFile = FileRef.ReadLine
End Function

' Read Entire Text File Test

' Parameters:
' FileRef - reference to the file

Function ReadTextFileTest(StrFilePath)

   Const ForReading = 1, ForWriting = 2, ForAppending = 8
   Dim fso, f, Msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set f = fso.OpenTextFile(StrFilePath, ForReading)
   ReadTextFileTest = f.Readall()
End Function

' Closes an open file.

' Parameters:
' FileRef - reference to the file

Function CloseFile (byref FileRef)

   FileRef.close
End Function

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

' Parameters:
' FilePath - location of the file and its name
' mode options are:
' ForReading - 1
' ForWriting - 2
' ForAppending - 8

Function OpenFile (StrFilePath,mode)

   ' open the txt file and retunr the File object
   set OpenFile = objFso.OpenTextFile(StrFilePath, mode, True)
End Function

' Copy file.

' Parameters:
' FileRef - reference to the file

Sub FileCopy ( StrFilePathSource,StrFilePathDest)

   ' copy source file to destination file
   objFso.CopyFile StrFilePathSource, StrFilePathDest
End Function

' Delete a file.

' Parameters:
' FileRef - reference to the file

Sub FileDelete ( StrFilePath)
   ' copy source file to destination file
   objFso.DeleteFile ( StrFilePath)
End Function

' Create Folder if Not Exists.

Function ReportFolderStatus(fldr)

   Dim fso, msg
   Set fso = CreateObject("Scripting.FileSystemObject")
   If Not (fso.FolderExists(fldr)) Then
   Set f = fso.CreateFolder(fldr)
   End If
End Function

ReportFolderStatus("C:\Viplav")

' Count Number of Lines in txt file

Function NumberOfLines(FileName)

   i = 0
   Set objFSO = CreateObject("Scripting.FileSystemObject")
   Set objTextFile = objFSO.OpenTextFile(FileName, ForReading)
   Do Until objTextFile.AtEndOfStream
   Redim Preserve arrFileLines(i)
   arrFileLines(i) = objTextFile.ReadLine
   i = i +1
   Loop
   NumberOfLines = UBound(arrFileLines)
   objTextFile.Close
End Function

msgbox NumberOfLines("C:\Viplav\myfile.txt")




For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP

Excel Handling Through QTP


Excel handling using QTP is one of the most required utility that any QTP programmer need to be expert at . In the next few sections we shall be handling several excel handling codes that one can re-utilize as per his/her needs:

How to Create a new Excel Object with a default new Workbook ?
How to Close a open Excel Object ?
How to save a workbook according to the workbookIdentifier?
How to set the given 'value' in the cell ?
How to returns the cell's value according to its row column and sheet ?
How to get  returned an Excel Sheet according to the sheetIdentifier ?
How to insert a new worksheet into the active workbook ?
How to renames a worksheet's name ?
How to remove a worksheet from a workbook ?
How to create a new workbook in the excel application ?
How to open a previously saved Excel workbook and add it to the Application ?
How to set one of the workbooks in the application as Active workbook ?
How to close an open workbook ?
How to compare between two sheets ?



Dim ObjExcelApp 'As Excel.Application
Dim objExcelSheet 'As Excel.worksheet
Dim objExcelBook 'As Excel.workbook
Dim objFso 'As Scripting.FileSystemObject

' This function will return a new Excel Object with a default new Workbook

Function CreateExcel() 'As Excel.Application

   Dim objExcelSheet 'As Excel.worksheet
   Set ObjExcelApp = CreateObject("Excel.Application") 'Create a new excel Object
   ObjExcelApp.Workbooks.Add
   ObjExcelApp.Visible = True
   Set CreateExcel = ObjExcelApp
End Function

'This function will close the given Excel Object

'objExcelApp - an Excel application object to be closed

Sub CloseExcel(ObjExcelApp)

   Set objExcelSheet = ObjExcelApp.ActiveSheet
   Set objExcelBook = ObjExcelApp.ActiveWorkbook
   Set objFso = CreateObject("Scripting.FileSystemObject")
   On Error Resume Next
   objFso.CreateFolder "C:\Viplav"
   objFso.DeleteFile "C:\Viplav\ExcelExamples.xls"
   objExcelBook.SaveAs "C:\Viplav\ExcelExamples.xls"
   ObjExcelApp.Quit
   Set ObjExcelApp = Nothing
   Set objFso = Nothing
   Err = 0
   On Error GoTo 0
End Sub

'The SaveWorkbook method will save a workbook according to the workbookIdentifier

'The method will overwrite the previously saved file under the given path
'objExcelApp - a reference to the Excel Application
'workbookIdentifier - The name or number of the requested workbook
'path - the location to which the workbook should be saved
'Return "OK" on success and "Bad Workbook Identifier" on failure

Function SaveWorkbook(ObjExcelApp, workbookIdentifier, path) 'As String

   Dim workbook 'As Excel.workbook
   On Error Resume Next
   Set workbook = ObjExcelApp.Workbooks(workbookIdentifier)
   On Error GoTo 0
   If Not workbook Is Nothing Then
   If path = "" Or path = workbook.FullName Or path = workbook.Name Then
   workbook.Save
   Else
   Set objFso = CreateObject("Scripting.FileSystemObject")
   'if the path has no file extension then add the 'xls' extension
   If InStr(path, ".") = 0 Then
   path = path & ".xls"
   End If
   On Error Resume Next
   objFso.DeleteFile path
   Set objFso = Nothing
   Err = 0
   On Error GoTo 0
   workbook.SaveAs path
   End If
   SaveWorkbook = "OK"
   Else
   SaveWorkbook = "Bad Workbook Identifier"
   End If
End Function

'The SetCellValue method sets the given 'value' in the cell which is identified by

'its row column and parent Excel sheet
'objExcelSheet - the excel sheet that is the parent of the requested cell
'row - the cell's row in the objExcelSheet
'column - the cell's column in the objExcelSheet
'value - the value to be set in the cell

Sub SetCellValue(objExcelSheet, row, column, value)

   On Error Resume Next
   objExcelSheet.Cells(row, column) = value
   On Error GoTo 0
End Sub

'The GetCellValue returns the cell's value according to its row column and sheet

'objExcelSheet - the Excel Sheet in which the cell exists
'row - the cell's row
'column - the cell's column
'return 0 if the cell could not be found

Function GetCellValue(objExcelSheet, row, column)

   value = 0
   Err = 0
   On Error Resume Next
   tempValue = objExcelSheet.Cells(row, column)
    If Err = 0 Then
    value = tempValue
    Err = 0
   End If
    On Error GoTo 0
    GetCellValue = value
End Function

'The GetSheet method returns an Excel Sheet according to the sheetIdentifier

'ObjExcelApp - the Excel application which is the parent of the requested sheet
'sheetIdentifier - the name or the number of the requested Excel sheet
'return Nothing on failure

Function GetSheet(ObjExcelApp, sheetIdentifier) 'As Excel.worksheet

    On Error Resume Next
    Set GetSheet = ObjExcelApp.Worksheets.Item(sheetIdentifier)
    On Error GoTo 0
End Function

'The InsertNewWorksheet method inserts an new worksheet into the active workbook or

'the workbook identified by the workbookIdentifier, the new worksheet will get a default
'name if the sheetName parameter is empty, otherwise the sheet will have the sheetName
'as a name.
'Return - the new sheet as an Object
'ObjExcelApp - the excel application object into which the new worksheet should be added
'workbookIdentifier - an optional identifier of the worksheet into which the new worksheet should be added
'sheetName - the optional name of the new worksheet.

Function InsertNewWorksheet(ObjExcelApp, workbookIdentifier, sheetName) 'As Excel.worksheet

   Dim workbook 'As Excel.workbook
    Dim worksheet 'As Excel.worksheet
    'In case that the workbookIdentifier is empty we will work on the active workbook
    If workbookIdentifier = "" Then
    Set workbook = ObjExcelApp.ActiveWorkbook
    Else
    On Error Resume Next
    Err = 0
    Set workbook = ObjExcelApp.Workbooks(workbookIdentifier)
    If Err <> 0 Then
    Set InsertNewWorksheet = Nothing
    Err = 0
    Exit Function
    End If
    On Error GoTo 0
    End If
    sheetCount = workbook.Sheets.Count
    workbook.Sheets.Add , sheetCount
    Set worksheet = workbook.Sheets(sheetCount + 1)
    'In case that the sheetName is not empty set the new sheet's name to sheetName
    If sheetName <> "" Then
    worksheet.Name = sheetName
    End If
    Set InsertNewWorksheet = worksheet
End Function

'The RenameWorksheet method renames a worksheet's name

'ObjExcelApp - the excel application which is the worksheet's parent
'workbookIdentifier - the worksheet's parent workbook identifier
'worksheetIdentifier - the worksheet's identifier
'sheetName - the new name for the worksheet

Function RenameWorksheet(ObjExcelApp, workbookIdentifier, worksheetIdentifier, sheetName) 'As String

    Dim workbook 'As Excel.workbook
    Dim worksheet 'As Excel.worksheet
    On Error Resume Next
    Err = 0
    Set workbook = ObjExcelApp.Workbooks(workbookIdentifier)
    If Err <> 0 Then
    RenameWorksheet = "Bad Workbook Identifier"
    Err = 0
    Exit Function
    End If
    Set worksheet = workbook.Sheets(worksheetIdentifier)
    If Err <> 0 Then
    RenameWorksheet = "Bad Worksheet Identifier"
    Err = 0
    Exit Function
    End If
    worksheet.Name = sheetName
    RenameWorksheet = "OK"
End Function

'The RemoveWorksheet method removes a worksheet from a workbook

'ObjExcelApp - the excel application which is the worksheet's parent
'workbookIdentifier - the worksheet's parent workbook identifier
'worksheetIdentifier - the worksheet's identifier
Function RemoveWorksheet(ObjExcelApp, workbookIdentifier, worksheetIdentifier) 'As String

   Dim workbook 'As Excel.workbook
    Dim worksheet 'As Excel.worksheet
    On Error Resume Next
    Err = 0
    Set workbook = ObjExcelApp.Workbooks(workbookIdentifier)
    If Err <> 0 Then
    RemoveWorksheet = "Bad Workbook Identifier"
    Exit Function
    End If
    Set worksheet = workbook.Sheets(worksheetIdentifier)
    If Err <> 0 Then
    RemoveWorksheet = "Bad Worksheet Identifier"
    Exit Function
    End If
    worksheet.Delete
    RemoveWorksheet = "OK"
End Function

'The CreateNewWorkbook method creates a new workbook in the excel application

'ObjExcelApp - the Excel application to which an new Excel workbook will be added
Function CreateNewWorkbook(ObjExcelApp)
    Set NewWorkbook = ObjExcelApp.Workbooks.Add()
    Set CreateNewWorkbook = NewWorkbook
End Function

'The OpenWorkbook method opens a previously saved Excel workbook and adds it to the Application

'objExcelApp - the Excel Application the workbook will be added to
'path - the path of the workbook that will be opened
'return Nothing on failure
Function OpenWorkbook(ObjExcelApp, path)

    On Error Resume Next
    Set NewWorkbook = ObjExcelApp.Workbooks.Open(path)
    Set OpenWorkbook = NewWorkbook
    On Error GoTo 0
End Function

'The ActivateWorkbook method sets one of the workbooks in the application as Active workbook

'ObjExcelApp - the workbook's parent excel Application
'workbookIdentifier - the name or the number of the workbook
Sub ActivateWorkbook(ObjExcelApp, workbookIdentifier)
On Error Resume Next
ObjExcelApp.Workbooks(workbookIdentifier).Activate
On Error GoTo 0
End Sub

'The CloseWorkbook method closes an open workbook

'ObjExcelApp - the parent Excel application of the workbook
'workbookIdentifier - the name or the number of the workbook
Sub CloseWorkbook(ObjExcelApp, workbookIdentifier)
    On Error Resume Next
    ObjExcelApp.Workbooks(workbookIdentifier).Close
    On Error GoTo 0
End Sub

'The CompareSheets method compares between two sheets.

'if there is a difference between the two sheets then the value in the second sheet
'will be changed to red and contain the string:
'"Compare conflict - Value was 'Value2', Expected value is 'value2'"
'sheet1, sheet2 - the excel sheets to be compared
'startColumn - the column to start comparing in the two sheets
'numberOfColumns - the number of columns to be compared
'startRow - the row to start comparing in the two sheets
'numberOfRows - the number of rows to be compared
Function CompareSheets(sheet1, sheet2, startColumn, numberOfColumns, startRow, numberOfRows, trimed) 'As Boolean
   Dim returnVal 'As Boolean
   returnVal = True
    'In case that one of the sheets doesn't exists, don't continue the process
    If sheet1 Is Nothing Or sheet2 Is Nothing Then
    CompareSheets = False
    Exit Function
   End If
    'loop through the table and fill values into the two worksheets
   For r = startRow to (startRow + (numberOfRows - 1))
    For c = startColumn to (startColumn + (numberOfColumns - 1))
    Value1 = sheet1.Cells(r, c)
    Value2 = sheet2.Cells(r, c)
    'if 'trimed' equels True then used would like to ignore blank spaces
    If trimed Then
    Value1 = Trim(Value1)
    Value2 = Trim(Value2)
    End If
    'in case that the values of a cell are not equel in the two worksheets
    'create an indicator that the values are not equel and set return value
    'to False
    If Value1 <> Value2 Then
    Dim cell 'As Excel.Range
    sheet2.Cells(r, c) = "Compare conflict - Value was '" & Value2 & "', Expected value is '" & Value1 & "'."
    Set cell = sheet2.Cells(r, c)
    cell.Font.Color = vbRed
    returnVal = False
    End If
    Next
    Next
    CompareSheets = returnVal
End Function


For gaining more insights in the automation using QTP log on to below url :
Automation Testing Using QTP