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 automation testing. Show all posts
Showing posts with label automation testing. Show all posts

Multiple Iteration Data Driven Code Ui Testing

 How  to Data driving a Test project in Visual Studio Using Coded Ui Testing for multiple Couded Ui Class files for varying iterations:

For long this has been a debatable issue as to how we can unleash the data driving functionality in the Automation Testing that needs to be done in the Visual Studio tool using its Test project feature. We utilize the Coded Ui Test approach for functional automation testing to achieve the same. With initial hiccups always going to ramp down the confidence one can repose in a tool, I am sure that with experience and devoted mindset the same can be overcome and the great quality this tool has in it can be leveraged with slight knowledge of the usage of the hierarchy available therein.
We already have gone through the tool basics on how it does object recognition and how it undergoes the test effort automatically , but when it comes to take the data drving approach we might just encounter some hiccups as has been outlined by some of my colleagues in the IT industry with tons of mail shooting into my inbox on their inability to do the data driving for the test projects. The error they complain or more clinically speaking the shortcoming the tool has in it is that when we need to data drive the test file wherein separate Coded ui Class file has separate number of iterations to be undergone, the Coded Ui Test approach does not meet the expectation of the automation gurus in the IT sector !

How good that holds is for all of us to take a call on but as a matter of fact the approach that we try to adopt in data driving our test files need to be addressed first and that might just provide a necessary resolution of the problems that we encounter.

As has been provided at the  below link [ Mahe's mail ]http://www.articlesontesting.com/2011/07/issues-in-visual-studio-coded-ui.html the issue is simple . The Test project created by the user has in it three Coded Ui Test files  addressing three different business scenarios, and the business requirement that needs to be addressed is that the three different coded ui Test files need to iterate different number of times. The below description is definitely going to clear the cloud on this.
Three business scenarios are as under :
1.       One being the Login Scenario
2.       Second being the business requiremenmt such as doing some search event/transaction.
3.       Third being the Log Out Scenario.
The traditional approach we have been following is have a single data file with all data in it. The same can be adopted with this set of scenarios as well, but it definitely will involve some degree of coding and technical skills which we can avoid by transforming our approach to test the same.

Have one data sheet file in csv format for the Login Scenario.
Have one data sheet file in csv format for the search event.
Third scenario is definitely not dependent on data set up.

But one general issue that would be pondered upon is how to run all the three in unison .
This has a solution in the following approach . Just add an ordered test file by using the following link.
And then call them in the order the business requirement is. First Login Coded ui test file, then Search Coded uI test file and then finally log out Coded Ui test file.

The business runs smooth and also the effort and expertise you need to implement the same is very less .
That indeed is quite a good degree of ROI.

Issues in Visual Studio Coded ui Automation Testing

I received a mail from one of my colleagues in the automation testing arena who is using Coded Ui test project of the Visual Studio to automate some features. Below is the mail I recieved, and I shall be replying to the issues specified here itslef, so that the more audience can acquaint themselves with this issues in Coded Ui automation.


Mail :
Hi Viplav,
I am using VSTS2010 for automating a search functionality in my application. I recorded three coded UI test for-

a) Login- CodedUItest
b) Policy Search using some search criteria & then editing a policy selecting from search results- CodedUItest
c) Logout- CodedUItest


Thereafter I called login & logout functions from Search codedUITest.cs

I also have parameterized search criteria values (PolicyNumber, Policystatus etc) from  excel sheet (Used AppConfig for excel data connection).
I have 4 data rows in my input data sheet (to parameterize search criteria at the rum time).
Issue 1- Now what is Currently happening is- That my coded UITest runs , it does login, perform policy search and edit policy & then gets logout for each and every interation i.e for each data row, causing Opening of multiple browser instances.

My expectation :
            What I want to implement is just one login & one logout. So that- 
            a)users logins
            b)Perform search for all iterations, edit policy
            c)Go back to main page, Repeat steps a-c for all iterations
            d) then log out

Comments : A very geniuinely valid point raised by you Mahesh. Would definitely provide resolution to the same.


Issue2-  The second issue happening with all the iterations is that even after my script has executed for all data rows,It keeps on running and opening browser instances taking parametrized values as blank.
My expectation :
            Ideally it should stops once test is executed for all data rows, When it found no search criteria that is empty cells it should stop running.
            Here i need help, If we can implement some End of Row (EOR) in scripts, As soon as scripts finds EOR it should stop execution.
Comments : Would definitely provide its resolution.

Issue 3-
This issue is related to issue 3, as multiple browser instances are opening. I need some way to close them as soon as test completes for all iterations, better if they get closed after every iteration. I know we can use KILL IE function but I have to give control back to the interface where from I have invoked the scripts that is opened in IE browser. If I apply Kill IE function after all iterations are done, Interface brwoser gets closed as well.

Need you support in all this issues. Please guide.
I really appreciate any help in this regard.

Regards,
Mahendra.

Hi Mahendra,

I would be giving resolution to these three issues in the below comment chain one at a time. Do stay posted.

- Viplav Anand

The better approach is available here to address the business scenario handling :http://www.articlesontesting.com/2011/07/multiple-iteration-data-driven-code-ui.html

Code Customization In VSTS CodedUi Testing

How to do custom clicking in any particular checkbox in a web table based on specific field value within the one row in the complete table.

Before explaining or walking through the solution statement, I would prefer to explain to you the business scenario we often come across in our day to day automation testing experience during the course of functional testing automation.

Problem Statement:
We have a Table and within table a certain number of rows having certain number of columns. Suppose 5 rows and 3 columns. The first column has an html control in it of type Checkbox, Second column is having a particular field name, suppose product name in it and the third column is having the quantity of the item that has to be purchased. We have to check that particular row’s checkbox which has a particular product name in its product name column field.

Solution Approach:
We can break the problem statement into Five solution components –
1.  Fetch the row count in that particular table.
2.  Figure out the relation between the control id of the checkbox on the row number within the table.
3.  Fetch the row number in the table that has the corresponding Product name in the second column.
4.  Get the control id of the corresponding Checkbox generated based on Step 2 relationship establishment
5.  Set the checked status of the checkbox to True.

Before going through the codes below don ot forget to add the required objects by the below method by using the Add objects to the Ui Control map feature of the UITest Recording menu.


public void CodedUITestMethodCustomization()
{
// To generate code for this test, select "Generate Code for Coded UI Test" from the shortcut menu and select one of the menu items.

#region Variable Declaration
HtmlControl uiTable = this.UIMap.HierarchyWindow.HierarchyFrame.HierarchyTable;
HtmlCell uiTablecell = this.UIMap.HierarchyWindow.HierarchyFrame. HierarchyTable.uiTableCell;
string strProdTobDel= "Groceries";
string str1;
HtmlCheckBox chkbox = this.UIMap.HierarchyWindow.HierarchyFrame.uiTableCell CheckBox;
// To convert str1 into integer and then increment by one for checkbox recognition as inthis application the checkbox number is one more than the product control id‘s number
int intstr1;
string strCheckBoxId;
#endregion

#region  Get the rowcounts of the table
string RowCount = uiTable.GetProperty(HtmlTable.PropertyNames.RowCount).ToString();
MessageBox.Show(RowCount);
#endregion

#region Search for the Row and store in str1 having the Product to be deleted
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.Id);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.Name);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.MaxDepth);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.ControlDefinition);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.RowIndex);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.ColumnIndex);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.TagInstance);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.Class);
uiTableCell.SearchProperties.Remove(HtmlCell.PropertyNames.InnerText);
uiTableCell.SearchProperties[HtmlCell.PropertyNames.InnerText] = strProdTobDel;
str1 = uiTableCell.GetProperty(HtmlCell.PropertyNames.RowIndex).ToString();
MessageBox.Show(str1);
#endregion

#region Click Corresponding Checkbox To The User That Is Fetched From Datasheet
strCheckBoxId.SearchProperties.Remove(HtmlCheckBox.PropertyNames.Name);
strCheckBoxId.SearchProperties.Remove(HtmlCheckBox.PropertyNames.LabeledBy);
strCheckBoxId.SearchProperties.Remove(HtmlCheckBox.PropertyNames.Title);
strCheckBoxId.SearchProperties.Remove(HtmlCheckBox.PropertyNames.Class);
strCheckBoxId.SearchProperties.Remove(HtmlCheckBox.PropertyNames.ControlDefinition);
strCheckBoxId.SearchProperties.Remove(HtmlCheckBox.PropertyNames.TagInstance);
strCheckBoxId.SearchProperties.Remove(HtmlCheckBox.PropertyNames.Value);
           
// Increment str by one due to bad coding discipline and resulting mismatch in column and row increments
intstr1 = Convert.ToInt16(str1);
intstr1 = intstr1 + 1;
strCheckBoxId = "ctl00_ContentMain_grdCreateCustRepoUsersModerator_ctl0" + intstr1 + "_chkUser";
MessageBox.Show(strCheckBoxId);
strCheckBoxId.SearchProperties[HtmlCell.PropertyNames.Id] = strCheckBoxId;
strCheckBoxId.Checked = true;
#endregion

}

 
For more on Automation Testing using CodedUitesting in VSTS :Log On To
Automation Testing Using Coded Ui Testing In VSTS

Why VSTS For Automation Testing

Automation Testing ?
There has been a fast pace growth in the market capitalization of the VSTS tool for various Testing requirements at the various. It Service as well as Product based organisation. It has been not just the ability to market its products well by the Microsoft on this occasion but also the high quality packaged product that has been in the shipping container named as VSTS 2010 i:e Visual Studio 2010.

People for long in the IT industry has been using several stand alone tools for activities related to software development. In the fast paced environment that IT industry projects today, VSTS has definitely been an intelligent product and also the most competitive one.

Looking into the tools abilities we can keep exploring it for long long timelines, but some features that have made it a unique one is the Testing management at a   single platform that has been offered  in its integrated environment that brings all the various teams of Industrial development activities at one place and always in synch.

Primarily a current day Software Development comprises of three teams, namely Requirement Team, Development Team, and the Quality Assurance Team. In the old scenario we had all these three teams in a geographically separated environment as well as there was no tool to keep them in synch. This is the right tool that has been able to bring all of them together and the Dashboard feature provides the complete status automatically with various Project related metrics getting reflected.

Earlier versions of Visual studio had lots of features and we were definitely on the expectation that something had to be incorporated with the Testing features coming up in future releases. This is definitely  a well laid out feature with both the Manual as well as Automation Testing having been uniquely cared for on this occasion, VSTS will be able to bring all the three stakeholder groups on a synchronized platform of TFS with VSTS IDE being the client environment. 

Regarding the cost effectiveness we have just $25 tool in for the complete products requirement management to its development as well as testing on a single platform. We run no more the synch issues of multiple teams due to the TFS availability. We  no more need separate bunch of tools  such as QTP, QC, Excel to manage just the testing requirements. Now its all availed at just throwaway price of $25, and I guess you know what QTP, QC  is charged at. Automation Testing had never been that cheap!

Though we have shortcoming such as Add Ons unavailability but with slowly market getting acclimatized to this new low price tool, we are always going to benefit as business would flourish at the optimized cost now. So happy testing !!!

We can keep talking of the various integrated features but the best process is to explore the tool using its most advanced version The VSTS Ultimate.


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