Wednesday, December 29, 2010

Excel Automation Using VBScript

Using VBScript, we can automate most of the Excel verification activities. In one project we can export reports to Excel. I have to verify the cell value, font color and Background color. It is difficult task to verify each cell property by any GUI testing tool. All tools are used to identify Excel Grid (Workbook) as Custom Object. I am using VBScript to read the excel contents. Another advantage, you can use the VBScript against different versions of Excel such as 2002, 2003 and 2007. But you need to change the code for Excel 2003 and 2007, if you have done by using GUI objects.

Below I put one Visual Basic script code. It reads the given excel file and put the details of each cell into a log file. Copy all contents from below textbox and save it as MyExcel.vbs and try to run this VBS file. You can run this script by using any GUI Testing tool. Command line call should be cscript MyExcel.vbs sExcelFile iStartRow iStartCol iEndRow iEndCol iSheetIndex

To Know more about this VBA Help, download help from this link Microsoft Office 2003 Editions: Excel VBA Language Reference

If you are unable to run any VBScript, See my earlier post Unable to run VBS or CScript in Windows XP .

VB Script to Read Excel Contents

' USAGE: MyExcel.vbs "D:\VB\Complex.xls" iStartRow iStartCol iEndRow iEndCol iSheetIndex
'cscript MyExcel.vbs "D:\VB\Complex.xls" 1 1 30 12 2

'******** Variables Declaration
' Files section
'XLS File name
gsFile="D:\VB\Complex.xls" 'File with macros
gsLogFile="D:\VB\Results_vbs.log"

Dim gsExcelFile, giStartRow, giStartCol, giEndRow, giEndCol, giSheetIndex
Dim gsResultsFile 'Text file name
gsDirSeparator = "\" 'Directory separator character


If WScript.Arguments.Count = 6 Then
gsExcelFile = WScript.Arguments.Item(0)
giStartRow = CInt (WScript.Arguments.Item(1))
giStartCol = CInt (WScript.Arguments.Item(2))
giEndRow = CInt (WScript.Arguments.Item (3))
giEndCol = CInt (WScript.Arguments.Item (4))
giSheetIndex = CInt (WScript.Arguments.Item (5))
'To Read the Excel file
'ReadExcel gsFile, 1, 1, 30, 12, 2
'WScript.Echo "ReadExcel " , gsExcelFile, giStartRow, giStartCol, giEndRow, giEndCol, giSheetIndex
ReadExcel gsExcelFile, giStartRow, giStartCol, giEndRow, giEndCol, giSheetIndex

Else
'WScript.Echo "Usage: MyExcel.vbs sExcelFile iStartRow iStartCol iEndRow iEndCol iSheetIndex"
'WScript.Quit
ReadExcel gsFile, 1, 1, 30, 12, 2
End If

'ReadExcel gsFile, 1, 1, 30, 12, 2

'---------------------------------
' Method : ReadExcel
' Author : T. Palani Selvam
' Purpose : Reading Excel contents.
' Parameters: - Nil
' Returns : - Nil
' Caller : - Nil
' Calls : - Nil

' Revision History:
'
' [No] da-mon-year Name: Action:
' [ 1] 07-Nov-2007 Palani Created first version
'---------------------------------
Sub ReadExcel(sExcelFile, iStartRow, iStartCol, iEndRow, iEndCol, iSheetIndex)

'WScript.Echo "ReadExcel " , sExcelFile, iStartRow, iStartCol, iEndRow, iEndCol, iSheetIndex
'ReadExcel(sExcelFile As Variant, iStartRow As Integer, iStartCol As Integer, iEndRow As Integer, iEndCol As Integer,iSheetIndex As Integer)

' Purpose: For Excel verification
' To Read the Excel and write into a file
' Each cell content
' Each cell - Foreground color, font name, font style, font size and Background color.


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 sCellValue 'As Variant
Dim sShowCellValue 'As Variant
Dim sFontName 'As Variant
Dim sFontStyle 'As Variant
Dim iFontSize 'As Variant
Dim iBackColorIndex 'As Variant
Dim iForeColorIndex 'As Variant
Dim iBackColorIndex2 'As Variant
Dim iForeColorIndex2 'As Variant
Dim sResult 'As Variant


' 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:\VB\Contacts.xls"
Else
sExcelPath = sExcelFile
End If

if (iSheetIndex = "") Then
iSheetIndex =1
End If


FileDeleteAndCreate (gsLogFile)

'XL file check
If (FileExists (sExcelPath) <> 0) Then
LogWrite ("The Excel file " & Chr(34) & sExcelPath & Chr(34) & " does not exit!")
'WScript.Echo "The Excel file, " & Chr(34) & sExcelPath & Chr(34) & " does not exit!"
'WScript.Quit
Else
LogWrite ("The XL file " & sExcelPath & " exists.")
End If

Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Open sExcelPath, False, True
'WScript.Echo "Reading data from " & sExcelPath
' objExcel.ExecuteExcel4Macro

'On Error GoTo ErrorHandler1
On Error Resume Next


WorkSheetCount = objExcel.Worksheets.Count
'WScript.Echo "We have " & WorkSheetCount & " worksheets."
'Set objXLWorkbook = objExcel.Workbooks(1)
Set objXLWorkbook = objExcel.ActiveWorkbook
'objXLWorkbook.RunAutoMacros

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


iUsedRowsCount = iEndRow 'CurrentWorkSheet.UsedRange.Rows.Count
iUsedColsCount = iEndCol 'CurrentWorkSheet.UsedRange.Columns.Count
iTop = iStartRow 'CurrentWorkSheet.UsedRange.Row
iLeft = iStartCol 'CurrentWorkSheet.UsedRange.Column

' Cells object
CurrentWorkSheet.Cells.Activate

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

sResult = ""

Set objCurrentCell = CurrentWorkSheet.Cells(iRow, iCol)
sCellValue = objCurrentCell.Value

'If ((sCellValue = empty) Or (sCellValue = "empty")) Then
If ((sCellValue = empty)) Then
sCellValue = "empty"
Else
Set objFont = objCurrentCell.Font
sFontName = objFont.Name

sFontStyle = objFont.FontStyle
iFontSize = objFont.Size
iForeColorIndex = objFont.Color
iForeColorIndex2 = objFont.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 (iForeColorIndex = Empty) Then
iForeColorIndex = "99999999"
End If
If (iForeColorIndex2 = Empty) Then
iForeColorIndex2 = "99999999"
End If
sResult = "Reading Cell {" & CStr(iRow) & "," & CStr(iCol) & "}," & sCellValue & "," & sFontName & "," & CStr(sFontStyle) & "," & CStr(iFontSize) & "," & CStr(iForeColorIndex) & "," & CStr(iForeColorIndex2)

LogWrite (sResult)

End If
Set objCurrentCell = Nothing

Next

Next

' 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

'---------------------------------
' Method : Logwrite
' Author : T. Palani Selvam
' Purpose : Append the given message into Log file.
' Parameters: sMsg - String, Contains logging message.
' Returns : - Nil
' Caller : - Nil
' Calls : - Nil

' Revision History:
'
' [No] da-mon-year Name: Action:
' [ 1] 07-Nov-2007 Palani Created first version
'---------------------------------
Sub LogWrite(sMsg)
Const ForAppending = 8
'FileName = "D:\VBs\Mysamples\1create.txt"

Set objFSO = CreateObject("scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile (gsLogFile, ForAppending, True)

objTextFile.WriteLine date & " " & time & ": " & sMsg
objTextFile.Close

Set objTextFile = Nothing
Set objFSO = Nothing
End Sub

'---------------------------------
' Method : FileExists
' Author : T. Palani Selvam
' Purpose : Checks the given file is avialable or not.
' Parameters: - Nil
' Returns : - Returns As Boolean
' Caller : - Nil
' Calls : - Nil
'---------------------------------
Function FileExists(strPathName)
'return 0 if a file exists else -1
Dim ObjFSO

Set ObjFSO = CreateObject("Scripting.FileSystemObject")

if ObjFSO.FileExists(strPathName) = False then
FileExists = -1
else
FileExists = 0
end If

Set ObjFSO = Nothing
End Function

'---------------------------------
' Method : FileDeleteAndCreate
' Author : T. Palani Selvam
' Purpose : To delete the file if exists..
' Parameters: - Nil
' Returns : - Returns As Boolean
' Caller : - Nil
' Calls : - Nil
'---------------------------------
Function FileDeleteAndCreate(strFileName)
' delete
Set objFSO = CreateObject("Scripting.FileSystemObject")

On Error Resume Next
Set objTextFile = objFSO.GetFile(strFileName)
objTextFile.Delete

Set objTextFile = objFSO.CreateTextFile(strFileName)

objTextFile.Close
Set objTextFile = Nothing
Set objFSO = Nothing

End Function

'---------------------------------
' Method : Initialize
' Author : T. Palani Selvam
' Purpose : Initial actions & arrangements will be completed.
' Parameters: - Nil
' Returns : - Nil
' Caller : - Nil
' Calls : - Nil
'---------------------------------
Sub Initialize()
'CHECKING INPUT FILES ARE AVAILABLE OR NOT
gsLogFile = App.Path & "\Results.log"
End Sub

QTP - Descriptive Programming

QuickTestProfessional help refers Descriptive Programming as Programmatic description. Below given few info about Descriptive Programming.

Using Object Repository
When you record an operation on an object, QuickTest adds the appropriate test object to the Object Repository. Once the object exists in the Object Repository, you can add statements in the Expert View to perform additional methods on that object. To add these statements, you usually enter the logical name of each of the objects in the object's hierarchy as the object description, and then add the appropriate method.

Descriptive Programming (Programmatic Description) Usage
Programmatic description can be very useful if you want to perform an operation on an object that is not stored in the Object Repository. You can also use programmatic descriptions in order to perform the same operation on several objects with certain identical properties, or in order to perform an operation on an object whose properties match a description that you determine dynamically during the test run.

There are two types of programmatic descriptions:


  1. Static . You list the set of properties and values that describe the object directly in a VBScript statement.

  2. Dynamic . You add a collection of properties and values to a Description object, and then enter the Description object name in the statement.


Using the Static type to enter programmatic descriptions directly into your statements may be easier for basic object description needs. However, in most cases, using the Dynamic type provides more power, efficiency, and flexibility.

Useful Links :
Descriptive Programming by QTP Expert Tarun Lalwani

Sample QTP code for Descriptive Programming - Dynamic

Sample QTP code for Descriptive Programming - Static

Comparison between SilkTest and QuickTest Professional

Two months back, I thought to write a post about SilkTest and QTP comparison. Both the tools are market-leading testing tools. The latest versions of both tools have Vista and Flex support. I did not give any detailed description for each feature or item.

Product page
Here I have listed the product pages for both.
Silktest Product Page
Quick Test Professional Product page

Wiki pages
Silktest on Wiki
QuickTestProfessional (QTP) on Wiki

Code samples for both tools
Sample 4test code snippets for SilkTest
Sample QTP and VB Script code snippets

References:


  1. SILKTEST AND WINRUNNER FEATURE DESCRIPTIONS - By Horwath/Green/Lawler

  2. WinRunner vs. QuickTest Pro Quick Comparison - By Shawn LoPorto, Senior Test Automation Architect

  3. AUTOMATION TEST TOOLS - By Ray Robinson, 2001

  4. Comparision of Web testing tools



Comparison Table: SilkTest Vs QuickTest Professional


Features

SilkTest

QuickTest Professional

Recording ScriptRecorder available with different set of features.Recorder available with different set of features.
OS Windows upto Vista, Unix (SilkBean)Windows upto Vista, Unix (Xrunner)
Browsers supportInternet Explorer, Netscape, FireFox, AOLInternet Explorer, Netscape, FireFox, AOL
Database testsWith the help of DSN (ODBC32 Interface)With the help of DSN (ODBC32 Interface) plus VB Scripting
Data functionsGoodGood. Having extensive support for SpreadSheet (Excel).
Tests Termed as Testcase. Each Testcase has block of coding statements.Termed as Actions. Each Action has block of coding statements.
Test Script Script is a single file.Actually Script is a folder and have set of supporting files.
Code View Classic 4Test, Visual 4TestKeyword View, Expert View
Objects RepositoryOfficial term is Window declarations. They can be edited directly from the Editor. Maintained as separate file. With the help of utility, objects are modified. Two types as per QTP setting. They are 'Per Action Repository' and 'Shared Repository'. File extensions will be varied for each type.
Dynamic objectsObject properties can be passed dynamically. Variety of methods available to handle them. Object properties can be passed dynamically. Another term is known as Descriptive Programming.
Class Mapping Class Mapping is available.Class Mapping is available.
Custom ClassesRecorderClass and Extension Kit are available.Virutal Object Wizards available.
Image testingBitmap Capture and Verification functions.Bitmap Capture and Verification functions.
Test/Error RecoveryPowerful Recovery system available.Recovery Manager
VerificationProvided Verify and Verify Properties functions.Provided check points for different purposes.
Results ReportingResults are stored into *.res binary files. It can be converted into differnt formats. Multiple versions can be stored into single file.QTP results are stroed as XML files and can be converted to HTML files. Result folder contain many files. One result folder can store results for only one run.
Test Management Tool IntegrationIntegrated with SilkCentral Test Manager.Integrated with Quality Center.
Distributed TestingRemote Agent.Having Remote COM Agent.
DLL support Only Standard DLLs. It does not support the COM/ActiveX DLLs, which are created by VB/.NET.Both COM and Standard DLLs are supported.
Java SupportYesYes
Flex Support Available to certain extent.Available to certain extent.
DotNet SupportYes Yes
Internatioalization (i18N) Support YesYes
Timer functions Having rich set of functions to calculate time taken for block of statements or testcases. Help: TimersHaving limited functions to calculate time taken for block of statements or actions. Help: Measuring Transactions
Environment support Can access OS level variables.Can access OS level variables.
Batch RunSuite (*.s) and Test plan (*.pln) are available.Test Batch Runner utility.
Coding 4Test Language. Similar to Visual Basic
Ability to run multiple scripts consistantly and continuously. YesShould run from Quality Center.
Coding Style 4Test Language. Similar to C++ Visual Basic Script
Integration with External librariesNO VB Script libraries.
Code Samples Few samples from vendor. Few samples from vendor. But many VB Script samples available on Internet.
OOPs SupportYes. Oops concepts are supported for certain extent. User can extend standard classes.NO
Data types Set of data types are available. User can create their own data types also. Set of data types are available. User cannot create their own data types
Interactive DebuggingDebugging features available.Debugging steps available.
Ease of use Just record and playback, won't help. Medium. Record and playback used to help. Very Simple. Easy to learn.
DocumentationHLP file available. PDF docs are only for beginners.Both CHM and PDF files are available. Enough info.
Tool Updates Continuing process. Continuing process.
Cost~$9K More than $10K
Script Templates Manual. No Ways to create automatic templates. Manual. No Ways to create automatic templates.
EditorGood. Simple one. Having Project explorer similar to MS Visual Studio. Better one with nice look. But using tabs to show more than one script.
Tool Support Tool support is available for only latest versions (from silktest 8.0 ) Tool support is available for only latest versions.
Latest VersionSilktest 2008 QuickTest Professional 9.5
Strengths Good Development language, good online community, recovery system, Good cross browser support, Code Maintenance The most popular test tool by great user base, plenty of jobs, good online community, Good cross browser support.
Weaknesses Helpdesk, Slightly expensive, Skilled resourcesHelpdesk (Getting bad now), Expensive tool.
Vendor Borland. Initially developed by Segue. Borland acquired Segue on 2006. HP (Hewlett-Packard). Initially developed by Mercury Interactive. HP acquired Mercury on 2006.
Product Name Changes Initially QA Partner. Later changed to SilkTest.Initially Astra QuickTest. Later changed to QuickTest Professional.

VBScript - File Read and Write

I have developed few projects using Visual Basic. But I do not have much scripting in Visual Basic Script (VBS). In VB, the file handling functions are different than VBScript. We need to use FileSystemObject for file handling. Below I have given two code snippets to read and write into text files. This code can be used into Quick Test Professional also.

Reading a Text file



Const ForReading = 1, ForWriting = 2

FileName = "D:\VBs\Mysamples\1create.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")

If objFSO.FileExists(FileName) Then

Set objTextFile = objFSO.OpenTextFile(FileName, ForReading)

Do while Not objTextFile.AtEndOfStream
sLine = objTextFile.ReadLine
Wscript.Echo sLine
loop

End If

objTextFile.Close

Set objFile = Nothing
Set objFSO = Nothing


Writing to a Text file


Const ForAppending = 8
FileName = "D:\VB\Mysamples\1create.txt"

Set objFSO = CreateObject("scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile (FileName, ForAppending, True)

For iIndex=1 to 10
objTextFile.WriteLine(iIndex)
Next

objTextFile.Close

Set objTextFile = Nothing
Set objFSO = Nothing

Common Problems in Test Automation

Few years back, I have prepared few documents about automation scripting and concepts. This post will list the common problems faced by software industries in their test automation attempts.

Automation is not cheap
Test Automation is not cheap. Usually it takes between 3 to 10 times as long to create, verify and document the automated test as it takes to create and run once by hand. Test Automation takes lesser time to create than to test each test scripts.

Easy to run test alone is automated
Many test groups automate only the easy to run tests because early in testing, these are easy to design and the program might not be capable of running more complex test cases. Hence harsh test needs to be done by the skilled manual tester.

Duplicate information was kept in multiple repositories
Most of the project teams purchases a test management tool in addition to the already existing automated testing tools. Duplicate information was kept in multiple repositories and was very difficult to maintain. In several instances, the implementation of more tools actually results in less productivity.

Test Scripts duplicates the development effort
Test script development results in an almost complete duplication of the development effort, through overuse of the testing tool's programming language. In normal case the application itself used a complex algorithm and again the tester recreates these algorithms using the testing tool. Too much time was spent on automating scripts, without much additional value gained. The test team must be careful not to duplicate the development effort; this is a risk when developing elaborate test scripts.

A lack of test development guidelines was noted
One program had several test automation engineers, each using a different style for creating test scripts. Maintaining the scripts is a nightmare. This is due to the non-availability of development guidelines and hence script readability and maintainability becomes complicated.

Reports generated by the tool is futile
More time is spent by the testers in setting up elaborate customized reports, which is part of the automated testing tool. The reports were never used, since the data required for the report is never accumulated in the tool.

Web Testing & Client server testing

Server process:

 Server programs generally receive requests from client programs, execute database retrieval
and updates, manage data integrity
and dispatch responses to client requests. The serverprocess acts as a software engine
that manages shared resources such as databases, printers, communication links, or high
powered-processors.It is the backend process of the application.

Client process:

Client programs usually manage the user-interface portion of theapplication, validate data
entered by the user, dispatch requests toserver programs, and sometimes execute business logic.
The client-based process is the front-end of the application.It is the interaction between the user and the rest of the application
system.



In client server testing test engineer are conduct the following testings:-

1.Behaviour testing(GUI TESTING)

2.Input domain testing

3.Error Handling testing

4.Backend testing

In Web testing test engineer are condut the following testings:-

1.Behaviour Testing

2.Static web testing

3.Input domain testing

4.Backend testing

5.Error handling testing

5.Frame Level testing


Difference between Application server and Web server:

Application server

Web server

Developers can create, test, and execute application components

It is designed to create and deploy Web site, serving up content more so than applications.

These are typically J2EE-based, running EJBs or other Java components.

It supports JSP,servlets and ASP

Application servers are designed to create true applications with complex business logic,

Web servers are technology designed to create and deploy Web site serving
up content more so than applications, serving

Application Server supports HTTP,TCP/IP and many more protocols.

A Web Server understands and supports only HTTP protocol

Test Results Reporting

Results Reporting is very much important as automating functionalities. It will be better, if results are logged with screen shots for failed cases. Most of us, not concentrating much on Results Reporting. It will improve your automation level higher.

Automation Engineers are developing lot of test scripts. How will you check all scripts results? We can't check each testcase by testcase. Summary of test results is so important. Also the compiled results for all results is good to have.

Long back, I studied one article related with Automatic Results processing. That document discussed about extracting some keywords from particular log files and store the results in different format. I have implemented using Excel sheet and it will give result for each testcase(function) as well as compiled result for each scripts. If summary and results are stored into HTML files, we can easily get to know the results.

I agree, however one person need to look the results. Some of the tools are giving summary details after execution. I want to go one step ahead. I need to see all automation results of particular project from one file (HTML or Flat file or XL sheet). It is like maintaining history.

But Results processing is very common for test automation as well as general applications. You can follow like any standard log files format. You can maintain 2-3 log files for single script. One for all the activities of your suite and another one for Just giving Pass or Fail result for each testcase. It will be better, if all the log files are HTML files. At last prepare a single file to show the compiled results for the whole execution. You can publish the results easily.