Wednesday, November 1, 2017

Test Automation Estimation guidelines

Hi,

I found good article on below page.

https://www.stepinforum.org/Test_Automation/TA_finaltalk/PDFs/Papers/TEST%20AUTOMATION%20EFFORT%20ESTIMATION.pdf

Regards,
Trupti

Tuesday, October 31, 2017

Key design activities and component for framework

Folks,

Following are key design activities for create robust automation framework

1. Define standard project folder hierarchy
2. Define standard configuration and launcher script.
3. Design standard format for automation component
4. Define reusable modules to reduce development and maintenance cost
5. Define layered architecture of reusable modules
6. Design standard flow control module
7. Design standard data storage, loading, sharing mechanism
8. Define standard reporting mechanism
9. Design standard error or exception handling mechanism

Components
1. Controller
2. Reusable component
3. Event Handler
4. Reporter

Regards, Trupti 

Read, write and delete a key from windows system registry

Dim owshell, skeypath, Skeyval, skeytype
Skeypath= "hkey_current_user\mycustomekey\mycustomedata\myvalue"
Skeyval="this is UFT made registry"
Skeytype="reg_sz"

Set owshell= createobject("wscript.shell")
Owshell.RegWrite skeypath,Skeyval ,skeytype

Skeyval = owshell .RegRead(skeyPath)
Print Skeyval

Owshell .RegDelete skeypath
 'To run application
SApp="notepad.exe"
Owshell .run sApp
Set owshell = nothing

Delete Cookies

Cookies are files containing data that is used by websites to remember user preferences and other relevant information ,such as authentication credentials. In some cases, we may need to delete cookies in order to do following.
1. Test if a site detects that the cookies are missing
2. Test if a site responds accordingly to the browser's configuration for example it prompt for approval, and then stores the selection
3. Test if a site responds according to application requirements for example, prompts for login if an authentication cookie is missing.

Simple way to achieve cookie deletion as follow.

To delete all cookie
Webutil.deletecookies()

To delete specific cookie from a domain
Webutil.deletecookie(domain,cookie)

Monday, October 30, 2017

File Rename, invalid extension and modify file data using UFT

'Invalid file extension
Public Function fnFileInvalidExtn(strfolderSourcePath,strfolderdestnPath,strFile)
   
        Set FSO=CreateObject("Scripting.FileSystemObject")
        strfolderSourcePath_mod=strfolderSourcePath&"\"&strFile
        strTestFileName1=Split (strFile,".")
        strTestFileNameFir=strTestFileName1(0)
        strTestFileName_extn_chg=strTestFileNameFir&"."&"d"
        strfolderdestnPath_mod=strfolderdestnPath&"\"&strTestFileName_extn_chg
        FileEx=FSO.FileExists(strfolderSourcePath_mod)
   
        If FileEx=True Then
            FSO.MoveFile strfolderSourcePath_mod,strfolderdestnPath_mod
            Call fnDoneResult("File Extension changed is Sucessful","File is renamed to " & strfolderdestnPath)    
        else
            Call fnFailResult("File Extension changed is UnSucessful ","Unable to renamed file to " & strfolderdestnPath)
        End If
        fnFileInvalidExtn=strTestFileName_extn_chg
                               
End Function

'File Rename

Public Function fnFileRename(strfolderSourcePath,strfolderdestnPath,strFile)
        Set FSO=CreateObject("Scripting.FileSystemObject")
        strfolderSourcePath_mod=strfolderSourcePath&"\"&strFile
        strTestFileNamemsg=Split (strFile,".")
        strTestFileNameFir=strTestFileNamemsg(0)
        strNewTestFileName=Left(strTestFileNameFir,5)&"_"&"Data"& "_" & year(Date) & Right("00" & Month(Date),2) & Right("00" & Day(Date),2) & Right("00" & Hour(Time),2) & Right("00" & Minute(Time),2)  & Right("00" & Second(Time),2) & ".dat"
        strfolderdestnPath_mod=strfolderdestnPath&"\"&strNewTestFileName
        FileEx=FSO.FileExists(strfolderSourcePath_mod)
   
    If FileEx=True Then  
        FSO.MoveFile strfolderSourcePath_mod,strfolderdestnPath_mod
        Call fnDoneResult("File Rename is Sucessful","File is renamed to " & strfolderdestnPath)    
      else
        Call fnFailResult("File Rename is UnSucessful ","Unable to renamed file to " & strfolderdestnPath)
    End If
fnFileRename=strNewTestFileName  
End Function

'Function to modify the file data
Public Function fnModifyFile(strFilePath,strOrignalString, strmodifiedString)
Const ForReading = 1
Const ForWriting = 2
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile(strFilePath, ForReading)
strText = objFile.ReadAll
objFile.Close
strNewText = Replace(strText, strOrignalString, strmodifiedString)
Set objFile = objFSO.OpenTextFile(strFilePath, ForWriting)
objFile.WriteLine strNewText
objFile.Close
End Function

Cute FTP connect, disconnect and file upload

'function to connect cute FTP
public function fnConnectCuteFTP(strHost,strUploadUserID,strUploadPwd)
Dim Flag
If Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Exist Then
       Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Close
    End If
Systemutil.Run "C:\Program Files (x86)\Globalscape\CuteFTP\cuteftppro.exe"
Wait (5)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Dialog("regexpwndclass:=#32770","regexpwndtitle:=Tip of the Day").WinButton("regexpwndclass:=Button","regexpwndtitle:=&Close").Click
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("regexpwndclass:=Edit","attached text:=Host:").Type trim(strHost)
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("nativeclass:=Edit","attached text:=Username:").Set trim(strUploadUserID)
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("nativeclass:=Edit","attached text:=Password:").Set trim(strUploadPwd)
Wait(1)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinToolbar("regexpwndclass:=ToolbarWindow32","regexpwndtitle:=Quick Connect").Press 1
Wait (5)
If Window("regexpwndclass:=#32770","regexpwndtitle:=File Transfer Log").Exist Then
       Window("regexpwndclass:=#32770","regexpwndtitle:=File Transfer Log").Close
       Call fnFailResult("CuteFTP Connection Failure ","Unable to connect to CuteFTP")
Flag=False      
    Else
       Call fnDoneResult("CuteFTP Connection Sucessful ","CuteFTP connection is sucessful")
Flag=True      
    End If
    fnConnectCuteFTP=Flag
End function

Public function fnDisconnectCuteFTP()
If Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Exist Then
       Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").Close
Call fnDoneResult("CuteFTP DisConnection","CuteFTP Disconnected sucessful")      
    Else
Call fnFailResult("CuteFTP is not launched","Unable to close as CuteFTP is not launched")  
    End If

End function

Public Function fnCuteFTPFileUpload(strFileSourcePath,strTestFileName)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("regexpwndclass:=Edit","window id:=132").Set trim(strFileSourcePath)
Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinEdit("regexpwndclass:=Edit","window id:=132").Type micReturn
Count=Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinListView("regexpwndclass:=SysListView32","window id:=1200").GetItemsCount
For i = 0 To Count
        FileName=Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinListView("regexpwndclass:=SysListView32","window id:=1200").GetItem(i)
        If FileName=trim(strTestFileName) Then
           Window("regexpwndtitle:=Globalscape","regexpwndclass:=Afx:").WinListView("regexpwndclass:=SysListView32","window id:=1200").Activate i
           Exit For
        End If
Next
Call fnDoneResult("CuteFTP Fileupload done","CuteFTP File upload sucessful")
End Function

Validate Environment Variable value

Environment is global object in UFT, it can be used to store and retrieve both run time and design time data.
Two type of environment variables
1. User defined-it has two types
- internal variable-- referred as default values
-external variable-- referred as constant value
2. Built in-give two type of information
- static data such as OS,OS version,local host name, test name, test fir etc
-Runtime data such as test iteration ,action name,action iteration etc

function for Validate_EnvironmentVar
Public function fnVerifyEnvironmentVar(strTestCaseID,strVarName,strVarValue)
Dim Flag
Set Obj = CreateObject("wscript.shell")
set objEnv = Obj.Environment("System")
sVarValue = objEnv.Item(strVarName)
If Trim(ucase(sVarValue))=Trim(ucase(strVarValue)) Then
Call fnDoneResult("Environment variable verify successfully", strVarName & " variable have value " &strVarValue& " match successfully.")
Flag=True
else
Call fnFailResult("Environment variable verify unsuccessfully",strVarName & " variable have value " &strVarValue& " not match successfully.")
Flag=False
End If
fnVerifyEnvironmentVar=Flag

End function

To rename folder

public Function fnRenameFolder(strFolderName,strSourcePath,strDestinationPath)
 
    Set FSO = CreateObject("Scripting.FileSystemObject")
    If Not FSO.FolderExists(strDestinationPath) Then
       FSO.MoveFolder strSourcePath,strDestinationPath
       Call fnDoneResult(strFolderName & " Folder rename",strFolderName & " Folder rename from " & strSourcePath & "to " & strDestinationPath & "Sucessfully")
    Else
       Call fnFailResult(strFolderName & " Folder Not Exist",strFolderName & " Folder already exist with same name on " & strDestinationPath )
    End If  
End Function

Get Recent log file and validate log message present or not using UFT

'function to get recent log file
Public Function fnRecentLogFile(strLogpath)
    Set recentLogFile = Nothing
    For Each file in fsoLogFile.GetFolder(strLogpath).Files
          If (recentLogFile is Nothing) Then
            Set recentLogFile = file
        ElseIf (file.DateLastModified > recentLogFile.DateLastModified) Then
            Set recentLogFile = file
        End If
    Next
End Function
'function to verify log messages present in file or not
Function fnVerifyLogFile(strLogFilePath,strLogFileMsg)
    Dim Flag
    Call fnRecentLogFile(strLogFilePath)
    Set objFile = fsoLogFile.OpenTextFile(recentLogFile)
    line_num=0
    Dim bMatchFlag
    bMatchFlag=False
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        line_num = line_num+1
        If InStr(strLine,strLogFileMsg)>0 Then
            'msgbox strLine
            bMatchFlag=True
            Exit Do
        else
            bMatchFlag=False
        End If
    Loop  
    If bMatchFlag=True Then
       Call fnDoneResult("Log Message Present",strLogFileMsg & "Log Message Present in LOG File.")
       Flag=True
    else
      Call fnFailResult("Log Message not present",strLogFileMsg & "Log Message not present in LOG File.")
      Flag=False
    End If
    fnVerifyLogFile=Flag
End Function

XML File validations using UFT

'function to load xml file and use globle xml object
Public Function fnLoadReadXMLFile(strFile,strFilePath)
Set objXMLFile=createobject("Microsoft.XMLDOM")
objXMLFile.async=False
Set gobjXMLFile=fnLoadXMLFile(strFilePath,objXMLFile)
End Function
'function to load xml file
Public Function fnLoadXMLFile(strFilePath,ByRef objXMLFile)
objXMLFile.Load(strFilePath)
If objXMLFile.parseError.ErrorCode=0 Then
Call fnDoneResult("XML File Loaded", "XML File Loaded Successfully.")
else
Call fnFailResult("XML File does not Loaded","XML File does not Loaded Successfully.")
End If
Set fnLoadXMLFile=objXMLFile
End Function
'function to read xml node value
Public Function fnRetriveXMLNodeValue(strXMLNode,ByRef objXMLFile)
Set ColNodes=objXMLFile.selectNodes(strXMLNode)
If ColNodes.length >0 Then
For each objNode in ColNodes
strXMLTempOld=objNode.Text
strXMLTemp=strXMLTemp & "|" & strXMLTempOld

If Left(strXMLTemp,1)="|" Then
strXMLTemp=Right(strXMLTemp, Len(strXMLTemp)-1)
End If
' strXMLClientIDAttr=objNode.getAttribute("strAttributeName")
Next
fnRetriveXMLNodeValue=strXMLTemp
Call fnDoneResult("XML Node value found","XML Node value" & strXMLTemp& " found")
ElseIf ColNodes.length=0 Then
strXMLTemp=""
fnRetriveXMLNodeValue=strXMLTemp
else
Call fnFailResult("XML Node value not found","XML Node value" & strXMLTemp& " not found")
End If
End Function
'function to read xml node attribute value
Public Function fnRetriveXMLNodeAttributeValue(strXMLNode,strAttributeName,ByRef objXMLFile)
Set ColNodes=objXMLFile.selectNodes(strXMLNode)
If ColNodes.length >0 Then
For each objNode in ColNodes
strXMLTemp=objNode.Text
strXMLAttriVal=objNode.getAttribute(strAttributeName)
Next
fnRetriveXMLNodeAttributeValue=strXMLAttriVal
Call fnDoneResult("XML Node Attribute value found","XML Node Attribute value " & strXMLAttriVal & " found")
ElseIf ColNodes.length=0 Then
strXMLAttriVal=""
fnRetriveXMLNodeAttributeValue=strXMLAttriVal
else
Call fnFailResult("XML Node Attribute value not found","XML Node Attribute value " & strXMLAttriVal & " not found")
End If
End Function
'function to modify xml node attribute value 
 Public Function fnModifyXMLNodeAttributeValue(strXMLNode,strAttributeName,strModifyTagVal,ByRef objXMLFile,strFilePath)
Set ColNodes=objXMLFile.selectNodes(strXMLNode)
If ColNodes.length >0 Then
For each objNode in ColNodes
objNode.Attributes.getNamedItem(strAttributeName).Text = strModifyTagVal
strXMLAttriVal=objNode.getAttribute(strAttributeName)
If strXMLAttriVal=strModifyTagVal Then
Call fnDoneResult("XML Node Attribute modified","XML Node Attribute value is modifed with " & strModifyTagVal)
else
Call fnFailResult("XML Node Attribute not modified","XML Node Attribute value is not modified with " & strModifyTagVal)
End If
objXMLFile.Save(strFilePath)
Call fnDoneResult("XML File save","XML File save with attribute change")
Next
'fnModifyXMLNodeAttributeValue=strXMLAttriVal
Call fnDoneResult("XML Node Attribute modified","XML Node Attribute value is modifed with " & strModifyTagVal)
'ElseIf ColNodes.length=0 Then
' strXMLAttriVal=""
'fnModifyXMLNodeAttributeValue=strXMLAttriVal
else
Call fnFailResult("XML Node Attribute not modified","XML Node Attribute value is not modified with " & strModifyTagVal)
End If
End Function

To check whether file exist in the specified path or not

Function fnFileExists_InSpecifiedPath(str_Path_FileName)
On Error Resume Next
'Specify the Path as well along with file name
Set fso = CreateObject("Scripting.FileSystemObject")
fnFileExists_InSpecifiedPath = fso.FileExists(str_Path_FileName)
    Set fso = Nothing
End Function

To get the size of specified file

Function fnGet_FileSize(str_Path_FileName)
   On Error Resume Next
'Specify the Path along with the file name
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
If fso.FileExists(str_Path_FileName) Then
Set ofile = fso.GetFile(str_Path_FileName)
File_Size = ofile.Size & " bytes"
Else
Call DoneResult("Specified File: " & str_Path_FileName & " not found", "Not able to fetch size of the file")
End If
fnGet_FileSize = File_Size
Set fso = Nothing
Set ofile = Nothing
End Function

To delete all files in the specified path

Function fnDeleteAllFiles_InSpecifiedPath(strPathName)
   On Error Resume Next
   Set fso = CreateObject("Scripting.FileSystemObject")
   Set oFolder = fso.GetFolder(strPathName)
   For Each oFile In oFolder.files
       oFile.Delete True
   Next
   'Delete Folders and sub folders
   Set colSubfolders = oFolder.Subfolders
   On Error Resume Next
   For Each oSubfolder in colSubfolders
fso.DeleteFolder(oSubfolder), True
   Next
   Set fso = Nothing
   Set oFolder = Nothing
   Set colSubfolders = Nothing
   Set oSubfolder = Nothing
If Err.Number <> 0 Then
ErrorNumber =" Error # " & CStr(Err.Number)
ErrorDescription = Err.Description
Call DoneResult("Specified Path '"& strPathName &"' is incorrect", "Not able to delete files and sub folders from the specified path:" & strPathName )
Err.Clear ' Clear the error.
Else
Call DoneResult("All files, Folders and Sub Folders are deleted in '" & strPathName & "'", "All files and sub folders are deleted in the specifed path")
End If
End Function

to delete the specfied file in specified path

Function fnDeleteFile_InSpecifiedPath(strPathName, strFileName)
On Error Resume Next
Set fso = CreateObject("Scripting.FileSystemObject")
Set oFolder = fso.GetFolder(strPathName)
Result = 0
If Err.Number <> 0 Then
ErrorNumber =" Error # " & CStr(Err.Number)
ErrorDescription = Err.Description
Call DoneResult("Specified Path '"& strPathName &"' is incorrect", "Not able to delete file: " & strFileName & " from " & strPathName)
Err.Clear ' Clear the error.
Exit Function
End If
On Error Resume Next
For Each oFile In oFolder.files
  If strcomp(oFile.name,strFileName,0) = 0 Then
oFile.Delete True
Call DoneResult("The file '" & strFileName & "'  is successfully deleted from '" & strPathName & "'" , "File is successfully deleted from '" & strPathName & "'")
            Result = 1
Exit For
  End If
    Next
If Result = 0 Then
Call DoneResult("The file: '" & strFileName & "' ' is not found in '" & strPathName & "'" , "Not able to delete the file from '" & strPathName& "'")
        Exit Function
End If
   Set fso = Nothing
   Set oFolder = Nothing
End Function

To compare two excel sheets

Function fnVerify_DtSheets_Equal(strSourceFile, strSourceSheetIndex, strTargetFile,strTargetSheetIndex)
On Error Resume Next
' Function to compare two Excel files (more specific to two diff Excel sheets.  )
' t compares each and every row and col and identifies the differences and reports all in line by line.
DataDifferences = 0
CompareReport = ""
If Not fnFileExists_InSpecifiedPath(strSourceFile) Then
Call DoneResult("Specified Source File is not found", "Not able to compare Excel Sheets")
Exit Function
    ElseIf Not fnFileExists_InSpecifiedPath(strTargetFile) Then
Call DoneResult("Specified Target File is not found", "Not able to compare Excel Sheets")
Exit Function
End If
DataTable.ImportSheet strSourceFile ,strSourceSheetIndex ,1
    DataTable.ImportSheet strTargetFile ,strTargetSheetIndex ,2
    GbSheetRowGount = DataTable.GetSheet(dtGlobalSheet).GetRowCount
LcSheetRowCount  = DataTable.GetSheet(dtLocalSheet).GetRowCount
GlobalColumnCount = DataTable.GetSheet(dtGlobalSheet).GetParameterCount
LocalColumnCount = DataTable.GetSheet(dtLocalSheet).GetParameterCount
If  Trim(GbSheetRowGount) = Trim(LcSheetRowCount)  and Trim(GlobalColumnCount) = Trim(LocalColumnCount) Then
Counter = 1
'msgbox "both sheets row counts are equal...."
For var_RowId = 1 to GbSheetRowGount
DataTable.SetCurrentRow(var_RowId)
For var_ColumnId =1 to GlobalColumnCount
GbSheetValue = Trim(DataTable.Value(var_ColumnId,  dtGlobalSheet))
LcSheetValue = Trim(DataTable.Value(var_ColumnId, dtLocalSheet))
If  Trim(GbSheetValue) <> Trim(LcSheetValue) Then
DataDifferences  = DataDifferences + 1
CompareReport = CompareReport  &  "Difference " & DataDifferences & " at :--- >  Row : " & var_RowId  & " ,  Column :  " & var_ColumnId & "  values :  ' " & GbSheetValue & "'  ,  '" & LcSheetValue & "' "  & vbCr
End If
GbSheetValue =Null
LcSheetValue=Null
Next      
Next
If  DataDifferences <> 0 Then
Reporter.Filter = rfEnableAll
Call DoneResult("Comparision is failed", CompareReport & "TOTAL " & DataDifferences & "  Data differences found ")
fnVerify_DtSheets_Equal = False
Else
Reporter.Filter = rfEnableAll
Call DoneResult("Comparision is succeeded", "Data Sheets are Equal: Source File = '" & strSourceFile & "' and Target file = '" & strTargetFile & "'")
fnVerify_DtSheets_Equal = True
End If
Else
Reporter.Filter = rfEnableAll
   Call DoneResult("Comparision is failed","Data Sheets Row or Columns are not equal...." & vbCr & "Source sheet Rows & Columns are : " & GbSheetRowGount  & " , " & GlobalColumnCount & "  and" & vbCr & "Target Sheet Rows & Columns are : " & LcSheetRowCount & " , " & LocalColumnCount)
   fnVerify_DtSheets_Equal = False
End If
End Function 

To clear all variable/data from the text file

Function fnClear_Data_From_TextFile(strFilePath)
   'Function to clear all variable/data from the text file
   On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
    'Path of the file to be modified
'strFilePath = Environment("Env_TestData_TextFile")
    'Create FSO Object
    Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strFilePath) Then
Call DoneResult("Specified file: '" & strFilePath & "' does not exist", "Not able to clear total contents from text file")
fnClear_Data_From_TextFile = ""
Exit Function
End If
'Get the file to be read.
Set objGetFile = objFSO.GetFile(strFilePath)
If objGetFile.Size <> 0 Then
        Set objTextFile = objGetFile.OpenAsTextStream(ForWriting,False)
        objTextFile.Close
Call DoneResult("Data is successfully deleted from the file: '" & strFilePath & "'", "Text file contents are deleted successfully")
Exit Function
End If
If Err.Number <> 0  Then
Call DoneResult("Exception error " & Err.Number & " with the description " & Err.Description & " occured while clearing all data from Text file", "Emptying text file is failed")
fnGet_Value_From_TextFile = ""
End If
End Function

To delete specified variable content from the text file

Function fnDelete_Value_From_TextFile(varName,strFilePath)
   'Function to delete specified content from the text file
   On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
    'Path of the file to be modified
        'Create FSO Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strFilePath) Then
Call DoneResult("Specified file: '" & strFilePath & "' does not exist", "Not able to delete specified content from text file")
fnDelete_Value_From_TextFile = ""
Exit Function
End If
'Get the file to be read.
Set objGetFile = objFSO.GetFile(strFilePath)
    'This code will read the file as Text Stream
Set objTextFile = objGetFile.OpenAsTextStream(ForReading,-2)
    Flag = 0
Dim var_SplitData()
Counter = 0
'This code will read all the lines in the Config file
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
ReDim Preserve var_SplitData(Counter)
var_found = Instr(1,strNextLine,varName,1)
If var_found > 0 Then
Flag = 1
Else
var_SplitData(Counter) = strNextLine
Counter = Counter + 1
End If
Loop
'This code will close the file after reading
objTextFile.Close
'Write data into the file
Set objTextFile = objGetFile.OpenAsTextStream(ForWriting,False)
For var_Loop = 0 to UBound(var_SplitData)
objTextFile.WriteLine var_SplitData(var_Loop)
Next
objTextFile.Close
If Flag = 0 Then
Call DoneResult("Specified content: '" & varName & "' does not exist in the test data text file","Not able delete the specified content from text file")
fnDelete_Value_From_TextFile = ""
End If
Set objTextFile = Nothing
Set objGetFile = Nothing
Set objFSO = Nothing
If Err.Number <> 0  Then
Call DoneResult("Exception error " & Err.Number & " with the description " & Err.Description & " occured while deleting the value from Text file", "Deleting the value from text file is failed")
fnGet_Value_From_TextFile = ""
End If
End Function

To set/update the value of the variable into the text file

Function fnSet_Value_Into_TextFile(strFilePath,varName, varValue)
'function to set/update the value of the variable into the text file
On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
'Path of the file to be modified
'strFilePath = Environment("Env_TestData_TextFile")
'Create FSO Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
'If specfied text file does not exist, create the text file and set the data
If Not objFSO.FileExists(strFilePath) Then
Set  objTextFile = objFSO.CreateTextFile(strFilePath, true)
objTextFile.WriteLine varName & " = " & varValue
objTextFile.Close
Call DoneResult("Value: " & varValue & " is set to the variable: " & varName & " in the text file: " & strFilePath, varName & " = " & varValue)
Exit Function
End If
'Get the file to be read.
'if fhe file is already created but no data available, then set the data
Set objGetFile = objFSO.GetFile(strFilePath)
If objGetFile.Size = 0 Then
Set objTextFile = objGetFile.OpenAsTextStream(ForAppending,False)
objTextFile.WriteLine varName & " = " & varValue
objTextFile.Close
Call DoneResult("Value: " & varValue & " is set to the variable: " & varName & " in the text file: " & strFilePath, varName & " = " & varValue)
Exit Function
End If
'If text file exist and the variable exist in it, then update its value
'This code will read the file as Text Stream
Set objTextFile = objGetFile.OpenAsTextStream(ForReading,-2)
Flag = 0
Dim var_SplitData()
Counter = 0
'This code will read all the lines in the Config file
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
ReDim Preserve var_SplitData(Counter)
var_found = Instr(1,strNextLine,varName,1)
If var_found> 0 Then
Flag = 1
var_SplitData(Counter) = varName & " = " & varValue
Else
var_SplitData(Counter) = strNextLine
End If
Counter = Counter + 1
Loop
'This code will close the file after reading
objTextFile.Close
'Write data into the file
Set objTextFile = objGetFile.OpenAsTextStream(ForWriting,False)
For var_Loop = 0 to UBound(var_SplitData)
objTextFile.WriteLine var_SplitData(var_Loop)
Next
objTextFile.Close
If Flag = 0 Then
Set objTextFile = objGetFile.OpenAsTextStream(ForAppending,False)
objTextFile.WriteLine varName & " = " & varValue
objTextFile.Close
Call DoneResult("Value: " & varValue & " is set to the variable: " & varName & " in the text file: " & strFilePath, varName & " = " & varValue)
End If
Set objTextFile = Nothing
Set objGetFile = Nothing
Set objFSO = Nothing
If Err.Number <> 0  Then
Call DoneResult("Exception error " & Err.Number & " with the description " & Err.Description & " occured while set the value into Text file", "Set value to text file is  failed")
fnGet_Value_From_TextFile = ""
End If
End Function

To fetch the value of a variable from the text file.

Function fnGet_Value_From_TextFile(strFilePath,varName)
'function to fetch value of the variable from text file
On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
'Path of the file to be modified
'strFilePath = Environment("Env_TestData_TextFile")
'Create FSO Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strFilePath) Then
Call DoneResult("Specified file: '" & strFilePath & "' does not exist", "Not able to fetch the data from specified text file")
fnGet_Value_From_TextFile = ""
Exit Function
End If
'Get the file to be read.
Set objGetFile = objFSO.GetFile(strFilePath)
'This code will read the file as Text Stream
Set objTextFile = objGetFile.OpenAsTextStream(ForReading,-2)
'This code will read all the lines in the Config file
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
var_found = Instr(1,strNextLine,varName,1)
Flag = 0
If var_found> 0 Then
Flag = 1
'get the value of the  specified variable
var_SubString = Mid(strNextLine,var_found+Len(varName)+3)
fnGet_Value_From_TextFile = var_SubString
Call DoneResult("Value: " & varValue & " is retrieved for the variable: " & varName & " in the text file: " & strFilePath, varName & " = " & varValue)
Exit Do
End If
Loop
'This code will close the file after reading
objTextFile.Close
Set objTextFile = Nothing
Set objGetFile = Nothing
Set objFSO = Nothing
If Flag = 0 Then 'if the variable does not exist in the File, returns empty
fnGet_Value_From_TextFile = ""
Exit Function
End If
If Err.Number <> 0  Then
Call DoneResult("Exception error " & Err.Number & " with the description " & Err.Description & " occured while retrieving the value from Text file", "Data Retreival is  failed")
fnGet_Value_From_TextFile = ""
End If
End Function

To delete temporary files, temporary internet files and cookies

Function fnDelete_TempFiles_Cookies()
   'Delete temporary files , temporary internet files and cookies
   On Error Resume Next
'Set up environment
Set WSHShell = CreateObject("WScript.Shell")
Set fso = createobject("Scripting.FileSystemObject")
userProfile = WSHShell.ExpandEnvironmentStrings("%userprofile%")
Windir = WSHShell.ExpandEnvironmentStrings("%windir%")
    'start deleting files in Temp folder
Set oFolder1 = fso.GetFolder(userProfile & "\Local Settings\Temp\")
For Each oFile In oFolder1.files
oFile.Delete True
Next
'Delete folders and subfolders
Set colSubfolders1 = oFolder1.Subfolders
On Error Resume Next
For Each oSubfolder in colSubfolders1
fso.DeleteFolder(oSubFolder), True
Next
'deleting temporary internet files
Set oFolder2 = fso.GetFolder(userProfile & "\Local Settings\Temporary Internet Files\")
For Each oFile In oFolder2.files
oFile.Delete True
Next
Set colSubfolders2 = oFolder2.SubFolders
For Each oSubfolder in colSubfolders2
fso.DeleteFolder(oSubFolder)
Next
'delete Files and folders in System windows directory
Set oFolder3 = fso.GetFolder(Windir & "\Temp\")
For Each oFile In oFolder3.files
oFile.Delete True
Next
Set colSubfolders3 = oFolder1.Subfolders
For Each oSubfolder in colSubfolders3
fso.DeleteFolder(oSubFolder)
Next
'deleting Cookies
Set oFolder4 = fso.GetFolder(userProfile & "\Cookies\")
For Each oFile In oFolder4.files
oFile.Delete True
Next
Set colSubfolders4 = oFolder4.SubFolders
For Each oSubfolder in colSubfolders4
fso.DeleteFolder(oSubFolder)
Next
Call DoneResult("Temporary files, temporary internet files and cookies are deleted successfully","Temporary files, temporary internet files and cookies are deleted successfully")
'Clear memory
Set fso = Nothing
Set oFolder1 = Nothing
Set oFolder2 = Nothing
Set oFolder3 = Nothing
Set oFolder4 = Nothing
Set oSubFolder1 = Nothing
Set oSubFolder2 = Nothing
Set oSubFolder3 = Nothing
Set oSubFolder4 = Nothing
Set colSubfolders1 = Nothing
Set colSubfolders2 = Nothing
Set colSubfolders3 = Nothing
Set colSubfolders4 = Nothing
Set oFile = Nothing
Set userProfile = Nothing
Set Windir = Nothing
'End Script
WScript.Quit
fnDelete_TempFiles_Cookies = True
End Function

To search value from text file

Function fnSearchString_From_TextFile(strFilePath,varValue,NoOfOccurances)
   'function to search value from text file
   On Error Resume Next 'Error Handling
'Constants for Reading and Tristate Use Default
Const ForReading = 1,ForWriting= 2,ForAppending = 8
    'Create FSO Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
If Not objFSO.FileExists(strFilePath) Then
Call DoneResult("Specified file: '" & strFilePath & "' does not exist", "Not able to search the data from specified text file")
fnSearchString_From_TextFile = ""
Exit Function
End If
'Get the file to be read.
Set objGetFile = objFSO.GetFile(strFilePath)
'This code will read the file as Text Stream
Set objTextFile = objGetFile.OpenAsTextStream(ForReading,-2)
'This code will read all the lines in the Config file
var_Position = 1
var_Count = 0
Do Until objTextFile.AtEndOfStream
        strNextLine = objTextFile.Readline
var_Position = Instr(var_Position,strNextLine,varValue,1)
If var_Position > 0 Then
var_Count = var_Count + 1 'retrieving the no of occurances
Else
var_Position = 1
End If
Loop
    If var_Count  = NoOfOccurances Then 'if matched
        Call DoneResult("Number of Occurances "& NoOfOccurances & " for the value '" & varValue & "' in the text file '" & strFilePath & "' is passed", "Search is passed")
fnSearchString_From_TextFile = True
ElseIf var_Count > 0 Then 'if no of occurances are failed, but atleast one match found
Call DoneResult("'" & varValue & "' exists in the text file '" & strFilePath & "' for '" & var_Count & "' times, but not for the specified number of Occurances '" & NoOfOccurances & "'", "Search is failed")
fnSearchString_From_TextFile = ""
Else 'no match found
Call DoneResult("Search for Number of Occurances of the value '" & varValue & "' in the text file '" & strFilePath & "' is failed", "Search is failed")
fnSearchString_From_TextFile = ""
End If
'This code will close the file after reading
objTextFile.Close
Set objTextFile = Nothing
Set objGetFile = Nothing
Set objFSO = Nothing
If Err.Number <> 0  Then
Call DoneResult("Exception error " & Err.Number & " with the description " & Err.Description & " occured while searching the value from Text file", "Search failed")
fnSearchString_From_TextFile = ""
End If
End Function

Function to Zip and UnZip the folder and files

Function fnZipFile(strSource,strTarget)
    fnZipFile = false
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Set fso = CreateObject("Scripting.FileSystemObject")

    'write zip file header
    set file = fso.opentextfile(strTarget,ForWriting,True)
    file.write "PK" & chr(5) & chr(6) & string(18,chr(0))
    file.close
   
    'copy source file to zip file
    set shl = CreateObject("Shell.Application")
    shl.namespace(strTarget).copyhere(strSource)
    set shl = Nothing
    fnZipFile = True
End Function

Function fnUnZip(sUnfnZipFileName,sUnzipDestination)
Set oUnzipFSO = CreateObject("Scripting.FileSystemObject")
If (Not (oUnzipFSO.FolderExists(sUnzipDestination))) Then
oUnzipFSO.CreateFolder(sUnzipDestination)
End If
With CreateObject("Shell.Application")
.NameSpace(sUnzipDestination).Copyhere .NameSpace(sUnfnZipFileName).Items
End With
Set oUnzipFSO = Nothing
End Function

Download the attachments from path to To path

Public Function FnDownloadAttachments(ByVal FromPlace, ByVal ToPlace, ByVal fileName)
   FnDownloadAttachments = 0

   If Right(ToPlace , 1) <> "\" Then
ToPlace = ToPlace & "\"
   End If

Dim oFindAttachments
oFindAttachments = FnFindAttachment(FromPlace, fileName)

Set FSO = CreateObject ("Scripting.FileSystemObject")
Dim index

For index = LBound(oFindAttachments) to UBound(oFindAttachments)
oFindAttachments(index).Load True, ""
FSO.CopyFile oFindAttachments(index).FileName, _
ToPlace & oFindAttachments(index).Name(1), True

FnDownloadAttachments = FnDownloadAttachments + 1
Next
End Function

To check whether the perticular value is present into excel sheet

Function fnIsExistInExcelColumn(inputFilePath,excelSheetName,columnHeader,textValue)

Dim con,rs
Dim varme
Set con=createobject("ADODB.connection")
Set rs=createobject("ADODB.recordset")

con.open "DRIVER={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ="&inputFilePath&";Readonly=True"
varme="SELECT count(*) FROM ["&excelSheetName&"$] where "&columnHeader&" = '"&textValue&"' "
rs.open varme,con
fnIsExistInExcelColumn= rs(0)

'Release objects
Set rs= nothing
Set con= nothing

End Function

Close the Process running in windows Task manager

Function fnCloseProcess(strProgramName)
' creating variable
Dim objProcess
Set objProcess=CreateObject("WScript.Shell")
'running command to kill the process
objProcess.Run "TASKKILL /F /IM "& strProgramName
Set objProcess=nothing
End Function

Extract the text between start point and end point

Function fnGetInText(str,startChar,endChar)
  'stores coloumn position of end character
endPoint=InStr(str,endChar)
'stores coloumn position of starting character
startPoint=InStr(str,startChar)      
'resultant text
resultText=Mid(str,startPoint+1,endPoint-startPoint-1)
fnGetInText=resultText
End Function

Compare dates provide in two different formats

Function fnCompareDate(date1,Date2)
varDay1 = day(date1)
varMonth1 = Month(date1)
varYear1 = Year(date1)
varDay2 = day(date2)
varMonth2 = Month(date2)
varYear2 = Year(date2)

If ((varDay1=varDay2)and(varDay1=varDay2) and(varDay1=varDay2)) Then
fnCompareDate= true
Else
fnCompareDate= false
End If
End Function

Batch Process Application testing using UFT

Greetings to Readers,

Another try on sharing knowledge for batch process application testing using UFT. Below are few approach for automation framework in batch process applications.


  1. Understand the all batch process applications- sub batches functions, based on it decide the automation scenarios. sequence of batches for run, input and output for that batch, validation rules, where that batch files are deployed or run, how to run, how can we run using UFT etc needs to take care
  2. At a time, how many batches can run, do they require same inputs or outputs, dependent on each other, validation for some files, inputs etc.
  3. Try to use different library for all sub batch files, as maintenance is less
  4. Try to use generic functions for some validations of common batches validations
  5. Try to use global variables for maintain data through the batches for validations
  6. Use hybrid framework for automation with combination of module function based approach. here data will not be vary mostly for such type of applications.
Regards,
Trupti

Pega Automation approach using UFT

Hey folks,

I try here to give you reference for taking automation approach for PEGA automation projects. I have used UFT 12.02 for PEGA 7.2.2 version automation in one of my project. Following are checklist, which can help.

  1. As PEGA application is rule based and flow based application, there were always few set of pages will be used in application. Before deciding framework, dry run the whole application flow for the pages behavior.
  2. As pages, might be limited, we can use object repository approach for the application as size will not grow. For few PEGAcontrols, we need to write descriptive programming as well. Mostly frame related problems occurs for few control identification.
  3. As it is rule based application, may be require to run different set of test with combination of test data to test the rules, but pages remains same. So try use data driven approach while using framework. Keep all the functions generic so with any combination of test data, we can use same functions.
  4. As its having flow based application too, driver script should having provision to calling different functions in sequences to drive the flow. Write module based functions for easy flow driven. 
  5. Most of the flow driven by some actions like approve, reject etc., so write function in generic with switch cases to handle the different flow along with data passing approach.
  6. Few scenarios may be having multiple data at same flow, then there should be some provision to handle multiple entry of test data by passing argument in split way.
  7. Few controls are dynamic based on the conditions, so we can handle it using regular expression. for ex., few property values like , \strname1 can handle in as $\strname1, like that. 
  8. Controls are similar to rest web applications for PEGA. UFT can identify it properly, there is no additional add ins require.
  9. For error handling, we can used on error resume next statement at function level.
  10. Facing sync issue for application, which hurdle in night run execution. so increase wait time much to avoid such things.
  11. Try to keep all function libary at module levels.
  12. Use environment variables for sharing constant value across test suite
  13. keep configuration files for easy project path references.
  14. keep files references at top level with public variable to access across the test suite for implementing rules.
  15. keep generic functions to connect external files, fetching values or rules to implement, export test results etc.
  16. while executing UFT , we need to enable add on in internet explore for PEGA.
Regards,
Trupti

Thursday, October 26, 2017

PEGA Application Testing

Hi folks,

After long time, publish another article on Pega Application testing.

Pega application testing needs to take different approach of testing then normal STLC. Pega applications are rule based application having more than 10 k rules. I was worked with pega version 7.2.2.

Pegasystems is a leading BPM / Case Management platform provider. As leaders they are at the forefront in offering automated testing capabilities in the BPM space. Testing Pega BPM based applications from the UI is still a challenge however. Pega testing is followed in agile model. Pega is fast growing tool which makes millions of users happy. It is a business process management (BPM) tool which was founded by Alen Trefler. Pega PRPC is an Application Development Product from Pega Systems. To Test Pega Applications one need to know the Testing Management Framework (TMF) from Pega as well as Required knowledge in Manual Testing and Regressive Testing. Using Pega Unit Testing Feature one can test the Flow Rules, Decision Rules, Integrations and Automated Regression Testing. With the help of pega testing we test the pega applications very wisely and deliver as a defect free.It uses concept called PRPC which is a pega rules and process commander. It uses Rules set to design the pega applications.

As it is rule based application with large set of rules, automation tester needs to create their own framework for rule implementation. use unit testing or functional approach is more better to reusability purpose. Rules can be implemented as functional validations and we can add modules or component base approach as well for the flow of application.

As per research, selenium is best tool for pega testing, but I have used UFT 12.02 for the pega automation. Later on, project move in selenium, but I didn't find much difference in both apart from licence cost of UFT. all technical problem still resides in selenium too, which was happen with UFT.

(Reference taken from quora for below content)
Pega has different Debugging Tool inbuilt to test the Application .we have different types of testing in pega .
Types of Testing :
  • Flow based Testing – Concentrates on Business flows (E2E), involving multiple roles and interfaces
  • Role based Testing – Testing based on workgroups – Skills, UI etc
  • Rule based Testing –
    1. Business Rules - Formulae, delegated rules etc
    2. Technical Rules - integration rules etc
Pega Debugging Tools:
  • Clipboard
  • Tracer
  • Rule Inspector/UI Inspector
  • PLA (PegaRULES Log Analyzer)
  • PAL (Performance Analyzer)
  • AUT (Automated Unit Testing)
(Reference over)

For automation perspective- we should go with hybrid -data driven framework with modular approach, which work best for rule implementation with different set of data to all modules.

Few challenges in Pega projects like-
1. control identification for web edits not work proper- down key or keystroke approach needs to write for most of controls
2.Nightly run not work- application sync issues occurs much
3. modules approach required and for that application knowledge must be with you to take the decision for create modules-passing parameters, use parameters etc.
4. due to rule based implementation execution time takes more for end to end flows.
5. keep provision for normal end to end flow execution, rule base validation for module execution, role base validation etc in script itself.

Regards,
Trupti