The TDConnection Object - QTP

TDConnection is the top level object in the model. This object is required to connect to the QC server and works with any project. In QTP we obtain a reference to this object using the following statement:

'Get the TDConnection OTA object reference
Set TDConnection = QCUtil.TDConnection

But if we are not connected to QC then the above statement won't work and returns 'Nothing'. There are two ways to connect to QC through QTP, one of them is to connect through the QTP UI which has already been discusses earlier. The second method is to connect using the QTP Automation Object Model (AOM), which is shown using the following code:

"Get the QTP AOM Application object
Set qtpApp = CreateObject("QuickTest,Application")
'Launch the App qtpApp.
Launch
qtpApp.Visible = True
Set oQCConnection = qtpApp.TDConnection
sServerURL = "http://qcserver"
sDOMAIN = "DEFAULT"
sProjectName ="QualityCenter _Demo"
sUser ="username"
sPassword = "password"
'Check if we are already connected to QC
If oQCConnection.IsConnectedThen
"Check if the connection parameters are same with the
'the project which want to connect to
If oQCConnection.ServerosServerURLOr _
oQCConnection.Project<>sProjectNameOr _
oQCConnection.User<>sUser Then
'Disconnect from the project, we would like to reconnect
oQCConnection.Disconnect
End If
End If
'Connect only if we are not connected to QC
A If Not oQCConnection.IsConnected Then
'Sub Connect(ServerURL As String, DomainName As String,
'ProjectNameAs String, UserNarae As String, Password As String,
'EncryptedPWAs Boolean)
oQCConnection.ConnectsServerURL, sDOMAIN,sProjectName,sUser , sPassword, False
End If

'Get the TDConnection OTA Object reference
Set TDConnection = oQCConnection.TDOTA

The code given above first determines if we are already connected to the desired project and if not then it performs the required connection. If we don't want to use a plain text password then we can use the QTP Password Encoder tool located in the QTP programs folder menu. The code lines that would be changed are as follows:

'Encrypted password
sPassword = "46cSc47fc7c4cdc8b31096868@abb26396?el4bSf4d0"
'Connect using the encrypted password
oQCConnection.ConnectsServerURL, sDOMAIN,sProjectName,sUser ,sPassword, True

The method given above uses QTP AOM to get a TDConnection object reference, but it is also possible to create the object using the CreateObject function as follows:

'Create the TDConnection object using OTA COM object
Set TDConnection = CreateObject("TDAPIOleS0. TDConnection")
'Connection details
sServerURL = "http: //qcserver"
sDOMAIN = "DEFAULT"
sProjectName = "QualityCenter-Deato"
sUser = "usernane"
sPassword = "password"
'Connect to the Sever
TDConnection.InitConnectionExsServerURL
'Connect to the give project
TDConnection.ConnectProjectExsDOMAIN, sProjectName, sUser, sPassword
'Check the connection status
MsgBoxTDConnection,Connected
'Disconnect from the project
TDConnection.DisconnectPioject
'Release the connection to the server TDConnection.
ReleaseConnection

The Command and Recordset Objects

The Command and Recordset objects allow us to get data directly from the QC project's database. Details about the QC database tables are out of scope for this book but we will show how to make a simple query and process the results. The following code shows how to get the Design Steps (i.e. Manual Steps) present in test plan for the current test:

'Get the TD OTA object reference
Set TDConnection = QCUTil.TDConnection
'Get the ID of the current test in the Data base TestID = QCutil.
CurrentTest.Field ("TS„TEST„ID")
'Get all the design steps present in the Test and
'read the Step Description and Expected Text
Set TDCommand = TDConnection.CommandTDCommand.CommandText = _
"Select OS-DESCRIPTION, DS_EXPECTED Froa DESSTEPS

whereDS_.TEST_.ID = " &TestID
'Execute the query
Set TDRes = TDCommand.Execute
'Loop throuh all the results in the recordsetWhile Not TDRes.EOR
MsgboxTDRes.FieldValue("DSJJESCRIPTION")
MsgboxTDRes. FieldValue(,,DS_EXPECTED'™)
'Move to the next row of the results TDRes.Next Wend
We can use the above technique to pass parameters to the script using the design steps in an automated script. Note that in the example given above the description and expected value returned from the database is in HTML format. We can use the following function to convert the HTML to plain text:
'Function to convert HTML type text to plain text Public Function ConvertHTML2PlainText(ByValHTMLText)
Dim oHTML
'Create a HTML document object
Set oHTML = CreateObjectC'htmlfile")
oHTML.Clear
'Write the HTML on to the document
oHTML.writeHTMLText
'Get the outerlext of the whole document
ConvertHTML2PlainText = oHTML.
documentElement.outerText Set oHTML = Nothing
End Function

TheAttachmentFactory Collection

Attachments present in an object can be accessed through the AttachmentFactory collection. The Object can be one of the following:

  • Requirements Tab - Any requirement can have attachments
  • Test Plan Tab - Folder, Test in the folders and Design steps inside the tests can have attachments
  • Test Lab Tab -- Folder, TestSet, Test in the TestSet, TestRun of a Test, TestStep inside a TestRun can have attachments
  • Defects - A defect can also have attachments

Downloading and uploading attachments to one of these objects is done in a similar manner. But before we can download an attachment we need to locate a specific attachment in the collection. The following function shows how to find an attachment inside a selected object. The function returns an array of attachment objects which match the specified file name criterion:

'This function allows to find an attachment from a QC Object
'FromPlace is the object from where the attachments need to checked
Public Function FindAttachment(ByValFromPlace,ByValFileName)
Set FindAttachment = Nothing
'Get Attachments (AttachmentFactory)
Set oAttachments = FromPlace.Attachments
'Get a collection of all attachments present
Set allAttachment = oAttachments.NewList("")
. V 'Array to retun the files found Dim filesFound:
ReDimfilesFound(0)
'Object to match regular expresison in ffle names Dim regEx:
Set regEx = New RegExpregEx.IgnoreCase = True
'If there is a * present in the file name then treat it as regular expression "
.txt will be invalid r.e. in VBScript. So convert to .".txt If InStr(FileName, "#") Then
'It's regular expression
regEx.Pattern = Replace(FileName,"•",".•")
Else
'Treat it as a complete file name by appending " at start and $ at end
regEx.Pattern = """& Replace(FileName, ". "", "V. ") &""$""
End if
'Enumerate through all the attachments

For Each oAttachment In allAttachment'Does the actual file name match with the search criteria 'To get the actual file name we use thaparamter with name as 1 If regEx.Test(oAttachment.Name(l)) Then

'Add the attachment object to the array
Set filesFound(UBound(filesFound))= oAttachment
ReDim Preserve filesFound(UBound(filesFound)+l)
End if
Next
'We create an extra element in the array for the last attachment. Removed
'the extra element
ReDim Preserve filesFound(UBound(filesFound)-l)
'Retrun the array of attachment objects FindAttachment = filesFound
End Function

The function uses the NewList function to get the collection from an AttachmentsObject and then parses all attachments to get an array matching the file. Use the following function to download specific attachments:
'Function to download attachments from a QCObject

'to a specified folder
Public Function DownloadAttachments(ByValFromPlace, ByValTOPlace, ByVal
fileName)
'function returns the # of attachments downloaded
DownloadAttachments = 0
'If there is no at the end of the folder path then add one If Right(TOPlace,1)<>"" Then
TOPlace = TOPlace& ""
End If
'Find the attachment using the FindAttachment function
Dim oFindAttachments
oFindAttachments = FindAttachment(FromPlace, fileName)
Set FSO = CreateObject("Scripting.FileSystemObjeet") Dim i
For i = LBound(oFindAttachments) to UBound(oFindAttachments) 'Load the attachment to local drive oFindAttachments(i).Load True,""
"Copy the file from temporary downloaded location to the TOPlace folder FSO. CopyFileoFindAttachments(i).FileName, _
TOPlace&oFindAttachments(i).Name(l).True
'Increment no. of files downloaded DownloadAttachments= DownloadAttachments + 1 Next
End Function

We can use the above function in QTP as:

'Download all the VBS file attached to current test
'in the test plan tab
DownloadAttachmentsQCUtil.CurrentTest, "C:Doiinload", "*.vbs"
'Download all the VBS file starting with name as override from the
'current test set in which the test is present (test lab tab)
DownloadAttachmentsQCUtil.CurrentTestSet, "C:XDownload", "Override*.vbs"
'Download TestData.xls from the current test (in the test lab tab)
DownloadAttachmentsQCUtil.CurrentTestSetTest, "G Do»nload", "TestData.xls"

Simple way of Downloading files from QC

Downloading files from QC in QTP is not very complex. According to the QTP help, the PathFinder. Locate method returns the full file path that QTP uses for the specified relative path (resolves the path) based on the folders specified in the Folders tab search list (Tools > Options > Folders tab) of the Options dialog box Consider the paths present in the folders tab :

<CurrentTest>
[QualityCenter ] SubjectAll TestXCommon

Assume we have a common.vbs file in the QC path's common folder and we execute the following code:

'Locate the common.vbs from current folders path
sFilePath = PathFinder .Locate ("coMon. vbs") MsgboxsFilePath
We would intuitively expect the path to be "[QualityCenter]
SubjecfvAll TestCommonCommon. vbs".

But after running the code we will find that the MsgBox statement displays something like this:

'C:DOCUME^rfanmLOCALS-lTempTDJ0de8007c^AttachQTProULLJJSrS_730_Common, vbs"

So, what happened in here? PathFinder.Locate does something which is not documented in the QTP help. In case a file is located inside QC then QTP downloads the file to a temporary location and returns that path. But what happens if we have to download a file located in the "[QualityCenter] SubjectAll Test" folder or some other folder? If we use the file's complete path it too will be downloaded:

'Locate the common.vbs from current folders path
sFilePath = PathFinder.Locate (" [QualityCenterlSubjectXAllTestnurabers.jpg")
MsgboxsFilePath

Uploading Attachments to QC

The following function can be used to upload attachments to QC using the AttachmentFactory object:

'Function to Add an attachment to a specified object
Public Function AddAttachment(ByvalTOPlace.
ByValFileName.ByVal
overwriteExisting)
Set AddAttachment = NOthing
Dim oFindAttachment
'Get attachments (AttachmentFactory)
Set Attachments = TOPlace.Attachments
sFileName = GetLastNodeFromPath(FileName)
'Find if any attachment with that name already exists
oFindAttachment = FindAttachment(TOPlace, sFileName)
'If the attachment already exists and we are supposed to overwirtethe attachementthen
'remove the attachment first
If UBound(oFindAttachment) >= 0 and overwriteExisting Then
oAttachments.RemoveltemoFindAttachment(0)
End If
'Now just upload the new one
Set oNewAttachment = oAttachments.Addltem(Null)
oNewAttachment.FileName = FileName
oNewAttachment.Type= 1 'TDATT_FILE oNewAttachment.Post
'Return the new attachment
Set AddAttachment = oNewAttachmentEnd Function
'This function returns the last node text from a path
'For Ex - Last node in C:TestTestlTest2.txt is Test2.txt
Public Function GetLastNodeFromPath(Byval Path)
If Right(Path,1) = "" Then Path = Left(Path, Len(Path) - 1)
LastSlashlndex = InStrRev(Path, "V") If LastSlashlndexThen
GetLastNodeFromPath = Mid(Path, LastSlashlndex + 1)
Else
GetLastNodeFromPath = Path
End If
End Function

When files are uploaded to QC and the file name already exists in the attachments then QC appends a number to the file. To avoid this behavior we need to first remove the old attachment and then upload the new one. To achieve this, set the overwriteExisting flag to True when using the AddAttachmentfunction:

'Upload an attachment to the current test
AddAttachmentQCUtil.CurrentTest, "CsTestFile.txt"", False
'The below will create Filel.txt
AddAttachmentQCUtil.CurrentTest, "C:TestFile.txt", False
'This sill delete old File.txt and uploade the new copy
AddAttachmentQCUtil.CurrentTest, "C:TestFile.txt", True


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

QTP Topics