Escolar Documentos
Profissional Documentos
Cultura Documentos
Po
PR -Dep nin
BE TIC ym
st Tu
AC lo g
ST ES en
: t
VOLUME 5 • ISSUE 9 • SEPTEMBER 2008 • $8.95 • www.stpmag.com
Earn Yo
ur Chops T
esting
Micros
of t App
s
Tools For
page 1
4
.NET You he
Didn’t Know a
T
nd yed
You Had Bui Q A le Pla facts
F or ld a Ro Arti
Stu Fram By
Dat rd y,
a-A Rep ework
pp
Tes etitive
ting
EG ISTER R
R NE FO
ONLI DMISSION!
FREE A TPCON.COM
S
WWW.
FALL
IS IT CRAZY TO WANT TO MEET
THE MAKERS OF THE LATEST
SOFTWARE TESTING TOOLS?
WE DON’T THINK SO, which is why we’ve gathered
the industry’s TOP COMPANIES in our Exhibit Hall!
;dg dkZg &% nZVgh! FjVa^IZhi ]Vh WZZc YZY^XViZY id YZa^kZg^c\ hjeZg^dg F6 VcY
iZhi^c\ hZgk^XZh id <adWVa [dgijcZ *%% XdbeVc^Zh hjX] Vh B^Xgdhd[i! >ciZa! <:!
KZg^odc! I"BdW^aZ! BdidgdaV! H^ZbZch VcY H6E#
FjVa^IZhi egdbdiZh \adWVa hiVcYVgYh hjX] Vh IE> VcY @9I dc V adXVa WVh^h!
ldg`^c\ XadhZan l^i] ndjg iZVb id ZchjgZ ndj YZa^kZg dc i^bZ VcY dc WjY\Zi#
L^i] V egdkZc gZXdgY d[ ZmXZaaZcXZ ^c egVXi^XZ! lZ Wg^c\ `cdlaZY\Z VcY
ZmeZg^ZcXZ id ndj " Z^i]Zg dch^iZ dg i]gdj\] dcZ d[ FjVa^IZhiÉh Dch]dgZ F6
8ZciZgh d[ :mXZaaZcXZ#
Contents A Publication
14
COV ER STORY
Disciplines for Attacking Apps
Running on the Microsoft Stack
While Windows, .NET, IIS and SQL Server might themselves seem stable,
once one fails, the rest can shatter like cement blocks. By Pete Jenney
A Sturdy Data
Depar t ments
31 Framework For
Repetitive Testing
7 • Editorial
Why the AOL development team takes a
different tack on testing.
8 • Contributors
Here’s a test harness that your team Get to know this month’s experts and the
can build that will simplify manipula- best practices they preach.
tion and maintenance of your test data.
By Vladimir Belorusets 9 • Feedback
The Role Of
37 Artifacts in QA
It’s your chance to tell us where to go.
42 • Future Test
A trainer of Microsoft testers breaks out of
the black box. By Bj Rollison
www.empirix.com/freedom
Ed Notes
Editor
VOLUME 5 • ISSUE 9 • SEPTEMBER 2008
Edward J. Correia
EDITORIAL
Editorial Director
Alan Zeichick
NBC and China’s
Top Coders
+1-631-421-4158 x100 +1-650-359-4763
ecorreia@bzmedia.com alan@bzmedia.com
ST&P. ý
calling 1-847-763-9692.
.com), which has built a market in delighted to have him writing for
which developers compete for prizes
Automated Import
Of Virtual Environs
Test-tools maker StackSafe in early August released an update
to Test Center, adding the ability to automatically import virtu-
alized environments and their components for staging, testing,
analysis and reporting, either alone or in combination with phys-
ical systems.
Introduced in January, Test Center employs virtualization
technology to give IT operations teams an easy way to simulate
multi-tiered systems and applications for testing and perform-
ance tuning, according to company claims.
As before, copies of imported environments are introduced
into a working infrastructure stack that simulates the produc-
tion configuration, enabling production-safe changes, regres-
sion testing, patch testing, security and risk assessment, diag-
nostics and root-cause analysis, emergency change testing, appli-
cation assembly and validation, and compliance reporting, the
company says. Test Center now automates VMware component imports.
Test Center benefits test teams, according to claims, by pro-
viding a “broad view of the entire IT operations infrastructure,” components such as databases, mainframes and other compo-
enabling testing across physical machines running Linux and nents that cannot yet be virtualized. The update is free to cur-
Windows, virtual machines set up with VMware and external rent licensees.
MS Terms of Endearment
The first day on the job at a Microsoft shop, of simultaneous connections. Developers typi-
you might hear something like this: “The cally write programs in C# or VB and connect
graphic designers are using Expression Web to SQL Server via ADO.NET.
and Silverlight, but the developers will just
take the HTML and put it in ASP, which we’ll TEAM FOUNDATION SERVER (TFS) /
test with Watir. Of course, we all collaborate A collaboration tool for the entire develop-
with VSTS.” ment team that includes version control,
“Er, I’m sorry, what?” might be your feeble Matt Heusser and reporting, analytics, and process management.
response, unless you’ve read this issue of Chris McMahon
ST&Pedia. The Microsoft Technology stack is VISUAL BASIC .NET (VB.NET) / The
a complex and sophisticated environment. .NET version of Visual Basic, an easy-to-use
Having a knowledge of this environment—
even a surface knowledge—can make you a
Q: What would your
answers be?
programming environment that allows pro-
grammers (and testers) to be productive
more effective and more valuable software Did you exhaustively test quickly.
tester. this? Are we doing an SVT
Here’s a broad introduction to the after our BVT? Does the More MS Stuff
Microsoft environment and some of its related performance testing pass? MSTEST / Integrated with Visual Studio
products. If you’re already .NET-savvy, feel What are your equivalence Professional, enables programmers to write
free to skip around. classes? Which heuristics low-level tests in their language of choice to
are you using? perform API testing. http://msdn.microsoft
Microsoft Tools and .NET Components .com/en-us/library /ms182489(VS.80).aspx
ADO.NET / A technology anyone can use to
connect programming code to a database.
A : ST&Pedia will help
you answer questions
WEBTEST / Software that records the
like these and earn the
respect you deserve. HTTP traffic that goes from the server to
ASP.NET / A framework that allows the Upcoming topics: the browser – it does not test the GUI.
developer to embed ‘snippets’ of code in Web http://msdn.microsoft.com/en-us/library
pages, for example, to populate a table from a October /ms364082 (VS.80).aspx
database. Visual Studio provides additional Security & Code Analysis
tools to view and edit the page without look- LOADTEST / Simulates simultaneous users
ing at code. November on a Web site using unit tests or existing
Testers Choice Awards
WebTest scripts. http://msdn.microsoft.com
C# (see-SHARP) / An object-oriented pro- December /en-us/ magazin /cc163592.aspx
gramming language based on C++ with influ- Test Automation
ences of Delphi and Java. Its code runs in a TEAM FOUNDATION BUILD / A contin-
January 2009
managed runtime environment. Application Life Cycle
uous integration feature of TFS. http://
Management msdn.microsoft.com/en-us/library/ms181710
EXPRESSION WEB / Microsoft’s profes- (VS.80).aspx
sional Web layout tool; formerly known as February
Microsoft FrontPage. Defect Tracking Free Stuff
NUNIT / Similar to MSTest, NUnit is a port
IIS / Internet Information Server. Micro- March of the JUnit framework for .NET languages;
Web Performance
soft’s Web server manages requests for Web Management open source. http://www.nunit.org/
content by executing code or ‘serving up’
data files. WATIR / Short for “Web Application Testing
In Ruby,” Watir is a set of Ruby libraries that
Matt Heusser and Chris McMahon
SILVERLIGHT / Microsoft’s competitor to are career software developers,
drive Internet Explorer and monitors tests as
Quick Time and Shockwave, Silverlight is a testers and bloggers. They’re col- they run. Open source. Other implementa-
Web browser plug-in that supports animation, leagues at Socialtext, where they tions include those for Firefox (FireWatir)
graphics, audio and video. perform testing and quality assur- and Safari (SafariWatir), .NET (WatiN) and
ance for the company’s Web- Java (WatiJ).
SQL SERVER / A database engine similar to based collaboration software.
WatiN - http://watin.sourceforge.net/ ý
Watir - http://wtr.rubyforge.org/
Access designed to scale to massive numbers
FIG. 1: APP DEPENDENCIES when you crash an Techniques for testing compound
application in isola- applications vary, and the approach we
tion, it only takes will take here will be to simulate envi-
n
Application down the system it’s ronmental conditions that lead to appli-
running on. In a cation failure. Discovery and execution
compound applica- will leverage several off-the-shelf tools—
.NET Framework tion, it not only takes some freeware and some commercial—
itself, but potentially and target the platforms, including IIS,
many others too. .NET and SQL Server, with the goal of
OS/Services (Win 32) And, of course, each forcing flaws that propagate unstable
of those other behavior across the servers in a com-
Storage Memory Network Registry DLLs servers may be pound application.
depended on by
other compound Breaking Applications
calling buffer is unknown. Developers applications, etc. You get the picture. The most effective approach to breaking
and testers familiar with secure coding This article will highlight some spe- applications is to force them to respond
practices will find this rife with defects, cialized testing techniques and postu- to hostile conditions with appropriate
but the two critical ones are buffer over- late mechanisms for testing com- error/exception handling mechanisms.
flow and data corruption. pound applications running on the If no such mechanism exists, the appli-
Any developer writing code like this Microsoft stack. It will get you thinking cation will generally fail, or at least
should be taken out and shot at dawn, about what error handling means in become unstable and display unexpect-
naturally, but it is a good example and an interdependent runtime environ- ed behaviors. The attack vectors that will
it’s not made up. No kidding, this is ment, how forcing errors during run- provide the best results are typically
actual code. Any application calling this time is a critical activity in developing those that applications consume regu-
function will have to be prepared to secure and stable applications, and larly and that developers are least likely
handle all types of failures depending how you might apply these techniques to worry about when developing excep-
on what the caller needs to do with it. to your own environments. tion handlers. Specifically, these are:
Now consider this code snippet: • Registries
Testing on the Stack • File streams
try Compound applications are deployed • Network streams
{
char* buf = new char[MAX_PATH];
using stacks of other applications, with • Memory
int bytesRead, realLen; the Microsoft implementation being • Libraries (DLLs)
among the most popular. Its primary Attacks that focus on these items
BOOL pipeOpened = getPdata(buf, &bytesRead);
components are IIS for Web services, will yield some pretty spectacular
if(pipeOpened) .NET framework for application servic- results in many cases. In terms of the
{ es and SQL Server for data services compound application, simple appli-
if( (realLen = dataValid( buf )) != 0 ) // call our (see Figure 2). Each component in the cation failures could cause ripples
data cleanser
{
stack is, in itself, quite stable. However, throughout the entire system. Forcing
parseAndSend(buf, realLen); as we’ve seen, the applications that failures in each of these areas is two-
return( TRUE ); depend on them are the primary con- phased, requiring discovery and action
} cern, and forcing failures on one serv- using tools or done manually. In each
else
{ er will help to uncover dependency case, the activity is slightly different,
throw(“Malformed Data Error”); defects in others. and non-exhaustively described here.
}
}
} TABLE 1: PLAN OF ATTACK
catch(…)
{ Iteration Server Test Goal
logerror(_LINE_, “Pipe OpenFailure”);
} 1 Web Catastrophic Force other server failure
return( FALSE ); // Default, return failure 2 Database Catastrophic Force other server failure
Attacks Using the Registry the resul -data is fuzzed? There are sev- tem. Errors can be simple allocation fail-
Applications may rely heavily on the reg- eral methods to fuzz effectively, includ- ures, or they can be corrupted pointers
istry for runtime support. Interesting ing on-the-wire protocol fuzzing and or other local or heap manipulations. In
items such as configuration, file location network I/O virtualization. Each has any case, forcing memory allocation
and license information are good exam- its advantages and the result is gener- errors is great way to quickly force inter-
ples of things that applications regularly ally the same—sometimes spectacular esting failures in applications of all types.
store and consume from there.
Applications typically assume that they FIG. 2: DIVIDE AND CONQUER
have access to the registry and that the
data stored there is correct. Therefore,
the registry is a clear point of failure and Global Failure Conditions
a prime attack vector for attackers. • Server Unavailable
Successfully attacking applications is a • Server Unstable User Interface
matter of denying access to the registry • Server Data Corrupt
data, changing it or corrupting it some- • ...
how. Consider replacing a temp file path
Internet Explorer (IE)
with garbage like X:\\#$ERW—
&UD^\\@#!D.FOOF, and the application
trying to open or create it. Naturally, the
operating system would reject it as hav- Web Server
ing invalid characters, but what does the
application do with it? What happens if
the UI window width is set to 224 or some
Internet Information Server (IIS)
other ridiculously large number?
Iteration 5 to be used a lot and jump over to it in sensitive data or affect the way that the
Force memory constraints on the Web server your favorite registry editor. Save the application communicates with other
with the goal of putting it into some form of entire section of the registry you’re servers and destabilize entire com-
failure state that will slow it down and do going to work on before actually pound applications.
odd things. touching it, and then try to change
The conditions we want to create the values of the interesting key(s). If Iteration 7
will force the Web server to hit the you can’t change the values, stop the Force a failure in an application by fuzzing
swapper and start to thrash. This may AUT, change things around and file streams it consumes and make it crash,
or may not cause failures in the con- restart, keeping an eye on the key to perform non-deterministically or forward cor-
suming application, but it will be a data see if the AUT alters it/them during rupted data.
point either way. startup or shutdown. File fuzzing is becoming popular
There are a couple of ways to create If the AUT does manipulate the key, among testers, and there are a lot of free-
memory constraints and failures. The and you still can’t edit it at run-time, try ware and several good commercial tools
first is to tear open the machine available that do it well. The trick
and start pulling chips out. The
second is to start a lot of applica-
tions that will compete for mem-
ory. But the easiest is to use a
• to success is to find all the files
that applications consume and
when they use them, and then
corrupt them in a meaningful
fault injection tool to set up a File fuzzing is becoming popular way that will cause failures.
very low value for the available Finding them is simple with
system memory or to set up spo- among testers, and there are a some commonly available tools;
radic allocation failures. A test- fuzzing them is best done by one
ing tool that virtualizes applica-
tions is a good choice here
lot of tools that do it well. of the commercial or free
fuzzing frameworks and/or
because it allows testers to products. For cases like the
manipulate their runtime envi-
ronment and allows you to
quickly manipulate the memory
available to just the application
• Microsoft SDL, where it’s a
requirement to open 100,000
corrupt files of the type the
application creates and reads,
under test (AUT), so memory con- a fault injection tool that virtualizes the consider a tool that virtualizes a single
straints won’t affect any other programs application and allows real-time manipu- file and re-corrupts it on every open.
running on the system. lation of the keys. Failing that, just delete Consider the following pseudo code
Using the tool to simulate network the darned things. If the application is snippets:
bandwidth limitations and random cor- fragile, missing keys will send it reeling.
ruptions in the network stream will also Try several avenues to cause failure // Open and use the virtual file 100000 times, if it
fails, bail out
cause the Web server to react in inter- when working the registry such as: For( I = 1 to 100,000 )
esting ways and, in turn, drive interest- Corrupting key values—if the appli- App.FileOpenUseAndClose(“myfile
ing behaviors in dependent systems. cation uses data to control execution .mine_I_own_it.you_cant_have_it”)
Next I
Again, as the application is virtualized flow or configuration, out of range or
the rest of the system is not exposed to corrupted values may destabilize things Return “All Good”
the faults the AUT sees. Forcing error return values—if
While the Web server is being beaten your tools allow registry call return val- :ErrorTrap
up, pay careful attention to the system ues to be overridden, try returning Return “Failed on “ + I
and event logs on all the systems in the REGISTRY_CORRUPT or ACCESS
test and the applications. After the test _DENIED //—————————————————————
run is complete, all of the logs should Changing paths—if the application
// Open and use 100000 different files, if it fails, bail
be saved for later reference, or, if some- uses keys to point to configuration or out
thing crashed, immediately reviewed for temp files, change them and try redi- Array String[100000]// 100000 files I hand built …
coincident events. recting data to non-standard places, took me forever
// I hate my job and my boss
pipes or shares
LoadNames(Array)
Iteration 6 Changing the key type—try chang-
Force a failure in an application by corrupt- ing the type of data the key stores, for For( I = 1 to 100,000)
ing registry keys it consumes and make it example, a string to binary or other App.FileOpenUseAndClose(Array[I])
Next I
crash or perform non-deterministically. type.
Finding the registry keys an appli- While you’re manipulating the reg- :ErrorTrap
cation uses is pretty easy using com- istry, pay attention to the system and Return “Failed on “ + I
monly available free and commercial event logs and watch for odd behavior Follow the same steps as in iteration
tools. Several run in parallel to appli- from the other servers. Failures in reg- six to set up the AUT and locate targets
cations and capture all of their reg- istry reading may be pretty dramatic in to manipulate. Files are slightly differ-
istry, allowing you to get a good feel some cases and subtle in others. Loss ent than registry values because a
for how it is used and what keys might or corruption of data may cause com- process may create a file at runtime,
be interesting. Select a key that seems plete failure or allow redirection of keep it open and locked, and destroy it
A
at shutdown. So you’ll need to find files
that are available at runtime and that STACK OF TESTING TOOLS
the application really uses. Fuzzing
comes in two basic flavors: random and There are several tools both commercial and free that are great for implementing the test-
parametric. Random just corrupts bytes ing described in this article. Most have overlapping functionality, but in many cases the
standalone implementations are best for a specific task.
wherever; parametric allows specific
parts of files to be changed/corrupted RegMon for Windows v7.04 by Microsoft [SysInternals]
in specific ways. It’s best to experiment technet.microsoft.com/en-us/sysinternals/bb896652.aspx
with both. And while the tests are being RegMon is a free and very useful discovery tool that monitors all registry interaction from
executed, monitor all channels out of any and all running applications, and allows users to quickly jump to Regedt32 to manip-
the application for corrupted data too. ulate registry values.
Gomez® and Gomez.com® are registered service marks, and ExperienceFirstTM, Active NetworkTM XF and Active Last MileTM XF are service
marks of Gomez, Inc. All other trademarks and service marks are the property of their respective owners.
By Stephen Teilhet
A longtime .NET developer and author, Stephen Teilhet currently works public void WriteToLog(string message, EventLogEntryType type,
for security tool maker Ounce Labs. CategoryType category, EventIDType eventID, byte[] rawData)
{
if (log == null)
{ TABLE 1: THE APPEVENTS CLASS
throw (new ArgumentNullException(“log”,
“Open the event log before writing to Method Description
it.”));
} WriteToLog This method is overloaded to allow an entry to be written to
the event log with or without a byte array containing raw data.
log.WriteEntry(message, type, (int)eventID,
(short)category, rawData); GetEntries Returns all the event log entries for this event log in an
} EventLogEntryCollection object.
public EventLogEntryCollection GetEntries() ClearLog Removes all the event log entries from this event log.
{
if (log == null) DeleteLog Deletes this event log and the associated event log source.
{
throw (new ArgumentNullException(“log”, CloseLog Closes this event log, preventing further interaction with it.
“Open the event log before retrieving its
entries.”));
} NA = 0, will also help during a forensics investiga-
Read = 1, tion after a security breach occurs. The
return (log.Entries); Write = 2,
} ExceptionThrown = 3, logs can be compared to determine not
BufferOverflowCondition = 4, only if the attacker had access to modify
public void ClearLog() SecurityFailure = 5, the event log, but also which events were
{ SecurityPotentiallyCompromised = 6
if (log == null) modified. Unless the attacker had access
}
{ to the local and remote event logs, a
throw (new ArgumentNullException(“log”, public enum CategoryType : short forensics investigation can easily uncover
“Open the event log before clearing {
it.”));
the motives of the attacker and the extent
None = 0,
} WriteToDB = 1,
of the damage.
ReadFromDB = 2, Let’s dive into the specifics of the
log.Clear(); WriteToFile = 3, AppEvents class. The methods of the
} ReadFromFile = 4,
AppEvents class are described in Table 1:
AppStartUp = 5,
public void CloseLog() AppShutDown = 6, An AppEvents object can be added
{ UserInput =7 to an array or collection containing
if (log == null) } other AppEvents objects; each
{
throw (new ArgumentNullException(“log”, The AppEvents class provides applica- AppEvents object corresponds to a
“The event log was not opened.”)); tions with an easy-to-use interface for cre- particular event log. The following
} ating, using and deleting one or more code creates two AppEvents classes
log.Close();
log = null;
event logs in your application. Your appli- and adds them to a generic Dictionary
} cation might need to keep track of sever- collection:
public void DeleteLog() al logs at one time. For example, your
{ public void CreateMultipleLogs()
application might use a custom log to
if (EventLog.SourceExists(source, {
machineName)) track specific events, such as startup and AppEvents appEventLog = new
{ shutdown, as they occur in your applica- AppEvents(“AppLog”, “AppLocal”);
EventLog.DeleteEventSource(source, tion. To supplement the custom log, your AppEvents globalEventLog = new
machineName); AppEvents(“System”, “AppGlobal”);
}
application could make use of the securi-
ty log already built into the event log sys- Dictionary<string, AppEvents>
if (logName != “Application” && tem to read/write security events that logList = new Dictionary<string, AppEvents>();
logName != “Security” && occur in your application. logList.Add(appEventLog.Name,
logName != “System”) appEventLog);
{ Support for multiple logs also comes logList.Add(globalEventLog.Name,
if (EventLog.Exists(logName, in handy when one log needs to be cre- globalEventLog);
machineName)) ated and maintained on the local com- }
{
puter and another duplicate log is need-
EventLog.Delete(logName,
machineName); ed on a remote machine. This remote To write to either of these two logs,
} machine might contain logs of all run- obtain the AppEvents object by name
} ning instances of your application on from the Dictionary object and call its
if (log != null)
each user’s machine. An administrator WriteToLog method:
{ could use these logs to quickly discover
log.Close(); if any problems occur or if security has logList[appEventLog.Name].WriteToLog(“App
log = null; startup”,
been breached in your application. In EventLogEntryType.Information,
}
} fact, an application could be run in the CategoryType.AppStartUp,
} background on the remote administra- EventIDType.ExceptionThrown);
tive machine that watches for specific logList[globalEventLog.Name].WriteToLog(“App
The EventIDType and CategoryType enumerations
used in this class are defined as follows:
log entries to be written to this log from startup security check”,
any user’s machine. More about watch- EventLogEntryType.Information,
CategoryType.AppStartUp,
public enum EventIDType ing event logs for specific events later.
{ Keeping duplicate copies of event logs EventIDType.BufferOverflowCondition);
Storing all AppEvents objects in a ‘System.ArgumentException’ occurred in system.dll. Regardless of the state of the log vari-
Additional information: The source
Dictionary object allows you to easily ‘AppLocal’ is not registered in log ‘Application’.
able, the source and event log should
iterate over all the AppEvents objects (It is registered in log ‘AppLog’.) “. be deleted in this method.
that your application has created. Using The Source and Log properties must be matched, The DeleteLog method makes a crit-
or you may set Log to the empty
a foreach loop, you can write a single ical choice when determining whether
string, and it will automatically be matched to the
message to both a local and a remote Source property. to delete a log. The following code pre-
event log: vents the application, security and sys-
This exception occurs because the tem event logs from being deleted from
foreach (KeyValuePair<string, WriteToLog method internally calls the your system:
AppEvents> log in logList)
{
WriteEntry method of the EventLog
if (logName != “Application” &&
log.Value.WriteToLog(“App startup”, object. The WriteEntry method checks to logName != “Security” &&
EventLogEntryType.FailureAudit, see whether the specified source is regis- logName != “System”)
CategoryType.AppStartUp,
tered to the log you are attempting to {
EventIDType.SecurityFailure); if (EventLog.Exists(logName,
} write to. In this case, the AppLocal source
machineName))
was registered to the first log it was {
To delete each log in the logList Dictionary object, assigned to—the AppLog log. The sec- EventLog.Delete(logName,
you can use the following foreach loop: machineName);
ond attempt to register this same source
}
foreach (KeyValuePair<string, to another log, Application, failed silent- }
AppEvents> log in logList) ly. You don’t know that this attempt failed
{ until you try to use the WriteEntry If any of these logs are deleted, so
log.Value.DeleteLog();
} method of the EventLog object. are the sources registered with the par-
logList.Clear(); Another key point about the ticular log. Once the log is deleted, the
AppEvents class is the following code, deletion is permanent; and believe me,
placed at the beginning of each method it’s no fun trying to re-create a log and
You should be aware of several key (except for the DeleteLog method): its sources without a backup.
points. The first concerns a small prob- As a last note, the EventIDType and
if (log == null)
lem with constructing multiple {
CategoryType enumerations are
AppEvents classes. If you create two throw (new designed mainly to log security-type
AppEvents objects and pass in the same ArgumentNullException(“log”, breaches as well as potential attacks on
“Open the event log before writ-
source string to the AppEvents con- the security of your application. Using
ing to it.”));
structor, an exception will be thrown. } these event IDs and categories, the
Consider the following code, which administrator can more easily track
instantiates two AppEvents objects with This code checks to see whether the down potential security threats and do
the same source string: private member variable log is a null postmortem analysis after security is
reference. If so, an ArgumentException breached. These enumerations can eas-
AppEvents appEventLog = new
AppEvents(“AppLog”, “AppLocal”);
is thrown, informing the user of this ily be modified or replaced with your
AppEvents globalEventLog = new class that a problem occurred with the own to allow you to track different
AppEvents(“Application”, “AppLocal”); creation of the EventLog object. The events specific to your application.
The objects are instantiated without DeleteLog method does not check the
errors, but when the WriteToLog log variable for null, since it deletes the Searching Event Log Entries
method is called on the globalEventLog event log source and the event log itself. Now that your application supports writ-
object, the following exception is The EventLog object is not involved in ing events to the Event Log, it is possible
thrown: this process except at the end of this that the application might have added
method, where the log is closed and set quite a few entries to the log. To perform
An unhandled exception of type
to null, if it is not already null. an analysis of how the application oper-
ated, how many errors were encountered
TABLE 2: OTHER SEARCH METHODS and so on, you need to be able to per-
form a search through all of the entries
Searchmethodname Entry property searched
in an event log. You will eventually have
FindCategory (overloaded to accept a Category == categoryNameQuery to sift through all the entries your appli-
string type category name) cation writes to an event log to find the
entries that allow you to perhaps fix a bug
FindCategory (overloaded to accept a Category == categoryNameQuery
short type category or improve your application’s security sys-
tem. Unfortunately, there are no good
FindEntryType EntryType == entryTypeQuery search mechanisms for event logs.
InstanceID == instanceIDQuery
To fix this we have built the Event
FindInstanceID
LogSearch class, to which you’ll add stat-
FindMachineName MachineName == machineNameQuery ic methods, allowing you to search for
entries in an event log based on various
FindMessage Message == message.Query
criteria. In addition, this search mecha-
FindSource Source == sourceQuery nism allows complex searches involving
multiple criteria to be performed on an
{
event log at one time. To illustrate how searching works,
var entries = from EventLogEntry
entry in logEntries let’s assume that you are using the
using System;
using System.Collections;
where FindInstanceID method to search on
entry.UserName == userNameQuery the InstanceID. Initially, you would call
using System.Diagnostics;
orderby
entry.TimeGenerated ascending
the FindInstanceID search method,
public sealed class EventLogSearch
select entry; passing in the EventLogEntryCollection
{
private EventLogSearch() {} // Prevent this class collection (which contains all entries in
return entries.ToArray(); that event log) or even an array of
from being instantiated.
}
EventLogEntry objects. A LINQ query is
public static EventLogEntry[] FindEntryType (
EventLogEntryCollection logEntries,
The methods shown in Table 2 (page used to search through the
EventLogEntryType entryTypeQuery) 27) list other search methods that could EventLogEntryCollection for specific
{ be included in this class and describe event log entry objects (EventLogEntry)
var entries = from EventLogEntry entry in which property of the event log entries that satisfy the where clause of the
logEntries
where entry.EntryType == they search on. LINQ query. The ToArray method is
entryTypeQuery The FindCategory method can be used to convert the resulting LINQ
orderby entry.TimeGenerated overloaded to search on the category query results into an array of
ascending
name, the category number or both. EventLogEntry object. The
select entry;
The following method makes use of FindInstanceID method will then
the EventLogSearch methods to find return an array of EventLogEntry
return entries.ToArray(); and display entries that are marked as objects that match the search criteria
}
Error log entries: (the value passed in to the second argu-
public static EventLogEntry[] ment of the FindInstanceID method).
public void FindAnEntryInEventLog(
FindTimeGeneratedAtOrAfter( LINQ is used in the event log
)
EventLogEntryCollection logEntries, DateTime
{ search because of its power and sim-
timeGeneratedQuery)
EventLog log = new plicity. Its declarative syntax is easier to
{
EventLog(“System”);
var entries = from EventLogEntry entry in read and understand, while at the
logEntries same time providing a wealth of oper-
EventLogEntry[] entries =
where entry.TimeGenerated >=
timeGeneratedQuery
EventLogSearch.FindEntryType(log.Entries, ations that can be performed on your
EventLogEntryType.Error); query. LINQ allows not only sorting,
orderby entry.TimeGenerated
ascending
// Print out the information
but also grouping, joins with other
select entry; data sets, and multiple search criteria
foreach (EventLogEntry entry in
return entries.ToArray();
entries) in the where clause. LINQ also allows
{ the use of set operations such as
}
Console.WriteLine(“Message:
} union, intersect, except and distinct,
“ + entry.Message);
What makes this class so flexible is Console.WriteLine(“InstanceId: on your data. There are aggregate
that new searchable criteria can be “ + entry.InstanceId); operators, such as Count and Sum, as
Console.WriteLine(“Category:
added to this class by following the same well as quantifier operations, such as
“ + entry.Category);
coding pattern for each search method. Console.WriteLine(“EntryType: Any, All and Contains. This is but a
For instance, the following example “ + entry.EntryType.ToString( )); sampling of the operations a LINQ
shows how to add a search method to Console.WriteLine(“Source: query can perform on your data. By
“ + entry.Source);
find all entries that contain a particular }
combining these operations, you can
username: } come up with your own custom search
queries for your event log entries.
public static EventLogEntry[]
FindUserName(EventLogEntryCollection logEntries,
Note that this search mechanism can The real power of this searching
string userNameQuery) search within only one event log at a time. method design is that the initial search
on the EventLogEntryCollection
FIG. 1: CUSTOM DEBUGGER DISPLAY returns an array of EventLogEntry
objects. This EventLogEntry array may
then be passed back into another
search method to be searched again,
effectively narrowing down the search
query.
For example, the EventLogEntry
array returned from the FindInstanceID
method may be passed into another
search method, such as the FindEntry
Type method, to narrow down the
search to all entries that are a specific
entry type (informational, error, etc.).
This can continue until the search has
been sufficiently narrowed down. The
following method finds and displays
EventLogEntry[] entries =
EventLogSearch.FindTimeGeneratedAtOrAfter(log.E
ntries,
DateTime.Parse(“5/3/2008”));
entries =
EventLogSearch.FindEntryType(log.Entries,
EventLogEntryType.Error);
entries =
EventLogSearch.FindInstanceId(log.Entries,
3221232483);
By Vladimir Belorusets
www.stpmag.com • 31
DATA STRUCT
FIG. 1: TWO DIMENSIONS • How can we preserve the origi- reused, without changes, for testing
nal test data? a different functionality in a product
• Do we need to keep multiple just by modifying the test data.
instances of the data files for Separating the data from the scripts
each script? will also significantly reduce the
Successful adoption of a test total number of scripts that must be
automation framework depends on supported.
how effectively it supports the ease
of test data access and modification Rule 2: Test data should be presented in
and avoids conflicts of overwriting tables.
script data in the different test sets. Advantages. Presenting data in
tables facilitates design of data-driv-
Design Rules en tests. A data-driven test is a tech-
Based on industry practices, I have nique that allows one automation
developed a list of six general design script to implement many test cases
rules that have proven to be efficient by iteratively reading through a data
for organizing test data within the table one row at a time, using the
frameworks. These rules should be values in that row to drive the test.
considered as functional require-
ments when developing test automa- Rule 3: Data tables should be provided
tion frameworks in-house or when in external files and be easily available
evaluating commercial frameworks. for review and modification to the test
Here are the rules and the advan- case consumers.
tages that they bring to the test Advantages. I divide the users of
automation framework users: the scripts into two broad categories:
test automation engineers and sub-
Rule 1: Test data must be separated ject matter experts. Users belonging
from the test scripts. to the latter category usually do not
Advantages. This is the most fun- have programming skills, but they
damental principle in code design do have a deep understanding of the
applicable to any code including the business that an application under
test scripts. You will not believe how test automates. They know which
many times I have seen this rule data to apply to verify the subtleties
being violated. Because of that, the of the application’s functionality. If a
code had to be rewritten later with script is properly designed, the sub-
the missing deadlines. Once the pro- ject matter experts should be able to
gram is debugged and released you execute it easily without looking in
them on distributed hosts in a should avoid code change unless it’s the code. All they need to do is mod-
sequence defined by the test set. absolutely necessary. Any code mod- ify test data. If it takes considerable
Test data can be classified accord- ification is error-prone. effort to find the data file navigating
ing to scope. Global test set data are If the data are hard-coded, you through the tens of subdirectories,
shared and visible to all scripts within may change them in one place and then the test automation framework
a test set, and local data are visible forget to change them in the other is inefficient and unusable.
only within the originating script. places. Another reason is code inter-
Global test data usually represent the nationalization; all human-readable Rule 4: Global data common to all
configuration parameters, such as strings in the code should be repre- scripts in a test set must be separated
server name, starting Web page URL, sented by the vari-
and other items, which are common ables and stored FIG. 2: SCRIPT/DATA CATALOG
to all scripts. Figure 1 illustrates the in the separate
organization of the test sets. resource files. To
Every test automation framework change the locale,
architect should answer the follow- all you need to do
ing questions: is change the ref-
• How will we implement global erence to the new
data? locale directory,
• How will we change the script’s and no code edit-
local data? ing is required.
• Will the local data be overwrit- The main advan-
ten for every new test set? tage of this rule in
• If we want to rerun the script test automation is
later with data from a previous that the same
test set, do we need to reenter it? script can be
32 • Software Test & Performance SEPTEMBER 2008
DATA STRUCT
from the local script data. for test data organization FIG. 4: SUBSEQUENT SETS
Advantages. If script data files in a that abides by the presented
large test set contain both global design rules. The solution is
and local data, it takes more time to given for Windows, but the
modify the same data in all data same ideas can be applied to
files. This procedure is inefficient any platform, and the data
and error-prone. If we instead have a design rules are platform
central repository for global data, we independent.
need to do the modification only
once per test set and it will be imme- Data Organization
diately propagated to all the scripts. In this implementation, each script original local test data, you should
Everyone will be able to execute test is associated with only one data file. create a worksheet with the test set
sets in their environment just by It uses an Excel spreadsheet for pre- name and enter the new test data
modifying global settings and senting test data in the tables follow- there (Figure 4). This way, local data
reusing the original local data with- ing Rule 2. According to Rule 3, for different test sets are associated
out changes if they are still valid for these data files should be easily with the test set names (Rule 5) and
their tests. accessible by subject matter experts. can coexist in one data file (Rule 6).
This raises another funda- We use the following simple algo-
FIG. 3: FIRST TEST SET mental question on how to rithm for accessing local test data.
effectively group scripts Each script reads the associated data
and their data files for easy from the worksheet that has the test
location. set name the script belongs to. If
When an engineer begins there is no such worksheet, the data
a test automation project, the are automatically read from the
first task he is faced with is “Default” worksheet. If subject mat-
how to arrange scripts and ter experts want to modify the origi-
data. To conduct this task, I nal test data, all they need do is cre-
Rule 5: Local test data should be promote a practice of creating the ate a worksheet with the test set
uniquely associated with both the test application’s Functional Decomp- name in the data file.
script and the test set that contains the osition Model, where all of the appli-
script. cation’s functionality is decomposed Global Data Implementation
Advantages. An association with the into a hierarchy of functional areas Let’s look at a typical situation.
test set is necessary to run the same and subareas. This structure is then You’ve assembled a test set of 100
script in the multiple test sets but with mapped to a directory tree, which scripts developed by others. With the
different data. Note in Figure 1, I stores test cases and scripts under the scripts, you inherited their test data
assigned two dimensions to all local matching functional area directories. files. Every script in the test set uses
data: one index for the script, and the The subject matter experts do not Server_Name as an input parameter.
other one for the test set. need to review the individual scripts, You are comfortable with all test data
but they do need to know what the except that the server’s name in your
Rule 6: Local data for each test set script does and where its data are test environment differs from the
should be separated and coexist within located. one in the original data files. How
the same data file. Easy access to data files can be can you avoid the error-prone work
Advantages. To run the script, the provided by creating a script/data of editing all 100 data files to change
test automation framework extracts the catalog in MS Excel using its “Group the server’s name to the same value?
data file provided by the script devel- and Outline” feature (Figure 2). For The solution is global data for the test
oper from the script repository. To each script record, there is a link to set (Rule 4).
change data for the subsequent test set, the corresponding data file that you There are three options for where to
you need to overwrite that original can open, modify, and save directly store the global variables: Windows reg-
data file. This creates a data conflict. from the spreadsheet. istry, environment variables and files.
One possible solution is to have one Each data file has multiple work- One convenient way to implement
script and multiple data files corre- sheets with one mandatory work- global test data is through the environ-
sponding to every test set. Such an sheet, named “Default” (Figure 3). ment variables that one can easily view
approach creates overhead for data file That worksheet contains the
maintenance and for dynamically map- original test data provided FIG. 5: GLOBAL VALUES
ping the right data file to the script. If by the script developer.
we have only one data file with coexist- All worksheets have the
ing local data for every test set, it sim- same structure: the first row
plifies data inventory and search. Data contains headers (parameter
coexistence also protects against data names), and all other rows
conflicts and overwriting. contain test data values.
The following is an example of a Multiple rows indicate a data-
flexible and efficient architecture driven test. To modify the
SEPTEMBER 2008 www.stpmag.com • 33
DATA STRUCT
www.eclipseworld.net
PLATINUM SPONSORS GOLD SPONSORS SILVER SPONSOR MEDIA SPONSORS PRODUCED BY
www.code-magazine.com
By Venkat Moncompu and
Sreeram N. Gopalakrishnan
adaptive design and development tech- So planning testing cycles entails effective
niques as opposed to predictive tech- Your Artifacts traceability of test artifacts to require-
ments planned for the iteration. Though
The authors are project managers at Intellisys the emphasis in agile development is on
Technology, an IT services company based in
people rather than on process, on work-
Oak Brook, Ill.
ing software over comprehensive docu-
mentation, and responding to change and/or features (remember “just enough features are tested and verified. This
rather than following a plan, a QA man- documentation to develop software”). In further provides valuable feedback to
agement process needs to remain nimble agile methodology, the emphasis is on the project team (including the end-
to the changing and evolving needs and software construction rather than docu- user stakeholder) about the software
requirements. This is precisely where the mentation, unlike the traditional water- construction progress. To be effective,
traceability matrix can be leveraged to fall model of software development. The therefore, it is important that the
perform optimal QA activities that give two main premises of being agile are: traceability is mapped thoroughly
the most value. • The ability to welcome and adapt making the features provided trans-
to requirement changes later in parent to all stakeholders. And for the
Agile Testing the development life cycle. QA manager, it provides a good substi-
Agile QA testing involves closer and • Testing often and testing early (in tute from “traditional” selection crite-
tighter feedback within each cycle of iterative cycles). ria for regression and acceptance tests.
iteration, defining levels and types of Apart from these two basic tenets, It plays an important role in providing
testing in each cycle of iteration. How the other difference from a waterfall a basis for statistical information such
can planning of requirements testing model is that the requirements are as burn rates and velocity for the team
work with iterations? User needs in an never really “frozen” in development management.
agile process are defined by a story such that it becomes an entry criterion
(sometimes captured as use-cases and for the software construction phase. Multi-Dimensionality of Traceability
features) planned to be implemented Prototyping is the key aspect of agile For the sake of clarity, a case study show-
iteratively. Work breakdown for devel- development techniques that help in ing traceability to map test cases relating
opment (in iterations) of these use- getting user feedback early and contin- to use cases and features of a student reg-
cases and features is defined in terms of uously in the development life cycle. istration system is discussed here.
tasks. As a logical extension, the QA This reduces the “dreaded integration Consider a student-course registration sys-
effort can also be tasked for planning phase” late in the software development tem. It should have the following features:
and scheduling purposes. phase, minimizing the risk of falling • Users (Students, Registrars and
The scope of testing in iteration is short of user needs or ending up with Professors) should be able to regis-
usually a set of unit and (build) accept- unfulfilled requirements. ter with the system.
ance tests to verify the requirements User acceptance tests serve as exit • Users should be able to create,
and features planned for the iteration. (or acceptance of the build) iteration update or delete their profiles and
The need for constant and continuous criteria and to measure progress (or preferences.
regression testing is warranted as the burn rate) of the project. So, in tech- • Users (Students) should be able to
software construction evolves and bugs niques such as feature-driven develop- register for classes and securely pay
get fixed, just as it scopes the features ment and test-driven development, the for courses.
and use cases that go into the current mapping of the features and use cases • Users (Students, Registrars and
iteration or development cycle. Itera- to test cases—traceability—serves as a Professors) should be able to view
tions, being time-boxed, do not wait for valuable tool to effectively plan and the student transcripts based on
the exit or entry criteria to be met nor schedule testing just as features and access restrictions.
are they predefined. cards are used to plan development in • Users (Registrars and Professors)
Agile testing leaves a lot of room for iterative cycles. should be able to create course
exploratory and ad hoc testing that isn’t And just as use cases provide a user offerings and the system should
necessarily captured in the use cases perspective for developers and design- provide a catalog of courses.
ers; testers have the onus of ensuring As with any system of moderate com-
the software meets the user require- plexity, the set of requirements can
ments adequately. This can be effectively never be really termed “complete.”
achieved by mapping test artifacts to Therefore the process should be adap-
requirements that are modeled as use tive to changing user needs. But for the
cases and testing the intended function- sake of this example, these require-
ality independently. ments will suffice. A set of possible use
cases identified for the system are:
Scheduling and Iteration Planning The use case descriptions in Table 1
The agile techniques for software devel- (see References) define the main suc-
opment uses tasks in place of work cess scenarios of the system. However,
breakdown structures referred in tradi- not every use-case scenario ends in suc-
tional project planning tools. To effec- cess for the user. While elaborating the
tively understand the use of tasks and use cases using the descriptive text to
planning of effort from a QA perspec- capture these alternate paths, new
tive, it is useful to breakdown the QA aspects of the systems come to light
work product into iterations based on when exceptions are encountered (non-
the features and functional specifica- happy path behavior of the system is
tions that are planned for the iteration. being captured).
Traceability matrices provide a con- Spence and Probasco refer to them
venient way of ensuring the intended as overloading the term requirements, a
ment or HTTP request performs.” structuring of queries or adding addi- tions were made that resolved all per-
DBAs trained in the optimization of tional networking resources in strategic formance issues, says Menezes.
SQL calls, whether to an Oracle, geographical locations. Though Emergisoft’s performance
Microsoft, My SQL or other database are After troubleshooting the Emergi– woes were found relatively quickly, that
almost always part of any large IT opera- softED application with the aid of a is not always the case, leading to politi-
tion. Specialists in HTTP opti- cal stress on the IT organization
•
mization are a newer breed, but and a potential loss of business.
are equally valuable. Even with “The entire development team
highly efficient database has to understand that they are
queries, determining which data all in this together, regardless
to return first and whether the Get the team together quickly and of where the actual problem is,”
entire screen or just a portion of says Technisource’s Yannetti.
it is refreshed can make a signif- keep management informed. “Post-deployment problem solv-
icant difference. ing is an area where the test
According to research firm manager needs to step up and
Gartner, the simple act of
opening a file can generate up
to 100 message exchanges.
Place the server and customer
• take the lead.”
Even with functional specifica-
tions that quantify the bounds of
acceptable performance and with
thousands of miles apart, and a 50-mil- thread analysis and application analytics a test environment that reproduces the
lisecond network latency for each of tool, performance degradation was production environment in terms of
those exchanges adds up to five sec- traced ultimately to a trio of factors: transaction load and simultaneous user
onds,before any transactions take place. SQL tuning and out-of-date or missing headcount, a post-deployment meltdown
Add hundreds or thousands of simulta- indexes. Once the offending SQL had can still occur. Get the team together
Index to Advertisers
Automated QA www.testcomplete.com/stp 10
Empirix www.empirix.com/freedom 6
Gomez www.gomez.com 23
Hewlett-Packard hp.com/go/quality 44
iTKO www.itko.com 43
McCabe www.mccabe.com/stp 35
Qualitest www.QualiTest-int.com 3
Ranorex www.ranorex.com/stp 34
Seapine www.seapine.com/optiframe 4