Search This Blog

Wednesday, December 8, 2010

Functionality:- Code for Finding and replacing the word/phase in QC test cases in Test plan.

This script helps us in finding and replacing all occurrences of a word/phrase with the given word/phrase in Quality Center test cases in Test Plan (Description and Expected Result fields of Design Steps, to be precise)

Script needs the following inputs:
1.       QC Server name (URL), Domain, Project, Username and Password
2.       Test case name or Test case folder name
3.       Search Item (word/phrase)
4.       Replace Item (word/phrase)

#######################################################################3
'==============================================
' Utility name: Find and Replace
'==============================================


' Get the QC Connection parameters from the user
 Set oShell = CreateObject( "WScript.Shell" )
 user = oShell.ExpandEnvironmentStrings("%UserName%")


 userName = InputBox("Enter the username", "Quality Center Username", user)
 userPassword = InputBox("Enter the password", "Quality Center Password")
 qcDomain = InputBox("Enter the domain", "Quality Center Domain", "WQA")
 qcProject = InputBox("Enter the project", "Quality Center Project", "FSDD_SDD")

' Establish the connection
 Set QCConnection = CreateObject("TDApiOle80.TDConnection")
 QCConnection.InitConnectionEx "http://wcpappa018609/qcbin"

 QCConnection.login userName, userPassword
 QCConnection.Connect qcDomain, qcProject


' Testcase and QC Path variables
 Dim tcName
 Dim qcPath
 
 qcPath = InputBox("Enter the absolute QC folder path", "QC Folder Path", "Subject\WAVES\Jan 2009 Reqs\1. Add Bank Draw Number")
 tcName = InputBox("Enter the testcase name: (leave blank for all testcases)", "Testcase Name", "1.2 Add Bank Draw Number")

' Search and replace variables
 Dim searchItem ' Search Sting
 Dim repItem ' Replace string

 searchItem = InputBox("Enter the search item", "Search Item")
 repItem = InputBox("Enter the replace item", "Replace Item")

' Initialize the QC connection variables
 Set tFact = QCConnection.TestFactory
 Set tFilter = tFact.Filter

 tFilter.Filter("TS_SUBJECT") = """" & qcPath & """" ' Find the QC Path
 ' tFilter.Filter("TS_NAME") = ""

' Find the testcase(s) in the given path
 If IsEmpty(tcName) = False Then
  tFilter.Filter("TS_NAME") = """" & tcName & """"
 End If

' Execute the filter
 Set tList = tFact.NewList(tFilter.Text)
 
' Create the log file setup
 Set oFSO = CreateObject("Scripting.FileSystemObject")
 Set oLogFile = oFSO.CreateTextFile("UpdateActualResult.log", True)


' Navigate through all the testcases that matched the search criteria (usually just one testcase)
 For i = 1 to tList.Count 
  
  Set myTest = tList.Item(i)
  
  oLogFile.WriteLine vbCrLf & "Log for test case: " & myTest.name

  ' Check whether Version Control is enabled for the test
  On Error Resume Next
  Set objVCS = myTest.VCS
  On Error Goto 0
 
  If IsObject(objVCS) Then
   ' Check out the test, if it not already checked out
   If objVCS.IsLocked = False Then
    objVCS.CheckOut "", "", True

   ' Verify if the test is checked out by other user - if Yes, exit test, if No, check out the test
   ElseIf objVCS.IsLocked AND userName <> objVCS.LockedBY Then
    oLogFile.WriteLine "WARNING: " & myTest.name & " is locked by: " & objVCS.LockedBy
    ExitTest
   End If
  End If

  Set dFact = myTest.DesignStepFactory
  Set dStepsList = dFact.NewList("")
 
  ' Navigate through all the teststeps and do the replacements
  Set oRegEx = New RegExp
  oRegEx.Pattern = searchItem
 
  For Each item in dStepsList
   ' Replace in the Step Description & Expected Result
   newStepDesc = oRegEx.Replace(item.StepDescription, repItem)
   newExpResult = oRegEx.Replace(item.StepExpectedResult, repItem)
 
   ' Print the log
   If newStepDesc <> item.StepDescription OR newExpResult <> item.StepExpectedResult Then
    oLogFile.WriteLine vbTab & "Replacement in Testcase " & myTest.Name & " step number - " & item.Order + 1
    item.StepDescription = newStepDesc
    item.StepExpectedResult = newExpResult
 
    item.Post
   End If
  Next

 ' Clear off the variables
 Set dStepsList = Nothing
 Set dFact = Nothing

 ' Check whether test is VCS enabled - if Yes, then check-in the script, if NO, just unlock the test
 If IsObject(objVCS) Then 
  objVCS.CheckIn "", ""
 End If

 ' Unlock the test
 If myTest.IsLocked Then
  myTest.UnLockObject
 End If
Next

' Clear off the variables
 Set tList = Nothing
 Set tFilter = Nothing
 Set tFact = Nothing

' Disconnect from QC
 QCConnection.Disconnect
 QCConnection.Logout
 QCConnection.ReleaseConnection
 
 
' End the script
 MsgBox "All the replacements have been done!  Press Refresh to see the results."

####################################################################################

Functionality:- Code for - To download file from QC from specified source folder to destination folder.

Input Parameter:
1.     File Name
2.     Source Folder
3.     Destination Folder

#################################################################################
Example:

File_Name = "Test Data.xls"
Folder_Name = "Subject\Automation-Regression\Test Data"
' Specify Destination folder path
Dest_Folder = "C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\"

PassFailFlag = DownloadFileFromQC(Folder_Name,File_Name,Dest_Folder)


***********************************************************************************************************************************
***********************************************************************************************************************************

Public Function DownloadFileFromQC(Folder_Name,File_Name,Dest_Folder)
                FilePath = GetAttachmentFromFolder(Folder_Name, File_Name, Dest_Folder)
               If FilePath <> "" Then             
                                                ' Step 2: Delete the file if it already exists
                                                Set objFSO = CreateObject("Scripting.FileSystemObject")
                                                If objFSO.FileExists(Dest_Folder & File_Name) Then
                                                                        objFSO.DeleteFile(Dest_Folder & File_Name)
                                                End If
                                                'Step 3: Rename the file
                                                objFSO.MoveFile FilePath , Dest_Folder & File_Name
                                                PassFailFlag = 0
                        ElseIf FilePath = "" Then
                                     PassFailFlag = 1     
                        End If
                        DownloadFileFromQC = PassFailFlag
End Function

' Get an attachment from Folder
Public Function GetAttachmentFromFolder(FolderName, FileName, OutPath)
                        Set TDConnection = QCUtil.TDConnection
                        Set treeManager =  TDConnection.TreeManager
                        Set node = treeManager.nodebypath(FolderName) 
                        GetAttachmentFromFolder = GetAttachmentFromTestObject(node, FileName, OutPath)
End Function

'Get an attachment from Test Object
Public Function GetAttachmentFromTestObject (TestObject, FileName, OutPath)
                        MyPath = GetAttachmentServerPath(TestObject, FileName, LongFileName)
                        If StrComp(MyPath, "") = 0 Then
                                                GetAttachment = ""
                                                Reporter.ReportEvent  Fail, "Specified file '"& File_Name &"' does not exsit in 'QC\ Test Plan\ Subject\ Automation-Regression\ Test Data' folder.",""
                                                PassFailFlag = 1
                                                Exit Function
                        End If
                        If Right(OutPath, 1) <> "\" Then
                                                OutPath = OutPath & "\"
                        End If
                        ' Load the attachment using the extended storage object
                        Set TDConnection = QCUtil.TDConnection
                        Set ExtendedStorage = TDConnection.ExtendedStorage
                        ExtendedStorage.ServerPath = MyPath
                        ExtendedStorage.ClientPath = OutPath
                        ExtendedStorage.Load LongFileName, True
                        GetAttachmentFromTestObject = OutPath & LongFileName
                        Reporter.ReportEvent 0, "File '"& File_Name &"' downloaded into '"& Dest_Folder & "' folder.",""
                        PassFailFlag = 0
End Function

'Get an attachment Server Path
Public Function GetAttachmentServerPath (Object, FileName, LongFileName)
                        Set AttachmentFactory = Object.Attachments
                        Set AttachmentList = AttachmentFactory.NewList("")
                        For Each Attachment in AttachmentList
                        If StrComp(Attachment.Name(1), FileName, 1) = False Then ' Equal
                                                LongFileName = Attachment.Name                                
                                                Pos = Instr(1, Attachment.ServerFileName, Attachment.Name, 1)
                                                GetAttachmentServerPath = Left(Attachment.ServerFileName, Pos - 1)
                                                Exit Function
                        End If
                        Next
                        GetAttachmentServerPath = ""
End Function

***********************************************************************************************************************************
***********************************************************************************************************************************

Functionality: Code for changing the format of the date to a requested format.

This function Changes the format of the date to a requested format. It will change the given date into following format:
1). "mm/dd/yy"
2). "mm/dd/yyyy"
3). “weekday,Month day,year"
4). "yy/mm/dd"
            5). “dd/mm/yy

______________________________________________________________________________________

'Example : Format_Date "01/26/1992",1

'frmtType = 1 for "mm/dd/yy"
'frmtType = 2 for "mm/dd/yyyy"
'frmtType = 3 for "weekday,Month day,year"
'frmtType = 4 for "yy/mm/dd"
'frmtType = 5 for "dd/mm/yy"

'*******************************************************************************************************************
'*******************************************************************************************************************


Function Format_Date(aDate,frmtType)
            Dim Curr_Day,Curr_Mon,Curr_Year,To_Date
    Curr_Day = datepart("d", aDate)
            Curr_Mon = datepart("m", aDate)
            Curr_Year = datepart("yyyy", aDate)
            If frmtType=1 then

                        Curr_Year = Right(Curr_year,2)

                        If Len(Curr_Day) = 1 Then
                                    Curr_Day = "0" & Curr_Day
                        End If
                        If Len(Curr_Mon) = 1 Then
                                    Curr_Mon = "0" & Curr_Mon
                        End If
                                   
                        To_Date = Curr_Mon & "/" & Curr_Day & "/" & Curr_Year
                        Format_Date = To_Date
            End If
            If frmtType = 2 Then
                       
                        If Len(Curr_Day) = 1 Then
                        Curr_Day = "0" & Curr_Day
                        End If
                        If Len(Curr_Mon) = 1 Then
                                    Curr_Mon = "0" & Curr_Mon
                        End If
           
                        To_Date = Curr_Mon & "/" & Curr_Day & "/" & Curr_Year
                        Format_Date = To_Date
            End If
            If frmtType= 3 Then

                        To_Date = Formatdatetime(aDate,1)
                        Format_Date = To_Date
            End If

            If frmtType = 4 Then

                        Curr_Year = Right(Curr_year,2)

                        If Len(Curr_Day) = 1 Then
                                    Curr_Day = "0" & Curr_Day
                        End If
                        If Len(Curr_Mon) = 1 Then
                                    Curr_Mon = "0" & Curr_Mon
                                               
                        End If
                        To_Date = Curr_Year & "/" & Curr_Mon & "/" & Curr_Day
                        Format_Date = To_Date
            End If

            If frmtType = 5 Then
                        Curr_Year = Right(Curr_year,2)

                        If Len(Curr_Day) = 1 Then
                                    Curr_Day = "0" & Curr_Day
                        End If
                        If Len(Curr_Mon) = 1 Then
                                    Curr_Mon = "0" & Curr_Mon
                       
                        End If
                        To_Date = Curr_Day & "/" & Curr_Mon & "/" & Curr_Year
                        Format_Date = To_Date
                       
            End If
End Function

'*******************************************************************************************************************
'*******************************************************************************************************************

Fucntionality : Compare 2 Excel sheets and store the Result into new Excel sheet

This function is used to compare two excel file and to store the results in another file.
It takes the File Path for the First & Second Excel Files to be compared, Takes the Sheet Numbers of both the excel Sheets.    
(1) First File: This parameter defines the path for the First Excel File
(2) Second File: This parameter defines the path for the Second Excel File
(3) First Sheet: This parameter specifies the Sheet Name in the specified First Excel File
(4) Second Sheet: This parameter specifies the Sheet Name in the specified Second Excel File
(5) Result File: This parameter defines the path where the output file needs to be stored

------------------------------------------------------------------------------------------------------------------------------------------------------------------

Example:-
__________________________________________

CompareExcelSheets("C:\Actual\One.xls","C:\Test\Two.xls","Sheet1","Sheet2","C:\Result\ComparisionOutput.xls")                                                                                                                                                                                                                                                           
'########################################################################################################################

Function CompareExcelSheets(FirstFile,SecondFile,FirstSheet,SecondSheet,ResultFile)
   Dim objFSO,ff,sf,x,y,ExcelApp1,SheetCount1,ExcelApp2,SheetCount2,xyz,i,j,Row1Count,Row2Count,Col1Count,Col2Count,ColCount,RowCount,RowNumber
   On Error Resume Next
 Set objFSO = CreateObject("Scripting.FileSystemObject")
ff=0
sf=0
x=0
y=0

'Check for the given file existence
If (objFSO.FileExists(FirstFile)) then
               Set ExcelApp1 = CreateObject("excel.application")
       ExcelApp1.workbooks.open(FirstFile)
       SheetCount1 = ExcelApp1.Application.Workbooks(1).worksheets.count
'Check for the given sheetname existence
            For i=1 to SheetCount1
               If ExcelApp1.Application.Workbooks(1).worksheets(i).name = FirstSheet Then x=1
            Next
'           msgbox ExcelApp1.Worksheets(FirstSheet).Rows.count
Else
ff=1
End If
'Check for the given file existence
If (objFSO.FileExists(SecondFile)) Then
               Set ExcelApp2 = CreateObject("excel.application")
       ExcelApp2.workbooks.open(SecondFile)
       SheetCount2 = ExcelApp2.Application.Workbooks(1).worksheets.count
'Check for the given sheetname existence              
            For j=1 to SheetCount2
               If ExcelApp2.Application.Workbooks(1).worksheets(j).name = SecondSheet Then y=1
            Next
            'msgbox ExcelApp1.Worksheets(SecondSheet).Rows.count
Else
sf=1
End If

'File1 Doesn't Exist then Quit the Function
If ff=1 Then
            Reporter.ReportEvent 1,"Please Verify File Path and Name Of First File       "&FirstFile,""
            Exit Function
End If
'File2 Doesn't Exist then Quit the Function
If sf=1 Then
            Reporter.ReportEvent 1,"Please Verify File Path and Name Of Second File        "&SecondFile,""
            Exit Function
End If
'Sheet1 Doesn't Exist then Quit the Function
If x=0 then
               Reporter.ReportEvent 1,"Please Verify Sheet Name Of First File            "&FirstSheet,""
               Exit Function
End If
'Sheet2 Doesn't Exist then Quit the Function
If y=0 then
               Reporter.ReportEvent 1,"Please Verify Sheet Name Of Second File            "&SecondSheet,""
               Exit Function
End If

If (objFSO.FileExists(ResultFile)) Then
            xyz=0
            else
            Reporter.ReportEvent 1,"Please Verify File Path and Name Of Result File       "&ResultFile,""
            Exit Function
End If

ExcelApp1.workbooks.close
            Set ExcelApp1 = Nothing
ExcelApp2.workbooks.close
            Set ExcelApp2 = Nothing

'   Add both sheets FirstExcel and SecondExcel
            datatable.AddSheet("FirstExcel")
            datatable.AddSheet("SecondExcel")

            'Import data to FirstExcel Sheet from FirstSheet of FirstFile
Execute "datatable.ImportSheet" & Chr(34) & FirstFile & Chr(34) & "," & Chr(34) & FirstSheet & Chr(34) & ", " & chr(34) &_
 "FirstExcel" & chr(34)

 'Import data to SecondExcel Sheet from SecondSheet of SecondFile
Execute "datatable.ImportSheet" & Chr(34) & SecondFile & Chr(34) & "," & Chr(34) & SecondSheet & Chr(34) & ", " & chr(34) &_
 "SecondExcel" & chr(34)

    'Assign the no.of Rows of FirstExcel to Row1Count and SecondExcel to Row2Count
            Row1Count = datatable.GetSheet("FirstExcel").getrowcount
            Row2Count = datatable.GetSheet("SecondExcel").getrowcount

            'Assign the no.of Columns of FirstExcel to Col1Count and SecondExcel to Col2Count
            Col1Count = datatable.GetSheet("FirstExcel").GetParametercount
            Col2Count = datatable.GetSheet("SecondExcel").GetParametercount

'If Row1Count = 0 Then
            '              Reporter.ReportEvent 1, "Check For Empty Sheet         "&FirstExcel,""
                        '   Exit Function
'End If

'If Row2Count = 0 Then
            '              Reporter.ReportEvent 1, "Check For Empty Sheet        "&SecondExcel,""
                        '   Exit Function
'End If 

'If any of the files are empty then quit the function
If Row1Count=0 or Row2Count = 0 Then
                           Reporter.ReportEvent 1, "Check For Empty", "Sheet"
                           Exit Function
End If 

                        'Check for the no.of Columns of both the sheets and if they are not equal then quit the function
                        If Col1Count <> Col2Count Then
                                    Reporter.ReportEvent 1, "Mismatch", "Columns"
                                    Exit Function
                        Else
                                    'If the no.of Columns of both the files are equal then add the Output sheet
                                    datatable.AddSheet "Output"
                                    ColCount = Col1Count
                                    'Print the Column Headings to the Output Sheet
                                    For i = 1 to ColCount
                                                datatable.GetSheet("Output").addparameter datatable.GetSheet("FirstExcel").getparameter(i).name, nothing
                                    Next
                                    'Add another column as Remarks to the Output Sheet for writing the Difference after Comparision
                                    datatable.GetSheet("Output").addparameter "Remarks",nothing

                                    'Compare the Rows of First and Second Data Sheets                
                                    If Row1Count < Row2Count Then
                                                RowCount = Row1Count
                                                datatable.GetSheet("Output").setcurrentrow Row1Count +1
                                                Row1Number = Row1Count +1
                                                'If the Second Sheet has got more no.of rows it displays a remark in Output Sheet
                                                For i =1 to (Row2Count - Row1Count)
                                                datatable.GetSheet("Output").getparameter(ColCount +1).value = "All Rows Does not Exist in First Sheet"
                                                datatable.GetSheet("Output").setcurrentrow Row1Number +i
                                                Next
                                    Else

                                                RowCount = Row2Count
                                                datatable.GetSheet("Output").setcurrentrow Row2Count +1
                                                Row2Number = Row2Count +1
                                                'If the First Sheet has got more no.of rows it displays a remark in Output Sheet
                                                For i =1 to (Row1Count - Row2Count)
                                                datatable.GetSheet("Output").getparameter(ColCount +1).value ="All Rows Does not Exist in Second Sheet"
                                                datatable.GetSheet("Output").setcurrentrow Row2Number +i
                                                Next
                                    End If
   
                                    RowNumber = 1
                                    datatable.GetSheet("FirstExcel").setcurrentrow 1
                                    datatable.GetSheet("SecondExcel").setcurrentrow 1
                                    datatable.GetSheet("Output").setcurrentrow 1
                                    B=True
                                    While datatable.GetSheet("FirstExcel").Getcurrentrow <= RowCount
                                                For i = 1 to ColCount
                                                            'Check the data in FirstExcel is same as SecondExcel and if they are same then write All Columns Match, else write the Column no where the mismatch is
                                                            If datatable.GetSheet("FirstExcel").getparameter(i).value = datatable.GetSheet("SecondExcel").getparameter(i).value Then
                                                                        datatable.GetSheet("Output").getparameter(i).value = datatable.GetSheet("FirstExcel").getparameter(i).value
                                                                                    If datatable.GetSheet("Output").getparameter(ColCount +1).value = "" Then
                                                                                    datatable.GetSheet("Output").getparameter(ColCount +1).value = "All Columns Match"
                                                                                    'B=True
                                                                                    End If
                                                            Else
                                                                        datatable.GetSheet("Output").getparameter(i).value = datatable.GetSheet("SecondExcel").getparameter(i).value
                                                                        If datatable.GetSheet("Output").getparameter(ColCount +1).value = ""  Then
                                                                                    datatable.GetSheet("Output").getparameter(ColCount +1).value ="Column " &  i  & " Does Not Match"
                                                                                    B=False
                                                                        Else
                                                                                    If datatable.GetSheet("Output").getparameter(ColCount +1).value = "All Columns Match" Then
                                                                                                datatable.GetSheet("Output").getparameter(ColCount +1).value = "Column " &  i  & " Does Not Match"
                                                                                                B=False
                                                                                    Else
                                                                                                datatable.GetSheet("Output").getparameter(ColCount +1).value = datatable.GetSheet("Output").getparameter(ColCount +1).value & "," & " Column " & i  & " Does Not Match"                 
                                                                                                B=False
                                                                                    End if
                                                                        End if
                                                End If
                                    Next
                                    RowNumber = RowNumber +1
                                    datatable.GetSheet("FirstExcel").setcurrentrow RowNumber
                                    datatable.GetSheet("SecondExcel").setcurrentrow RowNumber
                                    datatable.GetSheet("Output").setcurrentrow RowNumber
                        Wend
                        End if

'Export the OutputDataSheet data into Given ResultFilePath
Execute "datatable.Exportsheet"  & chr(34) & ResultFile & chr(34) & "," & Chr(34) & "Output" & Chr (34)
If B=False Then
            CompareExcelSheets=False
                                      '  Reporter.ReportEvent 1, "Mismatch", "Columns"
            Else
            CompareExcelSheets=True
                                    '           Reporter.ReportEvent 0, "Match All", "Columns"
End If
End Function

############################################################################