Saturday, May 26, 2012

Sending email using QTP from Microsoft Outlook

In the previous article, we saw how to send emails from  QTP via Gmail & Yahoo Mail. There we wrote the code that connects to GMail/Yahoo SMTP Server and sends mails to any email id. But if you have MS Outlook installed in your machine, you can directly use Outlook to send emails to the required mail ids.  Also, the code to send mails from Outlook is relatively simpler than code for sending mails from Gmail/Yahoo using Microsoft CDO technology. Let’s see how the code works -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Function fnSendEmailFromOutlook
'Create an object of type Outlook
Set objOutlook = CreateObject("Outlook.Application")
Set myMail = objOutlook.CreateItem(0)
'Set the email properties
myMail.To = "some_mail_id@gmail.com"
myMail.CC = "some_mail_id_2@gmail.com; some_other_mail@yahoo.com" 'Sending mails to multiple ids
myMail.BCC = "" 'If BCC is not required, then this line can be omitted
myMail.Subject = "Sending mail from MS Outlook using QTP"
myMail.Body= "Test Mail Contents"
myMail.Attachments.Add("D:\Attachment.txt") 'Path of the file to be attached
'Send the mail
myMail.Send
Wait(3)
'Clear object reference
Set myMail = Nothing
Set objOutlook = Nothing
End Function

Sending emails using QTP from Gmail and Yahoo

This article shows how you can use QTP to send mails to any email address using email service providers such as GMail, Yahoo Mail etc. Automatically sending mails through QTP can be a very nice enhancement to your automation framework. For example, after you run your test scripts, you need to email test run reports (number of test scripts passed / failed etc) to the stakeholders. You can automate this mailing process and send custom reports to the required people.
Send Email from Gmail and Yahoo Mail
Send Email from Gmail and Yahoo Mail
Before going through the code, lets go through some important points regarding the code -
1. The below given email code is not directly related to QTP as such. The code is actually a VBScript function which you can use in QTP. So even if you don’t have QTP, you can use this VBScript code directly.
2. The email functionality uses Microsoft’s CDO (Collaboration Data Objects) technology to send mails. You can find more details about Microsoft CDO in Microsoft’s MSDN Library.
3. It is not necessary that you have to use this code using VBScript only. Microsoft CDO can be programmed using any language that creates COM object such as ASP, VB, Visual C++, C# etc.
4. The below code has been tested on Gmail and Yahoo mail. If you want to use this code in your company’s SMTP server, you need to contact your network team to get details about the SMTP address, port number etc.
5. To use this code, you don’t need to have Microsoft Outlook installed on your system. You can also use MS Outlook to send emails 

Let’s now see the code for sending emails using QTP (VBScript) through Gmail.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Function fnSendEmail()
 
'Create an object of CDO type
Set myMail=CreateObject("CDO.Message")
'Enable SSL Authentication
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True
'Enable basic smtp authentication
'Specify SMTP server and port
myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.gmail.com"
myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Specify user id and password
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "senders_id@gmail.com"
myMail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "**********"
'Update the configuration fields
myMail.Configuration.Fields.Update
 
'Specify email properties
myMail.Subject = "Sending Email from QTP"
myMail.From = "senders_id@gmail.com"
myMail.To = "some_mail_id_1@gmail.com"
myMail.CC = ""
myMail.BCC = ""
myMail.TextBody = "This is the Text Body"
'Send mail
myMail.Send
Set myMail = Nothing
 
End Function
Using the above code, you can send emails to any email id using your gmail address. Just specify your gmail user id and password in lines 14 & 15. Also mention the email id to which you want to send mails in lines 22, 23 and/or 24.

How to send mails from your Yahoo mail id

To send mails using your yahoo mail id, you need to replace the Gmail SMTP address and port number with Yahoo’s SMTP address and port number.
1
2
3
'Specify Yahoo SMTP server and Port Number
myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.mail.yahoo.com"
myMail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465

How to send mails to multiple people in one go.

To send mails to multiple email ids in one go, you need to just enter multiple mail ids separated by a semi colon(;). Example:
1
2
myMail.To = "some_mail_id_1@gmail.com; some_other_id@yahoo.com"
myMail.CC = "some_mail_id@someaddress.com"

How to send html content in the mail.

Normally you would not send plain text in emails. You would usually be sending some html content in mails. To do so, you need to use HTMLBody in place of TextBody and include html tags in your text body.
1
2
'myMail.TextBody = "This is the Text Body"  -> TextBody not to be used
myMail.HTMLBody = "<html><table border=1><tr>Row1</tr><tr>Row2</tr></table></html>"

How to send attachments using the email code.

To add an attachment in you mail, you need to include myMail.AddAttachment line in your code and specify the correct path of the file to be attached. To add more than one attachment, repeat myMail.AddAttachment code required number of times.
1
2
3
4
5
6
7
8
9
10
11
'Specify email mail properties
myMail.Subject = "Sending Attachment in Mail from QTP"
myMail.From = "some_id@gmail.com"
myMail.To = "some_other_id@gmail.com"
myMail.TextBody= "Mail Content"
'Send 2 attachments in the mail
myMail.AddAttachment "D:\Attachment1.txt"
myMail.AddAttachment "D:\Attachment2.txt"
 
myMail.Send
set myMail=nothing
Files Attached in Gmail

Wednesday, May 23, 2012

3 ways on How to Turn Off or Disable QTP Results

Consider a situation where you want to “turn off” or disable QTP Results (some part of the result or the entire result itself) that is generated at the end of the test run. There may be many reasons why you may want to do this, few of which have been listed at the end of the post. Let us see the 3 different ways by which you can disable/turn off QTP results.

3 Ways to Disable / Turn Off QTP Results

3 Ways to Disable / Turn Off QTP Results

1. Display only certain steps in the Test Run Results.
Using this method, you can control what all you want to display in the test run results. For example, you may want to display only the failed steps & not the passed ones. To do so, you would need to use the Filter Property of the Reporter Object. You can use any of the below mentioned values in the Reporter.Filter property -
Mode Description
0 or rfEnableAll Default. All reported events are displayed in the Run Results
1 or rfEnableErrorsAndWarnings Only event with a warning or fail status are displayed in the Run Results.
2 or rfEnableErrorsOnly Only events with a fail status are displayed in the Run Results.
3 or rfDisableAll No events are displayed in the Run Results.

Let us see an example on how this concept can be used -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Reporter.ReportEvent micPass, "Step 1", "Passed"
Reporter.ReportEvent micFail, "Step 2", "Failed"
 
'Disable all the Results
Reporter.Filter = rfDisableAll
Reporter.ReportEvent micPass, "Step 3", "Passed"
Reporter.ReportEvent micFail, "Step 4", "Failed"
 
'Enable Result Display
Reporter.Filter = rfEnableAll
Reporter.ReportEvent micWarning, "Step 5", "Warning"
 
'Enable only Errors and Warnings
Reporter.Filter = rfEnableErrorsAndWarnings
Reporter.ReportEvent micPass, "Step 6", "Passed"
Reporter.ReportEvent micFail, "Step 7", "Failed"
Reporter.ReportEvent micWarning, "Step 8", "Warning"
The test run result for the above code is shown in below figure. You can notice that Step 3 & Step 4 are not displayed in the result due to rfDisableAll, and Step 6 is not displayed due to rfEnableErrorsAndWarnings which displays only Errors and Warning messages in the Run Report.
Reporter.Filter property
Reporter.Filter property

2. Turn Off the display of Results at the end of test case run.
Here you would see how you can prevent the Run Results from getting displayed every time you run a test case. Let’s see the steps involved -
a. Go to Tools -> Options.
b. Select ‘Run’ node from the left hand side pane. Deselect the check box – ‘View results when run session ends’.
c. Click on ‘Apply’ and then ‘OK’ button.
View Results When Run Session Ends
View Results When Run Session Ends
Now when you run a test case, the run results would not appear at the end of the run session. Please note that this option just prevents the run results from getting displayed, but it doesn’t prevent the run results from being generated (and saved in your system).
3. Prevent the creation of Test Run Results. Using this method you can actually prevent the run results from being generated. Thus there is no way your test results will get displayed. To do so, you can follow the below steps -
a) Go to Start -> Run. Enter regedit in the text field and click on OK button to open the Registry Editor.
b) Navigate to HKEY_LOCAL_MACHINE \ SOFTWARE \ Mercury Interactive \ QuickTest Professional \ Logger \ Media \ Report node in the Registry Editor.
c) From the right hand side pane, double click on Active option and change the value from 1 to 0.
Turn Off QTP Results from Registry Editor
Turn Off QTP Results from Registry Editor
Since you have seen the 3 ways to disable QTP Results, you might be wondering as to why is there a need to turn off/disable the run results. Listed below are 3 scenarios where you might want to suppress QTP results.
Mode Scenario
Disable certain parts of the run result. Let us suppose that you are using GetCellData function on a table with a large number of rows. In this situation QTP Results will display one step for each GetCellData function call (which you might want to avoid)
Prevent QTP Results from appearing after a run session ends. There might be several cases where you would be running a small script multiple number of times for debugging purposes. In such situations, it becomes bit distracting & irritating to have the results screen displayed after every run.
Prevent QTP Results from being created. In some of your automation framework, you might want to go with custom reporting rather than the standard QTP reporting. In such cases it’s always better to prevent the creation of QTP results. This would definitely help you save some disk space.

Sunday, May 20, 2012

Passing Parameters between QTP tests stored in Quality Center

In our recent project we had a requirement of passing some captured values in one test to another test in sequence of execution during runtime. We needed a solution which took lesser time to be implemented and tested, while satisfying our need to integrate 02 test instances in the test lab of Quality Center without getting dependent on other external data sources/utilities such as flat files, excels and file system object.



  1. Create a Test with Test Input Parameters using Test Settings
http://farm7.static.flickr.com/6143/5955598728_2fb7fe89a0_b.jpg
  1. Create Action Input Parameters in desired Action using Action Properties
http://farm7.static.flickr.com/6128/5955038667_c5703a5a90_b.jpg
  1. Link Above created Action and Test Parameter Using Action Call Properties
http://farm7.static.flickr.com/6007/5955039561_71113d0531_b.jpg
It is mandatory for us to link Action and Test Parameters as shown above, so that we can access the test parameters in an Action like below
ValueofTestParam = Parameter("ActionParam1")
Then Save the test in Test Plan Module. Ensure that your QTP is connected to QC
  1. Create a Test Set and Drag test in Test Lab Module of Quality Center Using Select Tests Tab
Now the Dragged instance of our test should be capable of recieving values from any other code/test. Have a look at the properties [3] of the dragged instance.
http://farm7.static.flickr.com/6150/5955039317_bf50e2474b_b.jpg
  1. Code in a common library
  1. Access Test Instance and its properties using OTA API
'Code to access the next test instance in Execution Flow
'Not a very clean code, please take care of declarations

Set TDC = QCUtil.QCConnection
set TSfact = TDC.TestSetFactory
Set TreeManager = TDC.TestSetTreeManager
Set tsFolder = TreeManager.NodebyPath("Root\Pathto\YourTestSetFolder")
Set TestSetList = tsFolder.FindTestSets("YourTestSetName")
Set theTestSet = TestSetList(1)
set TSTestFact = theTestSet.TSTestFactory
Set TestSetTestsList = TSTestFact.NewList("")

' You can take the other values as required in your framework
Inst = 1
TestName = "GettingParamTest"
InstanceName = "[" & Inst &"]" & TestName

For Each myinstance in TestSetTestsList

If Ucase(Trim(myinstance.Name)) = Ucase(Trim(InstanceName)) Then
        'I have got my instance
        Set MyTestInstance = myinstance
End If
  1. Study the xml format of automaion parameters stored in Quality Center
ExecutionParams property of a test instance has following xml representation
http://farm7.static.flickr.com/6147/5955039015_bd153103ac_b.jpg

<?xml version="1.0"?>
<Parameters>
        <Parameter>
                <Name><![CDATA[TestParam1]]></Name>
                <Value><![CDATA[ParamValue1]]></Value>
                <Name><![CDATA[TestParam2]]></Name>
                <Value><![CDATA[ParamValue2]]></Value>
        </Parameter>
</Parameters> 
  1. Plan modification of test instance parameters' values during runtime
ExecutionParams property of testinstance object returns a string(which is above mentioned xml )and the property is writable too.
NewParamsAndValues = Array("TestParam1>NewParamValue1","TestParam2>NewParamValue2")
OriginalParams = MyTestInstance.ExecutionParams

ModifiedParams = GetModifiedParams(OriginalParams,NewParamsAndValues)
' I am not writing the function GetModifiedParams in the example| You can write
' your own logic of manipulating the strings and values

MyTestInstance.ExecutionParams = ModifiedParams

print MyTestInstance.ExecutionParams
  1. How modified values will persist ?
Once you print MyTestInstance.ExecutionParams it will show the modified values for the test parameters, but these values do not persist. And these modified values need to persist for the next test instance to pick up in execution flow, Therefore We need to use post and refresh method ofMyTestInstance object.
MyTestInstance.Post()
MyTestInstance.Refresh()

Run Action Statement In QTP


Runs the specified action in the test.

Note: The RunAction statement can run only actions that are already associated with your test as part of the test flow. Therefore, in order to enter a RunAction statement in the Expert View for an external action, you must first insert a call to the action (Insert >Call to Action) or copy the external action (Insert > Copy of Action) into your test. Using this option associates the action with the test and also inserts a RunAction statement for you. After the the external action is added to the test flow, you can add additional calls to that external action in the Expert View.

If you insert a RunAction statement in the Expert View for an external action that is not already associated with your test as a part of the test flow, the RunAction statement fails. For more information on copying or calling external actions, see the HP QuickTest Professional User Guide.

Syntax

RunAction ActionName, [Iteration , Parameters]


Argument

Type

Description

ActionName

String

The name of the action.

Iteration

Variant

Optional.

-- oneIteration or 0 (Default)—Runs the action only once, using the row in the action's data sheet that corresponds to the global data sheet iteration counter.

If the action's data sheet contains fewer rows than the global sheet, the last row of the action's data sheet will be used for each subsequent iteration.

-- allIterations or 1—Runs iterations on all rows.

-- iteration row range (for example, "1-7")—Indicates the rows for which action iterations will be performed

Note: Iteration is required when calling an external action, but optional when calling a local action (from within the test).

Parameters

Variant

Optional.

The values and storage locations for the called action's input and output parameters. Input parameters are listed before output parameters.

For an input parameter, specify either a fixed value or the name of another defined parameter (Data Table parameter, environment parameter, or an action input parameter of the calling action) from which the argument should take its value.

For an output parameter, specify either a variable in which you want to store the value or the name of a defined parameter (Data Table parameter, environment parameter, or an action output parameter of the calling action).

Return Value

Variant.

If the action called by the RunAction statement includes an ExitAction statement, the RunAction statement can return the value of the ExitAction's RetVal argument. For more information, see ExitAction Statement.

Examples

The following example calls the SearchFlight action, and runs all iterations of the action.

RunAction "SearchFlight", allIterations

The following example performs the same call as the previous example, but runs only one iteration of the action and saves the returned value to the AxnVal variable.

AxnVal=RunAction ("SearchFlight", oneIteration)

The following example runs one iteration of the action, supplies a string value of MyValue for the input parameter, and stores the resulting value of the output parameter in a variable called MyVariable.

RunAction "Action2", oneIteration, "MyValue", MyVariable

Thursday, May 17, 2012

Functional and Structural testing

Functional testing (also known as black-box testing), is a software testing approach in which:
1. the tester will have a user perspective in mind,
2. not knowing and doesn't mind how the program works.
3. Input and output are the only things that matter.
4. The tester acts as if he/she is the final user of the program.

On the other hand, Structural testing (also known as white-box testing), is a software testing approach in which:
1. the tester will have a developer perspective in mind,
2. knowing how the program works behind the scene,
3. such that the test will test all algorithm paths in the program.
4. Everything does matter.
5. The tester acts as a developer of the program who knows the internal structure of the program very well.

Sunday, May 13, 2012

Difference Between Test And Action Parameters


Many QTP user confuse between Test and Action Parameters. This article will explains both the concepts in details and eliminate any confusion. QTP Help does not describe the method of using Test Parameters

Test Parameters

Test Parameters can be used to pass values to the test and retrieve values when the test completes. They are global parameters and can be accessed in any action or rather any scope. They are of two type – Input and output. Input Parameters are used to pass values to the test while Output Parameters are used to retrieve values from the Test.
Adding the Test Parameters
Test parameters can be added in the File->Settings…->Parameters (Tab) as shown in the image below
Adding Test Parameters
Adding Test Parameters
Note: Parameter names are case sensitive. Once added a parameter’s order can’t be changed, changes can only be done by deleting and re-creating the parameters.
Accessing Test Parameters
This is nowhere documented in the QTP Help file, but we can use Test Parameters using the TestArgs object. The code below shows how to access a parameter named ‘InputDataTable’
inputDataTable = TestArgs("InputDataTable")
Note: Many times Test Parameters are confused with Action Parameters and one tries to access the value using the Parameter object, which generates a ‘Parameter not found’ error.
Passing the Test Parameters
Test Parameters can be passed in three different ways
  1. Through the ‘Input Parameters’ tab of the Run window as shown in the image below
    Passing parameters through Input Parameters tab of Run window
    Passing parameters through Input Parameters tab of Run window

  2. Through QTP Automation Object Model (AOM) – We can also pass values of input parameters using the QTP AOM. The code needs to be run in a program external to QTP, ex – VBScript. The code shown below demonstrates the passing of test parameters
    'Launch QTP
    Set qtApp = CreateObject("QuickTest.Application")
    qtApp.Launch
    qtApp.Visible = True
     
    'Open a test
    qtApp.Open "C:\TestInputParams"
     
    ' Retrieve the parameters collection defined for the test.
    Set oParams = qtApp.Test.ParameterDefinitions.GetParameters()
     
    oParams.Item("InputDataFile").Value = "C:\NewTestData.xls"
     
    ' Run the test with changed parameters.
    qtApp.Test.Run , True, oParams
  3. Through Quality Center (QC) – We can also pass the parameters through. This option is only available when the test is added to a TestSet in TestLab

Action Parameters

Action Parameters can be used to pass or retrieve values to or from an Action.
Adding Action Parameters
Action parameters can be added in the Parameters tab of Action properties as shown in the image below
Adding Action Parameters
Adding Action Parameters
Accessing Action Parameters
Action Parameters can be accessed using the Parameter object. The code below demonstrates how to access a Input parameter named ‘InputValue’
sInputValue = Parameter("InputValue")
Note: Input parameters are NOT read-only and their value can be changed at run-time within the Action.
Action Parameters can only be accessed inside the Action they belong to.
Passing the Action Parameters
Action parameter can be passed in the RunAction call. All Input Parameters are passed first and then all the Output Parameters. Input Parameters can be passed as Constant Values or Variables. Example
RunAction "ActionParams", oneIteration, "C:\Test"
sInputValue = "C:\Test"
RunAction "ActionParams", oneIteration, sInputValue
Output Parameters need to retrieved through variables only. Output Parameters can be ignored by skipping the parameter in RunAction. Example – If a Action takes two parameters one Input and Output, we can call the Action in various ways as shown in code below
'Ignoring the Output Parameters
RunAction "ActionParams", oneIteration, "C:\Test"
sInputValue = "C:\Test"
RunAction "ActionParams", oneIteration, sInputValue
 
'Retrieving the Output Parameter
Dim sOutputValue
RunAction "ActionParams", oneIteration, sInputValue, sOutputValue
RunAction "ActionParams", oneIteration, "C:\Test", sOutputValue
Note: While calling an Action for all of it’s iterations, Output Parameters values can’t be captured. This happens because one call to the RunAction can run the Action for all of it’s iteration. Hence, on every iteration the Output Parameters value will be overwritten.

VBScript UBound Function


The UBound function returns the largest subscript for the indicated dimension of an array.
Tip: Use the UBound function with the LBound function to determine the size of an array.

Syntax

UBound(arrayname[,dimension])

ParameterDescription
arraynameRequired. The name of the array variable
dimensionOptional. Which dimension's upper bound to return. 1 = first dimension, 2 = second dimension, and so on. Default is 1

Examples

Example 1

The output of the code above will be:
0
6

Example 2

A two dimensional array:
The output of the code above will be:
0
2
0
3