Showing posts with label stcode. Show all posts
Showing posts with label stcode. Show all posts

Sunday, September 28, 2008

Children objects has negative co-ordinates in Browserchild

Last year, one web based product has been revamped with our own reporting modules. Lot of javascripts used for this reporting. Silktest is able to identify the HtmlTable and HtmlColumn objects properly. But the co-ordinates are shown wrong. Each click action is done in different point instead of expected point. Only X-Axis position got changed. See the RECT info below.

BrowserChild (Parent) rect: {195, 175, 827, 538}
Htmltable rect: {-77, 323, 818, 574}


It is varying for different kind of reports. Testcases need to do left-mouse click and right-mouse clicks. I have set few variables for position changes. I have written the code like below. In the Runtime, XAxis changes (ixGridInc) are calculated dynamically. I have given the code below:

4Test code - To set the Table position dynamically


[-] void SetGridTablePosChanges (Window wTable)
[ ] // To set xAxis and YAxis increments (changes)
[ ] // Position changes.
[ ] Window wParent
[ ] Boolean bxGetPos = FALSE
[ ] String sWinTag, sMainFrameTag
[ ]
[ ] RECT rtTblCell = wTable.GetRect (TRUE)
[ ] Print ("table rect: {rtTblCell}")
[ ]
[-] if (ixGridInc == -1)
[ ] Print ("Grid xAxis increment is going to set.")
[ ] ixGridPos = rtTblCell.xPos
[ ] // iyGridPos = rtTblCell.yPos
[ ] bxGetPos = TRUE
[-] else if (ixGridPos != rtTblCell.xPos)
[ ] bxGetPos = TRUE
[ ] ixGridPos = rtTblCell.xPos
[ ] // iyGridPos = rtTblCell.yPos
[-] else
[ ] Print ("Already Grid xAxis increment is available.")
[ ]
[-] if (bxGetPos)
[ ]
[ ] sMainFrameTag = WindowTag (wTable)
[ ] sWinTag = GetField (sMainFrameTag,"[BrowserChild]",3)
[ ] Print ("Whole Table tag: {sMainFrameTag}")
[ ] Print ("Parent tag: {sWinTag}")
[-] if (MatchStr ("*[6]*",sWinTag) || MatchStr ("*mainFram*",sWinTag))
[ ] wParent = MyReportPage
[ ] RECT rtTblCell2 = wParent.GetRect (TRUE)
[ ] Print ("Parent rect: {rtTblCell2}")
[ ]
[-] if ((rtTblCell.xPos < (rtTblCell2.xPos + XAXIS_TABLE_DIFF)) )
[ ] ixGridInc = rtTblCell2.xPos - (rtTblCell.xPos) + XAXIS_TABLE_DIFF
[ ] Print ("X Axis changed Position: {ixGridInc}")
[-] else
[ ] Print ("Parent{wParent} is not expected one.")

Saturday, September 6, 2008

Saving Clipboard contents as Image

Scenario 1:
Earlier I had a challenging task to automate SVG charts. There are two issues. Major issue is, Silktest does not identify SVG Chart as any object (custom/HtmlImage). Second one is taking Bitmap image for the chart. SVG chart gives the flexibility by 'Copy SVG' feature. Using this we can copy the chart image. It can be saved as text or Image file.

Scenario 2:
Last month, I have posted VBA - Extract Pictures from Excel . It works fine, if this VBA code is executed as Excel Macro. But the same code does not extract the image with the right quality, after running as VB Script. I got the problem, while saving/pasting the clipboard copy. I was forced to find a way to implement a method, to save clipboard image as a image file.

Solution:
IrfanView is a windows graphic viewer and it is a freeware utility. It can be used command-line utility. It has a command-line option to save the clipboard image as image file. You can save the image in many different formats.

Syntax to Convert clipboard image as image file:
/clippaste - paste image from the clipboard.

Below I have given the way to implement in VBScript and Silktest.
Silktest code:


[ ] // To save the image
[ ] SYS_Execute ("D:\autostuff\i_view32.exe /silent /clippaste /convert=D:\my_scripts\testdata\zsvg1.bmp")


VB Script code:

'-------------------------------------------------------------------------
' Method : CreateImageFromClipBoard
' Author : Palani Selvam
' Purpose : It gets the clipboard image and convert as a image file.
' Parameters: FileName - String, contains the BMP file name
' iIndex - Integer, contains the Worksheet index
' Returns : String. The replaced file name it gives.
' Caller : - Nil
' Calls : - Nil
'-------------------------------------------------------------------------
Sub CreateImageFromClipBoard(sFileName)

Dim wshShell,ShellReturnCode, sCmdExec

Set WshShell = WScript.CreateObject("WScript.Shell")
sCmdExec = "D:\autostuff\i_view32.exe /silent /clippaste /convert="& sFileName

ShellReturnCode = WshShell.Run(sCmdExec, 1, True)

End Sub


Modified VB Script code for VBA - Extract Pictures from Excel
Note: Few function calls are from my vbscript library.

'--------------------------------------
' Method : ReadExcel
' Author : T. Palani Selvam
' Purpose : Read all the contents from Excel sheet and write into log file
' Parameters: sExcelFile - String, contains the Excel file
' : iSheetIndex - Integer, Value for Sheet Index
' Returns : - Nil
' Caller : - Nil
' Calls : - Nil
'--------------------------------------
Sub ReadExcel(sExcelFile, iSheetIndex)
Dim sExcelPath 'As Variant 'Excel file
'********** Excel object declaration **********'
' Excel Application object
Dim objExcel 'As Excel.Application
Dim objXLWorkbooks 'As Excel.Workbooks
Dim objXLWorkbook 'As Excel.Workbook

Dim WorkSheetCount 'As Variant 'Work sheets count in a excel
Dim CurrentWorkSheet 'As Excel.Worksheet ' Current worksheet
Dim objCells 'As Excel.Range
Dim objCurrentCell 'As Variant
Dim objFont 'As Variant

' Result contents
Dim sCellText 'As Variant
Dim sFontName 'As Variant
Dim sFontStyle 'As Variant
Dim iFontSize 'As Variant
Dim iCellTextColorIndex 'As Variant
Dim iCellInteriorColorIndex 'As Variant
Dim sResult 'As Variant
Dim sChartFile 'As String


' Row and Col integer variables
Dim iUsedRowsCount 'As Integer
Dim iUsedColsCount 'As Integer
Dim iTop, iLeft 'As Integer
Dim iRow 'As Integer 'Row item
Dim iCol 'As Integer 'Col item
Dim iCurRow 'As Integer
Dim iCurCol 'As Integer


If (sExcelFile = "") Then
sExcelPath = "D:\my_scripts\Basic Wks.xls"
Else
sExcelPath = sExcelFile
End If

If (iSheetIndex = "") Then
iSheetIndex = 2
End If


Call FileDeleteAndCreate (gsLogFile)

'XL file check
If (FileExists(sExcelPath) <> 0) Then
Call LogWrite (gsLogFile, "The Excel file " & Chr(34) & sExcelPath & Chr(34) & " does not exit!")
Exit sub
End If

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open sExcelPath, False, True

On Error Resume Next

Set objXLWorkbook = objExcel.ActiveWorkbook
'objXLWorkbook.RunAutoMacros

WorkSheetCount = objXLWorkbook.Worksheets.Count

Set CurrentWorkSheet = objExcel.ActiveWorkbook.Worksheets(iSheetIndex) 'iSheetIndex worksheet

iUsedRowsCount = CurrentWorkSheet.UsedRange.Rows.Count
iUsedColsCount = CurrentWorkSheet.UsedRange.Columns.Count
iTop = CurrentWorkSheet.UsedRange.Row
iLeft = CurrentWorkSheet.UsedRange.Column

' Cells object
CurrentWorkSheet.Cells.Activate


For iRow = iTop To iUsedRowsCount-1 '(iUsedRowsCount - 1)
'Read All rows
For iCol = iLeft To iUsedColsCount '(iUsedColsCount - 1)

sResult = ""
Set objCurrentCell = CurrentWorkSheet.Cells(iRow, iCol)
sCellText = objCurrentCell.Text


If ((sCellText = Empty)) Then


sResult = "Reading Cell {" & CStr(iRow) & ", " & CStr(iCol) & "}^" &" "& "^" & " " & "^" & " " & "^" & " " & "^" & " " & "^" & " "

Call LogWrite (gsLogFile, sResult)

Else
Set objFont = objCurrentCell.Font
sFontName = objFont.Name
sFontStyle = objFont.FontStyle
iFontSize = objFont.Size
iCellTextColorIndex = objFont.Color
iCellInteriorColorIndex = objCurrentCell.Interior.ColorIndex



If (sFontName = Empty) Then
sFontName = "empty"
End If
If (sFontStyle = Empty) Then
sFontStyle = "empty"
End If
If (iFontSize = Empty) Then
iFontSize = "-99999999"
End If
If (iCellTextColorIndex = Empty) Then
iCellTextColorIndex = "99999999"
End If
If (iCellInteriorColorIndex = Empty) Then
iCellInteriorColorIndex = "99999999"
End If


sResult = "Reading Cell {" & CStr(iRow) & ", " & CStr(iCol) & "}^" & sCellText & "^" & CStr(iCellInteriorColorIndex) & "^" & sFontName & "^" & CStr(sFontStyle) & "^" & CStr(iFontSize) & "^" & CStr(iCellTextColorIndex)

Call LogWrite (gsLogFile, sResult)

End If

Set objCurrentCell = Nothing


Next

Next
'Get the Chart now
'sChartFile = Replace (sExcelFile,".xls",".png")
sChartFile = Replace (sExcelFile,".xls",".bmp")

'*****************************
' Place for Chart creation
objExcel.ScreenUpdating = False

Dim iIndex,iPictureHeight,iPictureWidth,iShapeCount
Dim aShape, aChart, aShapeChart, aChart1
Dim sPictureShape, sChartName, sCurrentSheet


'Set aWorkSheet = ActiveWorkbook.ActiveSheet

sCurrentSheet = CurrentWorkSheet.Name

For iIndex = 1 To CurrentWorkSheet.Shapes.Count

Set aShape = CurrentWorkSheet.Shapes(iIndex)
sPictureShape = aShape.Name
'Picture 1 Name, 13

If Left(aShape.Name, 7) = "Picture" Then
aShape.CopyPicture
Call CreateImageFromClipBoard (sChartFile)

''objExcel.ScreenUpdating = True
Exit For

End If
Next

if FileExists(sChartFile)=0 Then
Call LogWrite (gsLogFile, "Chart Image: " & sChartFile)
End If

' This will prevent Excel from prompting us to save the workbook.
objExcel.ActiveWorkbook.Saved = True
Set CurrentWorkSheet = Nothing

'objExcel.Worksbooks.Close
objExcel.Quit

''Set CurrentWorkSheet = Nothing
Set objExcel = Nothing

'MsgBox "Read Completed.", vbOKOnly, "Exec Over"
Exit Sub

ErrorHandler1:
'MsgBox "Error # " & CStr(Err.Number) & " " & Err.Description
'Err.Clear ' Clear the error.
End Sub

Wednesday, September 3, 2008

Convert failed testcases as a testplan

We have few silktest automation projects. One project is used to execute by suite. Another one is ran by batch (*.bat) file, which has few sub-plans. I am not able to run the failed cases from all results at one shot. I was looking an utility, similar to 'Mark failures in Plan' in the results menu. I thought to implement a 4test script to convert failed testcases as a testplan and I did it.

4Test code - Create testplan for failed cases only

[ ] LIST OF STRING glsFailedScripts = {} [ ] [+] testcase ConvertTestPlan_SingleFile () appstate none [ ] [ ] STRING sResFile = "D:\Auto_Scripts\Results\MyStuff_MasterPlan.res " [ ] STRING sRexFile = "D:\Auto_Scripts\Results\MyStuff_MasterPlan1.rex " [ ] STRING sMyPlanFile = "D:\Auto_Scripts\Results\zSingleFailed.pln " [ ] [ ] glsFailedScripts = {} [ ] CreateFileFromTemplate(sPlanTemplate,sMyPlanFile) [ ] ResExport (sResFile,sRexFile) [ ] ProcessSingleREXFile (sRexFile,sMyPlanFile) [ ] [ ] Agent.DisplayMessage ("test","Completed.") [ ] [-] // functions [+] Boolean GetFailedTestInfo (STRING sRexLine, out LIST OF STRING lsPlanInfo) [ ] [ ] // Title [ ] //TestPlan Script TestCase TestData ErrorCount ErrorText DateTime Elapsed [ ] [ ] // Samples [ ] // "D:\Auto_Scripts\PlanFiles\MyStuff_MasterPlan.pln","D:\Auto_Scripts\Scripts\FamilyFunctions.t","FamilyFunctions_DimensionFunctions_5", [ ] // "Verify user sees a proper error message by clicking OK button.",0,"","2008-08-18 21.52.06","0:00:00" [ ] [ ] STRING sScript [ ] STRING sTestCase [ ] STRING sTestData,sFormattedData [ ] STRING sTestTime [ ] STRING sErrCount, sErrCount1 [ ] INTEGER iPos [ ] [ ] // Initialization [ ] STRING sIndentation = " " [ ] STRING sIndentation1 = "[+] " // Level1 [ ] STRING sIndentation2 = " [ ] " // Level2 [ ] [ ] STRING sSeperator = """,""" [ ] STRING sErrSeperator = ",""" //",""***" [ ] STRING sDataSeperator = """,0,""" [ ] STRING sErrSeperator1 = """" [ ] Boolean bResult = FALSE [ ] lsPlanInfo = {} [ ] [ ] sErrCount1 = GetField (sRexLine,sSeperator,4) [ ] sErrCount = GetField (sRexLine,sDataSeperator, 2) [ ] //if ((Trim(sErrCount) != "") && (Val(sErrCount) > 0)) [+] if ((Trim(sErrCount) == "") && (Trim(sErrCount1) != "") ) [ ] Print ("Considering line: {sRexLine}") [ ] bResult = TRUE [ ] sScript = GetField (sRexLine,sSeperator,2) [ ] sTestCase = GetField (sRexLine,sSeperator,3) [ ] sTestTime = GetField (sRexLine,sSeperator,6) [ ] Print ("Elapsed: {sTestTime}") [+] if (sTestTime == "") [+] sFormattedData = "" [ ] iPos = StrPos (sErrSeperator, sTestCase,TRUE) [+] if (iPos > 0) [ ] Print ("sTestCase:{sTestCase}: iPos:{iPos}") [ ] sTestCase = SubStr (sTestCase, 1,iPos - 4) [ ] Print ("Before formatting, sTestCase:{sTestCase}") [ ] //sTestCase = StrTran (sTestCase,"\","") [ ] Print ("After formatting, sTestCase:{sTestCase}") [ ] [+] else [ ] sTestData = GetField (sRexLine,sSeperator,4) [+] if (MatchStr ("*,?,""*",sTestData)) [ ] iPos = StrPos (sErrSeperator, sTestData,TRUE) [+] if (iPos > 0) [ ] Print ("TestData:{sTestData}: iPos:{iPos}") [ ] sTestData = SubStr (sTestData, 1,iPos - 4) [ ] Print ("Before formatting, TestData:{sTestData}") [ ] sFormattedData = StrTran (sTestData,"\","") [ ] Print ("After formatting, TestData:{sTestData}") [ ] [ ] Print ("TestCase: {sTestCase}") [ ] Print ("TestData: {sFormattedData}") [ ] [+] if ( (glsFailedScripts == {}) || (glsFailedScripts[ListCount(glsFailedScripts)] != sScript) ) [ ] ListAppend (glsFailedScripts,sScript) [ ] ListAppend (lsPlanInfo,"{sIndentation1}#script: {sScript}") [+] // if (Trim (sTestData) != "") [ ] // ListAppend (lsPlanInfo,"{sIndentation2}#testdata: {sFormattedData}") [ ] ListAppend (lsPlanInfo,"{sIndentation2}#testcase: {sTestCase}({sFormattedData})") [ ] [+] else [ ] Print ("Not Considering line: {sRexLine}") [ ] [ ] return bResult [+] public void TestPlanWrite(STRING sPlanFile, ANYTYPE aMsg) [ ] // To write content into log file [ ] HFILE hFile [ ] STRING sItem [ ] [ ] hFile = FileOpen (sPlanFile, FM_APPEND) [+] switch TypeOf (aMsg) [+] case STRING [ ] FileWriteLine(hFile,"{aMsg}") [+] case LIST OF STRING [+] for each sItem in aMsg [ ] FileWriteLine(hFile,"{sItem}") [+] default [ ] Print ("Non supported element for TestPlanWrite: {TypeOf (aMsg)}") [ ] FileWriteLine(hFile,"{aMsg}") [ ] [ ] FileClose (hFile) [ ] [ ] [+] VOID ProcessSingleREXFile (String sRexFile, STRING sPlanFile) [ ] // To create a testplan [ ] // Implemented for Auto Scripts [ ] // It will read the text file [ ] [+] // Parsing REX file and then writing into plan file [ ] HFILE hInFile [ ] STRING sLine [ ] LIST OF STRING lsPlan [ ] [ ] hInFile = FileOpen (sRexFile,FM_READ) [ ] [+] while (FileReadLine (hInFile, sLine)) [+] if (GetFailedTestInfo (sLine,lsPlan)) [ ] TestPlanWrite (sPlanFile,lsPlan) [ ] [ ] FileClose (hInFile)

Wednesday, August 27, 2008

Restart Silktest Agent at Runtime

Last few months, I faced one issue and solved it by restarting silktest Agent.
Problem
We have a silktest suite for our Excel AddIn. It is developed by DotNet Framework. Silktest DotNet extension goes off after running 75-200 tests. Also facing this issue differently for both Excel 2003 and Excel 2007. Already I raised one post 'Application not responding" for this.



[ ] *** Error: Application is not responding
[ ] Occurred in Exists
[ ] Called from MSExcelAddIns at ExcelRecoverySystem.inc(573)
[ ] Called from ASCS_EAIBaseState at ExcelRecoverySystem.inc(684)
[ ] Called from SymmetricReport at ExcelRecoverySystem.inc(714)
[ ] Called from TestcaseEnter at ExcelRecoverySystem.inc(255)
[ ] Called from PreservingFunctions_ReplaceWithUpper at PreservingFunctions.t(238)
[ ] Error E_APP_NOT_RESPONDING) raised. Closing all applications
[ ] *** Error: Application is not responding
[ ] Occurred in Exists
[ ] Called from KillExcelApp at ExcelRecoverySystem.inc(395)
[ ] Called from CloseAllApps at ExcelRecoverySystem.inc(386)



Solution:
Later selected cases are executed fine, If I close silktest agent and re-run few cases. I am able to figure out, where/when it is not able to identify. Then I tried to restart the agent in that machine, while scripts are executing continuously.

4Test code: To restart Silktest Agent


[-] void RestartSilkAgent ()
[ ] // To Restart Silktest Agent
[ ]
[ ] STRING sAgent
[ ]
[ ]
[ ] sAgent = GetMachineName ()
[ ] Print ("Agent name: {sAgent}")
[ ] Print (Desktop.GetActive ())
[ ] Disconnect (sAgent)
[ ]
[ ] Print ("**** Restarting Silktest Agent ...")
[ ] SYS_Execute ("D:\SampleDotNet\RestartAgent.bat")
[ ] Print ("**** Restarted Silktest Agent @@@@@@")
[ ]
[ ] Connect (sAgent)
[ ] Print (Desktop.GetActive ())
[ ]
[ ]

Friday, August 15, 2008

SilkTest - Convert String to List of String

Last month, my friend asked a silktest function similar to Split in QTP. Silktest does not have any built-in function. I thought to develop a function for this need. See the 4test code below:

4Test Code - Convert STRING contents as List of STRING

[+] List of STRING SplitToList (String sInput, String sDelimiter) [ ] List of STRING lsReturn = {} [ ] Integer iIndex =1 [ ] [+] while (GetField (sInput,sDelimiter,iIndex) != "") [ ] ListAppend (lsReturn, GetField (sInput,sDelimiter,iIndex)) [ ] iIndex++ [ ] [ ] return lsReturn

Sunday, August 3, 2008

Silktest - Date Puzzle

I am always interested to participate in code competition. Recently I solved one puzzle like that.

Puzzle
Develop an algorithm to display the day of the week (Sunday to Saturday) for a given date. For example, if the date given is 07/07/2008 (8th July 2008, dd/mm/yyyy format), the algorithm would return Monday. Date 29/02/2008 will return Friday.

Solution - 4test code

[+] testcase Puzzle_4Test (STRING sGivenDate) appstate none [ ] // Puzzle: [ ] // Develop an alogrithm to display the day of the week (Sunday to Saturday) for a given date. [ ] // For example, if the date given is 07/07/2008 (8th July 2008, dd/mm/yyyy format), the algorithm would return Monday. [ ] // Date 29/02/2008 will return Friday. [ ] INTEGER iGivenYear, iGivenMonth, iGivenDay [ ] DATETIME dtFormat [ ] STRING sResult [ ] [ ] STRING sSeperator = "/" [ ] STRING sFormatRequired = "dddd" // To get the day in word [ ] [+] do [ ] [ ] iGivenDay = Val (GetField (sGivenDate,sSeperator,1)) [ ] iGivenMonth = Val (GetField (sGivenDate,sSeperator,2)) [ ] iGivenYear = Val (GetField (sGivenDate,sSeperator,3)) [ ] [ ] dtFormat = MakeDateTime (iGivenYear,iGivenMonth, iGivenDay) [ ] sResult = FormatDateTime (dtFormat,sFormatRequired) [ ] Print ("Puzzle1: Input - {sGivenDate}: Result - {sResult}") [+] except [ ] LogError ("Puzzle1: Input - {sGivenDate} is not in expected Format dd/mm/yyyy")

Tuesday, July 15, 2008

Silktest - File Download window

Sometimes Silktest is not identifying FileDownload objects properly. To save it, we need to use TypeKeys. I used following code snippet to save a file from Browser.

Sample 4Test code



[+] Boolean SaveFile (String sFile)
[ ] Boolean bResult = FALSE
[+] do
[+] if (FileDownload.Exists(1))
[ ] Print ("FileDownload exists.")
[ ] FileDownload.SetActive ()
[ ] Sleep (1)
[ ] FileDownload.Save.Click (1,10,3)
[ ] Sleep (3)
[ ]
[ ] Window wActive = Desktop.GetActive ()
[ ] Print ("Window: {wActive}")
[ ] // DialogBox("File Download").DialogBox("Save As")
[ ] wActive.TypeKeys (sFile)
[ ] wActive.TypeKeys ("", 1)
[ ] wActive.TypeKeys ("", 1)
[ ] wActive.TypeKeys ("S",1)
[ ]
[ ] bResult = TRUE

[+] else
[ ] Print ("BrowserFileDownload does not exist.")
[+] except
[ ] ExceptLog ()
[ ]
[ ] return bResult
[ ]

Monday, June 16, 2008

4Test - Getting IP address

In automation, sometimes we need to find the tricks to achieve it. Like that I have done to find the IP address of a machine. You can see the following code snippet.

Silktest code - To find IP address of a system

[+] public String GetIpAddress(String sMachineName) [ ] //To get IP Address for the particular machine in Network [ ] List of String lsOutput [ ] String sCommand [ ] String sTemp, sItem [ ] String sResult = NULL [ ] Boolean bResult = FALSE [ ] Integer iPos1, iPos2 [ ] [ ] sCommand = "ping -a {sMachineName}" [ ] Sys_Execute (sCommand,lsOutput) [ ] [ ] //ListPrint (lsOutput) [-] for each sItem in lsOutput [-] if (MatchStr("*pinging*", sItem)) [ ] bResult = TRUE [ ] break [ ] [-] if (bResult) [ ] iPos1 = StrPos ("[", sItem) [ ] iPos2 = StrPos ("]", sItem) [-] if ((iPos1 > 0) && (iPos2 > 0)) [ ] sResult = SubStr(sItem,iPos1+1, iPos2-iPos1-1) [ ] Print ("Found IP Address: {sResult}") [ ] return sResult

Monday, June 9, 2008

SilkTest - Make sublist from a list

I have written a function to get sublist from a list of items. I have done for STRING type. You can try for ANYTYPE data type.Its usage is similar to SubString. See the following code snippet.

Silktest code sample: GetSubList

[+] public LIST OF STRING GetSubList(LIST OF STRING lsInput, STRING sFirst optional, STRING sLast optional, Boolean bMatch optional) [ ] //To get String list between sFirst and sLast [ ] //If sFirst is NULL or "", SubList will be taken from first item of list [ ] //If sSecond is Null or "", SubList will be taken upto last item of list [ ] //bMatch - FALSE means exact match, TRUE means Partial Match [ ] Integer iCount, iItem [ ] Boolean bFirst = FALSE [ ] Boolean bLast = FALSE [ ] LIST OF STRING lsReturn = {} [ ] [-] if (IsNull(bMatch)) [ ] bMatch = FALSE [-] if (IsNull(sFirst) || (sFirst == "")) [ ] bFirst = TRUE [ ] [ ] iCount = ListCount(lsInput) [-] for iItem=1 to iCount [-] if !(bFirst) [-] if !(bMatch) [-] if (sFirst == lsInput[iItem]) [ ] bFirst = TRUE [ ] ListAppend(lsReturn,lsInput[iItem]) [-] else [-] if (Len(sFirst) <= Len(lsInput[iItem])) [-] if (MatchStr("*{sFirst}*",lsInput[iItem])) [ ] bFirst = TRUE [ ] ListAppend(lsReturn,lsInput[iItem]) [+] else [-] if !(bLast) [ ] ListAppend(lsReturn,lsInput[iItem]) [-] if !(IsNull(sLast)) [-] if !(bMatch) [-] if (sLast == lsInput[iItem]) [ ] bLast = TRUE [-] else [-] if (MatchStr("*{sLast}*",lsInput[iItem])) [ ] bLast = TRUE [-] else [ ] break //Exit from for loop [ ] [ ] return lsReturn [ ]

Wednesday, June 4, 2008

Silktest - File Handling

Any automation suite must have file handling functions for various scenarios. It may be just text files or any data files. Silktest also has few methods for file handling.

SYS_FileOpen is executed by the Agent process and not by the SilkTest host process. But it is essentially the same as FileOpen. SYS_FileOpen and SYS_FileClose should be used to do file operations in other machines (while the agents are running from other machines ), not in the host machine. Below few 4test code samples are given.

4Test Sample Code: To Read a text file.

[+] public void ReadTxtFile(STRING sFile) [ ] // Purpose: Read contents of a file. [ ] HFILE hFile [ ] String sLine [ ] [ ] hFile = FileOpen (sFile, FM_READ) [ ] Print ("File: {sFile}") [ ] [-] while (FileReadLine (hFile, sLine)) [ ] Print (sLine) [ ] [ ] FileClose (hFile) [ ]

4Test Sample Code: To Create a text file.
[+] public void CreateTxtFile(STRING sFile, STRING sMsg) [ ] // Purpose: Create a txt file. All contents will be removed [ ] // from that file, if that file exists already. [ ] HFILE hFile [ ] String sLine [ ] [ ] hFile = FileOpen (sFile, FM_WRITE) [ ] FileWriteLine (hFile, sMsg) [ ] FileClose (hFile)

SilkTest Sample Code: To append a text file.
[+] public void AppendTxtFile(STRING sFile, STRING sMsg) [ ] // Purpose: Create a txt file. Given string will be appended [ ] // from last line of the file, if that file exists already. [ ] HFILE hFile [ ] String sLine [ ] [ ] hFile = FileOpen (sFile, FM_APPEND) [ ] FileWriteLine (hFile, sMsg) [ ] FileClose (hFile) [ ]

Silk Test Sample Code: To Delete a text file.
[-] void DeleteFile (String sFileName) [ ] // To delete given file, if it exists [-] if (Sys_FileExists(sFileName)) [ ] Print ("Existing file - {sFileName}") [ ] Sys_RemoveFile (sFileName) [ ] Sleep (0.1) [-] if (Sys_FileExists(sFileName)) [ ] Print ("Could not delete file - {sFileName}") [-] else [ ] Print ("Deleted file - {sFileName}") [-] else [ ] Print ("File {sFileName} does not exist.")

Silktest Sample Code: To Separate filename and path.
[+] public void GetFileNameAndPath (String sFileWithPath, inout String sFileName null optional, inout String sFilePath null optional) [ ] // Purpose: To separate filname and path. [ ] String sTmpFile, sTmpPath, sTemp [ ] Integer iPos,iCount = 0 [ ] [ ] sTemp = sFileWithPath [ ] iPos = strPos ("\",sTemp, TRUE) [-] if (iPos > 0) [ ] sFileName = Substr (sTemp,iPos + 1) [ ] sFilePath = Left (sTemp,iPos -1) [-] else [ ] Print (" File {sFileWithPath} does not have File Separator")

Friday, May 30, 2008

Silktest - String Match against a List

Silktest has MatchStr function to compare one string with another. Here you can use pattern. But Silktest does not have a built-in function to match a item by a pattern with a List of items. I have used this scenario in many places of the code. Code snippet is given below.

4Test Code: To Match a string against List

[-] public Integer MatchList(String sPattern, LIST OF STRING lsInput) [ ] //To match one string with any item in list of strings [ ] //Returns the item value(integer) [ ] Integer iCount, iItem [ ] String sData, sTemp [ ] Integer iReturn = 0 [ ] [ ] iCount = ListCount(lsInput) [-] for iItem=1 to iCount [-] if (MatchStr(sPattern,lsInput[iItem])) [ ] iReturn = iItem [ ] break [ ] [ ] return iReturn

Thursday, May 29, 2008

Silktest - Classic 4Test and Visual 4Test

I think that many of the silktest automation engineers do not know, Silkest has two outline editors. Visual 4Test, enabled by default, is similar to Visual C++ and contains colors.

Classic 4Test is one of the two outline editors you can use with SilkTest. Classic 4Test is similar to C and does not contain colors.

Below I have given the samples for both type of modes. To change editor modes, click Edit Menu -> "Visual 4Test" to select or clear the check mark. You can also specify your editor mode on the General Options dialog.

Sample Classic 4Test - Silktest Code



public LIST OF WINDOW GetChildObjects(Window wContainer, DATACLASS dcObject)
{
// To get All child objects.
// Used recursive method.
LIST OF WINDOW lwndObjects, lwTemp1, lwTemp2;
LIST OF WINDOW lwndChildren =
{
};
WINDOW wParent, wChild, wTemp;

do
{
if (wContainer.Exists (10))
{
lwndChildren = wContainer.GetChildren (TRUE, FALSE);

for each wChild in lwndChildren
{
if wChild.IsOfClass(dcObject)
{
ListAppend (lwndObjects,wChild);
}
else
{
lwTemp1 = wChild.GetChildren(TRUE, FALSE);
if (ListCount(lwTemp1) > 1)
{
lwTemp2 = GetChildObjects(wChild,dcObject); //To get particular objects
if (ListCount(lwTemp2) > 0)
{
ListMerge (lwndObjects, lwTemp2);
}
}
}
}
}
else
{
Print ("Container {[STRING]wContainer} window is not available.");
}
}
except
{
ExceptLog ();
}

return lwndChildren;
}


Sample Visual 4Test - Silktest Code


[+] public LIST OF WINDOW GetChildObjects(Window wContainer, DATACLASS dcObject)
[ ] // To get All child objects.
[ ] // Used recursive method.
[ ] LIST OF WINDOW lwndObjects, lwTemp1, lwTemp2
[ ] LIST OF WINDOW lwndChildren = {...}
[ ] WINDOW wParent, wChild, wTemp
[ ]
[-] do
[-] if (wContainer.Exists (10))
[ ] lwndChildren = wContainer.GetChildren (TRUE, FALSE)
[ ]
[-] for each wChild in lwndChildren
[-] if wChild.IsOfClass(dcObject)
[ ] ListAppend (lwndObjects,wChild)
[-] else
[ ] lwTemp1 = wChild.GetChildren(TRUE, FALSE)
[-] if (ListCount(lwTemp1) > 1)
[ ] lwTemp2 = GetChildObjects(wChild,dcObject) //To get particular objects
[-] if (ListCount(lwTemp2) > 0)
[ ] ListMerge (lwndObjects, lwTemp2)
[-] else
[ ] Print ("Container {[STRING]wContainer} window is not available.")
[+] except
[ ] ExceptLog ()
[ ]
[ ] return lwndChildren

Friday, May 16, 2008

SilkTest - TimeStamp for Current time

In Previous post, I have given the code to get TimeStamps from TSL (Winrunner) code. Now the same feature is given in Silktest (4Test) Code. It will be useful to create unique files and set the DateTime info whenever needed. Below I have given the 4Test ( Silktest scripting ) code snippet for timestamps.

4Test Code: TimeStamp for Current time



[+] public void GetCurrentDateTime(out String sDate optional, out String sTime optional,String sDateFormat null optional,String sTimeFormat null optional)
[ ] // Purpose: Current date and time are taken from the system.
[ ] DateTime dtmCurrent
[ ]
[+] if (IsNull(sDateFormat))
[ ] sDateFormat = "mm/dd/yyyy"
[+] if (IsNull (sTimeFormat))
[ ] sTimeFormat = "hh:nn:ss AM/PM"
[ ] dtmCurrent = GetDateTime ( )
[ ] sTime=FormatDateTime (dtmCurrent, sTimeFormat)
[ ] sDate=FormatDateTime (dtmCurrent, sDateFormat)
[+] String GetTimeStamp()
[ ] //Purpose: To get current time stamp in the given format
[ ] String sDate, sTime
[ ] String sTcFile
[ ] STRING sPrefix
[ ]
[ ] GetCurrentDateTime (sDate, sTime,"yyyymmdd","hhnnss" )
[ ] sPrefix = "{sDate}{sTime}"
[ ] return sPrefix

Wednesday, April 30, 2008

Accessing Excel - SilkTest

Few tools are providing built-in functions to read and write the data from Excel. Testers are comfortable with Excel than text file formats.

Silktest does not have any built-in functions to access data from Excel. But you can retrieve the data from Excel by treating Excel as Database. By using below code snippet, you can access the Excel data without pre-defined DSN. For this code snipper, You need to provide Excel filename with full path and worksheet name.

Silktest Excel - Code:

[+] public void ProcessExcelData(STRING sExcelFile, String sExcelSheet) [ ] // Purpose: Drives test suite based on excel sheet(testcase) information. [ ] // Executes for given worksheet. [ ] //SQL declaration [ ] HANDLE hDB [ ] HANDLE hSQL [ ] List of STRING glsData //To get testdata [ ] [ ] Print ("Test data:{sExcelFile} & Worksheet: {sExcelSheet} ") [ ] [-] do [ ] hDB = DB_Connect ("DRIVER=Microsoft Excel Driver (*.xls);DRIVERID=790;FIRSTROWHASNAMES=1;READONLY=FALSE;DBQ={sExcelFile}") [ ] [ ] //execute a SQL statement [ ] hSQL = DB_ExecuteSQL (hDB, "SELECT * from [{sExcelSheet}$]") [ ] //while there are still rows to retrieve [-] while DB_FetchNext (hSQL, glsData) [ ] GetListData (glsData) //Get all data without null [ ] [ ] [ ] //clean up the query [ ] DB_FinishSql (hSQL) [ ] [ ] //disconnect from the database [ ] DB_Disconnect (hDB) [ ] [-] except [ ] ExceptLog() [ ] Print ("Excelsheet {sExcelFile} couldn't be accessed by SilkTest.")

Friday, April 25, 2008

Loading a URL - Silktest

Silktest has two methods LoadPage and Navigate to load particular page or URL. Sometimes our project may have modal popups like network authentication or Certificate Security (SSL) popups before loading the page. At that time we can not use LoadPage and Navigate methods. Silktest is used to expect the browser, should be ready. In case of modal dialog box, browser will be active if the modal dialog box is closed.

To solve this problem, we need to type the URL and then hit ENTER key in the browser. Then verify for the possible popups and do appropriate actions. Few people might be using SetTrap and ClearTrap. Trapping can be done for the popups, which are not required any inputs. Below I have given a code snippet.

Code:



[ ] Browser.SetActive ()
[ ] Browser.Maximize()
[ ] Browser.Location.SetText ("{sUrl}")
[ ] Browser.Location.TypeKeys ("")
[ ] Sleep (2)
[+] if (BrowserSecurityInfo.Exists(5))
[ ] BrowserSecurityInfo.SetActive ()
[ ] Print ("BrowserSecurity Info Exists.")
[ ] BrowserSecurityInfo.Continue.Click ()
[+] if (BrowserAuthentication.Exists(5))
[ ] BrowserAuthentication.SetActive ()
[ ] BrowserAuthentication.UserName.SetText (sUsername)
[ ] BrowserAuthentication.Password.SetText (sPassword)
[ ] BrowserAuthentication.OK.Click ()

Wednesday, April 16, 2008

Access database without DSN

Developers used to write the code to retrieve the data from database, with the help of DSN (Data Source Name). Developers does not bother about the type of database. DSN is the bridge between database and scripting language.

Assume that your automation scripts are using a DSN. It is difficult to configure DSN, whenever the script runs. But you can set the DSN details dynamically to connect with any database. Below I have given the sample silktest (4test) code to run the script without having physical DSN.

4test code:



[+] void GetAccessDB ()
[ ] STRING CONN_STRING = "Driver=" + Chr(123) + "Microsoft Access Driver (*.mdb)" + Chr(125) + ";Dbq=\\AppServer\build05.mdb;Mode=16;"
[ ] HANDLE dbConn
[ ] HANDLE hSQL
[ ]
[ ] dbConn = DB_Connect(CONN_STRING)
[ ] hSQL=DB_ExecuteSql(dbConn, "Select * from Emp_Master")
[ ]
[ ] DB_FinishSql (hSQL)
[ ] DB_Disconnect (dbConn)

Saturday, April 12, 2008

HtmlText object not a Parent

Three years ago, we have upgraded Silktest version to 6.5. At that time, Silktest identified HtmlText objects as parent objects. We changed our scripts lot and it was difficult to manage the scripts release by release. Then I found that we need to set a Agent option in Silktest. You can avoid this by two ways.


  • By coding. You need to use this statement after invoking the browser object => BrowserPage.SetUserOption("ShowOverflow", FALSE,USEROPT_DEFAULT)

  • By configuration. Add ShowOverflow=FALSE under [Options] in extend\domex.ini

Wednesday, March 12, 2008

4test - Search and Replace

One project required to replace certain tags at every build. I written this function SearchAndReplaceInFile. This code snippet to search and replace strings in a file.

Code:



[+] public void SearchAndReplaceInFile (STRING sFileInput, STRING sFileOutput, STRING sSearch, STRING sReplace )
HFILE hInFile, hOutFile
STRING sTemp, sLine, sValue
INTEGER iPos1, iPos2

hInFile = FileOpen (sFileInput,FM_READ)
hOutFile = FileOpen (sFileOutput, FM_WRITE)

[-] while (FileReadLine (hInFile, sLine))
sTemp = sLine
[-] if !(Trim(sSearch) == Trim (sReplace))
ReadLine:
iPos1 = StrPos (sSearch,sTemp)
//Print ("Position {sTemp} - {sSearch} : {iPos1}")
[-] if (iPos1 > 0)
sValue = StrTran (sTemp, sSearch, sReplace)
//Print ("got value: {sValue}")
sTemp = sValue
goto ReadLine
FileWriteLine(hOutFile,sTemp)
FileClose (hInFile)
FileClose (hOutFile)

Friday, March 7, 2008

Recursive technique

I am very much interested to include the recursive technique. It is simplifying the code and reduce the number of lines. You can get the definition on Wiki. Below I have given the sample 4test code. This code snippet will get child objects from the given container object.



[+] public LIST OF WINDOW GetChildObjects(Window wContainer, DATACLASS dcObject)
// To get All child objects.
// Used recursive method.
LIST OF WINDOW lwndObjects, lwTemp1, lwTemp2
LIST OF WINDOW lwndChildren = {...}
WINDOW wParent, wChild, wTemp

[+] do
[+] if (wContainer.Exists (10))
lwndChildren = wContainer.GetChildren (TRUE, FALSE)

[+] for each wChild in lwndChildren
[+] if wChild.IsOfClass(dcObject)
ListAppend (lwndObjects,wChild)
[+] else
lwTemp1 = wChild.GetChildren(TRUE, FALSE)
[+] if (ListCount(lwTemp1) > 1)
lwTemp2 = GetChildObjects(wChild,dcObject) //To get particular objects
[+] if (ListCount(lwTemp2) > 0)
ListMerge (lwndObjects, lwTemp2)
[+] else
Print ("Container {[STRING]wContainer} window is not available.")
[+] except
ExceptLog ()

return lwndChildren