Вы находитесь на странице: 1из 27

CHAPTER11

TESTSCRIPTLANGUAGE

WewillnowlookattheTSLlanguage.Youhavealreadybeenexposed tothislanguageatvariouspointsofthisbook.Alltherecordedscripts thatWinRunnercreateswhenyouperformanoperationisinTSLcode syntax.KeepinmindthatwhilemasteryofTSLisnotrequiredfor creatingautomatedtests,knowledgeofthelanguagehelpstoenhance therecordedtestsandtocreatehighlysophisticatedtests.Skillful usageofTSLcanlimittheneedformanualinterventionwhenrunning yourtest.Itcanalsomakeyourtestlesserrorprone.

Test Script Language


TSListhescriptlanguageusedbyWinRunnerforrecordingand executingscripts.Inthischapter,Iwillprovideyouwiththe foundationalconceptsofTSL.Thinkoftheseasthebuildingblocksof TSLscriptingthatwillhelpyoulearnhowtowritethelanguage. AnotherusefulresourcetoreviewwhilelearningTSListhe WinRunnerhelpsystem.

TIP: To access the WinRunner help system at any time, press the F1 key.

TheTSLlanguageisverycompactcontainingonlyasmallnumberof operatorsandkeywords.Ifyouareproficientinanyprogramming language,youwillfindTSLeasytolearn.Infact,youwillfinditmuch easierthanlearningaprogramminglanguagebecauseTSLisascript languageandassuch,doesnothavemanyofthecomplexsyntax

structuresyoumayfindinprogramminglanguages.Ontheother hand,TSLasascriptlanguagehasconsiderablylessfeaturesand capabilitiesthanaprogramminglanguage. Table11.1showsthelistoffeaturesthatareavailableinTSL. Feature


Comments Naming Rules Data Types Data Storage Operations Branching Loops Functions Description Allows users to enter human readable information in the test script that will be ignored by the interpreter. Rules for identifiers within TSL. The different types of data values that are supported by the language. Constructs that can be used to store information. Different type of computational operations. Avoids executing certain portions of the code unless a condition is met. Repeats execution of a certain section of code. Group of statements used to perform some useful functionality.

Table 11.1: Parts of the TSL Language.

History
TSLstandsforTestScriptLanguageandisoftenreferredtobyits acronym.CreatedbyMercuryInteractiveanusedinseveraloftheir productlineincludingWinRunner,XRunnerandLoadRunner,TSLhas similaritiesinfunctionalityandkeywordstotheClanguageandanyof itsderivatives.KnowledgeofsimilarlanguagesasJavaScript,Perlor JavawouldaidinyourquickunderstandingofTSL.

General Syntax Rules


1.Semicolonsmarktheendofasimplestatement. Youmayhaveseenthatmanyoftherecordedstatementsinyourtest endswithasemicolon.ThisisimportantbecauseTSL,likeotherC basedlanguagesusethesemicolontospecifytheendofastatement muchlikeyouwoulduseaperiodtospecifytheendofasentencein English.Thefollowingcode:

foo(); bar();

canthenbewrittenas:
foo(); bar();

andWinRunnerwillstillexecutethemproperly. 2.Compoundstatementsusecurlybracesandnotsemicolons. Compoundstatements,i.e.statementsthatcanholdotherstatements withinthemdonotendwithasemicolon.So,theifstatement,whichis acompoundstatementiswrittenas:


if ( 1 > 0 ) { foo(); }

Noticethatthecontentwithintheifstatementhasthesemicolonand nottheifstatementitself.ItwouldbeWRONGtowritetheifstatement inthefollowingform:


if ( 1 > 0 ); { foo(); }

3.TSLiscasesensitive. TSLisalsoacasesensitivelanguagesopayspecialattentiontothecase ofthestatementsthatyouwrite.Mostoftheidentifiers,operatorsand functionswithinthelanguageutilizelowercase.So,whenyouare unsure,trylowercase.

TIP: When writing compound statements, it is highly beneficial to indent the content of the compound statement. This makes it easier to identify the items within a compound statements. Though the interpreter does not care about compound statements, it makes the code easier for you to read.

WewillnowlookcloselyatthepartsoftheTSLlanguagelistedin Table11.1.

Comments
CommentsallowyoutoincludestatementswithinaTSLtestandhave thesestatementsignoredbytheinterpreter.Theseinsertedcomments

areusefulbecausetheyprovidethereaderofthetestscriptwithuseful informationaboutthetest.Tocreateacomment,typethe#symbol anywhereonthelineandeverystatementincludedafterthissymbolis regardedasacomment.The#symbolcanappearasthefirstcharacter inalinemakingthewholelineacomment,oranywhereintheline makingapartiallinecomment.e.g.


# This is a whole line comment foo(); # This is a partial line comment

NOTE: When a comment is specified, the font style and color in the editor changes. You can control how the font looks for comments as well as for several other items in the editor by clicking on Tools->Editor Options.

Unlikesomeotherlanguagesthatyoumaybeusedto,TSLdoesnot havemultilinecomments.Youwillhavetoplacethe#characteratthe startofeachlineyouwishtoconvertintoacomment.

TIP: It is a good idea to use comments liberally in your test to make it easier for people to understand the assumptions/decisions you made in the test.

Naming Rules
Everylanguagehasrulesthatdefinewhatnamesareacceptableinthe languageandwhichnamesarenot.InTSL,severalitemshavetobe givennamesincludingvariables,constantsandfunctions.Thesenames aretheidentifiersweusetorefertoeachoftheseitems.Thefollowing rulesareusedfornamingitemsinTSL. 1. MustbeginwithaletterortheunderscoreNameslikecount, strInfo, _data areacceptablebutnameslike2day, 4get, *countviolatethisrule. 2. CannotcontainspecialcharactersexcepttheunderscoreNamescan onlybemadeupofalphabets,numbersandtheunderscore. Symbolsandotherspecialcharactersarenotallowed. 3. CannotmatchareservedwordWordshavingspecialmeaningsto TSLcannotbeusedasvariablenames,sonameslike for, if, inetc.are notallowed.

4. MustbeuniquewithinacontextThispreventsyoufromgivingtwo itemsthesamenameatthesametime.Thisisforthesamereasons youavoidgiventwochildreninthesamehouse,thesamename. 5. ArecasesensitiveMeaningthatyoucandeclarefoo, Foo,andFOOas threedifferentnameditemswithoutviolatingrule4. InChapter6,Idescribedanamingconventionthatcanbeusedin renamingGUImapobjects.Thesameconventionisveryapplicable here.Bynamingvariablesusingprefixesofnumandstr todenote numbersandstrings,youcancreatevariablesthatareeasyto reference.

Data Types
Everyscriptlanguagehasdifferenttypesofdatathatcanbestored whenascriptisexecuting.Thedifferenttypesofdataareknownas datatypes.Whilesomelanguageshaveseveraldatatypes,TSLhas onlytwo.ThetwodatatypesavailableinTSLare: Stringforstoringalphanumericdata.Stringsaredenotedbyputting doublequotes()aroundvalues.ExamplesincludeHello,John Q.Public,101CurlDrive,Itwasthebestoftimes,itwasthe worst... Numberforstoringnumericdata.Numberscanhavenegativevalues, holddecimalplaces,orbedenotedinexponentialnotation. Examplesinclude21,6,12.31,4e5,and4E5. Althoughtherearetwodatatypes,wedonotneedtospecifythetype ofavariableduringcreation.TSLsimplyusesthecontextinwhichwe accessthedatatodeterminewhatthedatatypeis.Informationis convertedeasilyandflexiblybetweenbothtypes.Thefollowingcode:
foo = "2" + 1;

resultsinfoobeingassignedthenumericvalue3becauseTSLseesthis asanarithmeticoperation.However,thefollowingcode:
bar = "2" & 1;

resultsinbarbeingassignedthestringvalue"21".Thedifferencehereis thatwhen&(stringconcatenation)isused,astringoperationis performedandtheoperandsareconvertedtostring.However,when+ (addition)isused,theoperandsareconvertedtonumbersandan arithmeticoperationisperformed.WewilllookatthedifferentTSL operatorslater.

ESCAPE SEQUENCES
String are defined as values enclosed in double quotes e.g. foo = "Hello"; would hold the value Hello. But what if you want to store the value John "Q" Public? To do this, you have to write the code: foo = "John \"Q\" Public"; Note that we have included a backslash (\) in front of the double quote. This format allows us to store the literal value of the double quote. This is known as using an escape sequence and it is a way to include certain types of characters and values within a string. TSL defines other escape sequences and I have included these in Table 11.2 below.

Feature
\ \\ \b \n \number \t \v

Description
Double quote Backslash Backspace New line Storing octal numbers e.g. \8 is 10 in decimal notation Horizontal tab Vertical tab

Table 11.2: TSL escape sequences.

Whenyouarereferringtofilenamesonacomputer,paycareful attentiontoescapesequences.Referringtothefile:
C:\newfile.txt

Willbeinterpretedbythesystemas
C: ewfile.txt

Notethatthesystemconvertedthe\ntoanewlinestatement.To preventthis,youwillneedtoescapethe\.So,youmustusethe\\ sequenceinstead.Thismeansthefilenamewillbewrittenas:


C:\\newfile.txt

Thisisaveryimportantitemtorememberandyouwillseetheusage ofthe\\inallinstanceswhereIrefertoafile.

Data Storage
Thisreferstohowinformationisstoredinthetestduringtest execution.Computersneedtostorelargeamountsofdataduringtest execution.Theseinclude: dynamicvaluesvaluesthatcanchange fixedvaluevaluesthatremainthesamethroughtestexecution setsgroupsofvalues. TSLusesthreedifferenttypesofstoragevehicles.Theseinclude Variablesfordynamicstorage,constantsforfixedvaluesandarrays forsets.Eachofthestoragedevicesaredescribedbelow: VariablesContainersthatcanholdapieceofinformation.The informationbeingheldcanbechangedoverthelifetimeofthe variable. ConstantsContainersthatcanholdapieceofinformation.The informationbeingheldcannotbechanged. ArraysAsinglecontainerthatcanbeusedtoholdseveralpiecesof informationatthesametime.Thisisusedtoholdinformation thatarerelatede.g.namesofpeople,statesetc. Datastorageonlyreferstoinformationthatneedstobestored temporarilyduringtestexecution.Forinformationthatyouwantto storepermanently,youshouldconsiderwritingtoafileordatabase.

Variables
Syntax:
class variable [ = value ];

Inourcode,weoftenneedtotemporarilystoreinformationthatwe plantouselater.Thisissimilartowhensomeonetellsyouaphone number.Youmaywritethisphonenumberdowntolateruse.The pieceofpaperyouwrotethenumberonisastoragedeviceforthe information.Justasyoucanerasethevalueonthepaperandwritea newpieceofinformation,youcansimilarlychangethevalueina variable.So,forthemultiplepiecesofinformationthatyourtestscript willcollectandprocessyouwillneedvariablestoholdthem. Inmanyprogramminglanguages,avariablemustbedeclared beforeuse.ButinTSL,variabledeclarationisoptionalsoyoucan createavariablesimplybyusingthevariableinyourcode.Whenever theinterpretercomesacrossanewvariablebeingusedinyourcode,it

automaticallyhandlesthedeclarationforyou.Thisisknownasimplicit declaration.Theonlyexceptiontothisisinfunctions(discussedlater inthischapter)wherevariabledeclarationisrequired. Declaringavariableisdoneusingthefollowingform:


class variable [ = value ];

Meaningthatthatyoueitherwrite
class variable;

or
class variable = value;

Thefirstformsimplydeclaresthevariablewhilethesecondform initializesitwithinavalue. ThewordclassshouldbereplacedwithavaluefromTable11.3 belowandvariableisanynamethatconformstoallthenamingrulesI listedearlier. Class


auto extern public static Scope Local Global Global Local Use in function Yes Yes No Yes Use in test No Yes Yes Yes

Table 11.3: Class values for variable declaration. Basedonthis,thefollowingdeclaresastaticvariablenamednumCount andassignsitavalueof7;


static numCount = 7;

Constants
Syntax:
const CONSTANT = value;

Constantsareverysimilartovariablesbecausetheystorevaluesalso. Themajordifferencebetweenthesetwoisthatthevalueofaconstant isfixedandcannotbechangedduringcodeexecution.Constantsare typicallyusedwhenanitembeingdescribedhasafixedvalueinthe realworld.E.g.


const DAYS_IN_WEEK = 7;

Thisway,insteadofwriting:
foo = 30 / 7;

wheneveryouaredoingdatebasedcalculations,youcanwrite:
foo = 30 / DAY_IN_WEEK;

Thedifferenceissubtlebutultimatelythesecondformofthecodeisa littleeasiertoread.Additionally,ifyouneedtochangethecalculation ofdaysfromcalendarsdays(7)tobusinessdays(5),youcaneasily changethisintheconstantdeclarationandhavethechangepropagate throughyourentirecode.

Arrays
Sometimesyoumaywanttostoreseveralpiecesofrelateddatasuchas names.Onewaytodothisistodeclaredifferentvariablesforeach valuee.g.
name1 = "John"; name2 = "Jane"; name3 = "Joe";

Whilethiswouldworkforyourneeds,TSLprovidesabetter mechanismforusewhendealingwithacollectionofsimilaritems.This concept,knownasarrays,allowsyoutostoreseveralvaluesofrelated informationintothesamevariable.Eachvaluemustbestoredwithina differentindexinthevariablename.So,thecodewrittenabovecanbe rewrittenas:


names[0] = "John"; names[1] = "Jane"; names[2] = "Joe";

The[ ]specifythatyouarestoringinformationintoanarrayandthe numberspecifiestheappropriateindex.Indeed,thecodelooksvery similartowhatwewrotepreviously.So,youmightask,whatisthe benefitofanarray?Theansweristhatusinganarray,Icaneasily performoperationsonmyentirecollectionofnameswithouthavingto dealwithmultiplevariables.IcanuseTSLconstructssuchasloopsto performoperationsontheentirearrayquiteeasily.Thefollowingcode:


for (i=0; i<3; i++) { print(names[i]); }

printsoutthethreenamesinmyarray.Ifthearrayhad50separate values,Iwouldstilluseasimilarlycompactamountofcodetoprintall

thevalues.IsimplywouldjustneedtochangetherangethatIam instructingthelooptouse.IfIused50differentvariables,theamount ofcodeIwouldneedtowritetoprinteachnamewouldbefargreater. Whenworkingwitharrays,thereareafewrulestoremember. 1.Arraysaredeclaredusingthefollowingrules:


class array[] [ = initialization ];

whereclassisavariabledeclarationtype(seeTable11.3),arrayisvalid name(seeNamingRules),andinitializationisasetofinitialvalues. Noticethatinthisconstruct,theinitializationisoptionalsoIcan declareanarrayas:


public names[] = {"John", "Jane", "Joe" };

or
public names[];

2.Arrayscanbeinitializedin2ways.Usingstandardinitialization shownbelow:
public names[] = {"John", "Jane", "Joe" };

orbyusinganexplicitformofinitializationsuchas:
public names[]; names[0] = "John"; names[1] = "Jane"; names[2] = "Joe";

3.TSLsupportsassociatearraysallowingyoutousestringsasyour arrayindexes.Forinstance:
capital["Ohio"] = "Columbus";

isvalidTSLcodethatstoresColumbuswithinthearraycapitalatthe indexOhio. 4.Arrayindexesdonothavetostartfrom0.Asshownabove,the indexesdonotevenhavetobenumbersatall. 5.Arrayscanbemultidimensionalallowingyoutostoremultiple piecesofinformationateachindex.Thefollowingcode:


names["first", 1] = "John"; names["first", 2] = "Jane"; names["middle", 1] = "Q"; names["middle", 2] = ""; names["last", 1] = "Public"; names["last", 2] = "Doe";

generatesdatathatcanbedisplayedinthefollowingformshownin Table11.4.
names first middle last 1 John Q Public Doe 2 Jane

Table 11.4: The 2-dimensional names array. A1dimensionalarraycanberepresentedasalist,a2dimensional arraycanberepresentedasatableanda3dimensionalarraycanbe drawnasacube.WhileTSLsupportsarrayswith4ormore dimensions,itisoftenmoredifficulttoconceptualizethese.

Operations
Operationsarethemanyformsofcomputations,comparisonsetcthat canbeperformedinTSL.Thesymbolsusedinanoperationareknown asoperatorsandthevaluesinvolvedintheseoperationsareknownas operands.MostoftheoperationsinTSLarebinaryoperations, meaningtheyinvolvetwooperands.Twooftheoperationsareunary (i.e.involvingasingleoperand),andoneoperationistertiary(i.e. involvingthreeoperands). Forunaryoperations,thesyntaxisintheform: Syntax:
operator operand1

Forbinaryoperations,thesyntaxisintheform: Syntax:
operand1 operator operand2

Fortertiaryoperations,thesyntaxisintheform: Syntax:
operand1 operator1 operand2 operator2 operand3

isusedinstead.Manyoftheoperatorsaremadeupof2symbols combinedtogether.Thisispossiblebecauseofalackofenoughdistinct symbolsonthekeyboard.Wheneveryouhavesuchanoperatore.g.>=, youcannotwritethisas> =.(Noticetheincludedspace). WinRunnersupportssixdifferenttypesofoperations.Theseare: Arithmetic

Arithmeticoperationsareusedforperformingcalculations.The operandsofanarithmeticoperationshouldbenumericvaluesandthe resultofthisoperationisnumeric.Thearithmeticoperatorsavailablein TSLareshowninTable11.5: Operator


+ * / % ^ or ** ++ -Description Addition Subtraction Negation Multiplication Division Modulo Exponent Increment Decrement Usage Example
foo = 4 + 2; foo = 4 - 2; foo = -4; foo = 4 * 2; foo = 4 / 2; foo = 4 % 2; foo = 4 ^ 2; foo++; foo --; # foo has the value 6 # foo has the value 2 # foo has the value -4 # foo has the value 8 # foo has the value 2 # foo has the value 0 # foo has the value 16 # The value of foo increases by 1 # The value of foo decreases by 1

Table 11.5: Arithmetic operators. Comparison Comparisonoperatorsareusedtocompare2valuesagainsteachother. Thetwovaluesbeingcomparedshouldbeofasimilartypee.g.you shouldcompare2numberagainsteachotherand2stringsagainsteach other.TheresultofacomparisonoperationistheBooleanvalueof1 (fortrue)or0(forfalse).Table11.6showsthecomparisonoperators availableinTSL. Operator
== != > < >= <= Description Equality Inequality Greater than Less than Greater than or equals Less than or equals Usage Example
4 == 2 4 != 2 4>2 4<2 4 >= 2 4 <= 2 # the result is 0 (false) # the result is 1 (true) # the result is 1 (true) # the result is 0 (false) # the result is 1 (true) # the result is 0 (false)

Table 11.6: Comparison operators.

Logical Logicaloperatorsexisttoallowustoreducethevalueofseveral BooleanoperationstoasingleBooleananswer.TheresultsofBoolean operationscanbecombinedinthreeways: Conjunctions:whenbothoperandsinthelogicaloperationare necessaryforaconditiontobesatisfied. Disjunctions:whenonlyoneoperandofthelogicaloperationisneeded tosatisfyacondition. Negation:Whenthevalueofanoperandisreversed. Table11.7providesthelistoflogicaloperatorsavailableinTSL. Operator
&& || ! Description And (Conjunction) Or (Disjunction) Not (Negation) Usage Example
4 > 2 && 0 > 2 # the result is 0 (false) 4 > 2 || 0 > 2 !(4 > 2) # the result is 1 (true) # the result is 0 (false)

Table 11.7: Logical operators. Concatenation Concatenationallowsyoutojoin2valuesasstrings.Theampersand (&)characterisusedforconcatenation.Anexampleofthisoperationis:


foo = Hello & World; # foo has the value Hello World

Assignment Assignmentstatementschangethevalueofavariable.Theequalsign (=)istheassignmentoperatorandtheoperationsimplyevaluatesthe expressionontherightsideoftheassignmentoperatorandassignsthis valuetothestoragecontainerontheleftsideoftheassignment operator. Severalshortcutformsalsoexistforcombininganassignment operationwithothertypesofoperations.Theseshortcutsandtheir expandedformsarelistedinTable11.8below: Operator
+= -=

Usage Example
foo += 2; foo -= 2;

Comparable construct
foo = foo + 2; foo = foo 2;

*= /= %= ^= or **= &=

foo *= 2; foo /= 2; foo %= 2; foo ^= 2; foo **= 2; foo &= Hello;

foo = foo * 2; foo = foo / 2; foo = foo % 2; foo = foo ^ 2; foo = foo ** 2; foo = foo & Hello;

Table11.8:Assignmentoperators.

CAUTION: You must not put a space between symbols when operators are made up of two or more symbols.

Conditional Conditionaloperatorsareusedasashorthandmethodforperforming assignmentsbasedontheresultofacondition.The?and:operators areinvolvedinthisoperationandtheyareusedinthefollowing syntacticform: Syntax:


variable = condition ? truevalue : falsevalue;

Inthisconstruct,iftheconditionevaluatestotrue,thevariableissetto thevalueindicatedbytruevalue.However,iftheconditionisfalse,the variableissettofalsevalue.

Branching
Branchingstatementsallowyourcodetoavoidexecutingcertain portionsofcodeunlessaspecifiedconditionismet.Thiscondition evaluatestoaBooleanvalueoftrueorfalse.Whenthecondition evaluatestotrue,wesaythattheconditionismetandwhenit evaluatestofalse,wesaytheconditionisnotmet. TSLusestheresultingvalueofaconditiontodecidewhatcodeto execute.TherearetwoformsofbranchingstatementssupportedinTSL andthesearetheifstatementandtheswitchstatement.

NOTE: In TSL, 1 represents a Boolean value of true, and 0 represents a Boolean value of false.

If Statements
Syntax:
if ( condition ) { [ statements; ] [ } else { [ elsestatements; ] ] }

Thefirstformofabranchingstatementthatwewilllookatistheif statement.Thisstatementallowsuserstoexecutecodeonlyifacertain conditionismet.Thesyntaxfortheifstatementisshownabove,but thoughitlooksintimidating,itisnt.Thesyntaxrepresentsthethree differentformsofwritingtheifstatement.Theseformsare:

The if Form
Syntax:
if ( condition ) { [ statements; ] }

Inthisformoftheifstatement,thespecifiedstatementsareonly executediftheconditionevaluatestotrue.Iftheconditionisfalsethen thevalueisnotprinted.Anexampleofthisis:


if ( x > 0 ) { pause("Positive"); }

ThisdisplaysthemessagePositiveinadialogwhenthevalueofx exceeds0.Thisisthesimplestformoftheifstatement.

The if-else Form


Syntax:
if ( condition ) { [ statements; ] } else { [ elsestatements; ] }

Inthisform,oneofthetwosetsofstatementwillalwaysbeexecuted.If thespecifiedconditionevaluatestotrue,thestatementsintheifblock areexecuted.However,iftheconditionevaluatestofalse,thenthe elsestatementsareexecuted.

Sincetheconditioncanneverbebothtrueandfalseatthesame time,onlyonesetofstatementsareexecuted.Therefore,thisformis bestsuitedforaneitherorsituationwhereyoualwaysexpecttoeither executestatementsaorstatementsb.Thefollowingcodedisplaysan exampleofusingthisformoftheifstatement:


if ( x > 0 ) { pause("Positive"); } else { pause("Not positive"); }

WhenthisTSLcodeblockexecutes,themessagePositiveisdisplayed whenthevalueisgreaterthanzero,ifthevalueiszeroorless,thenthe messageNotPositiveisdisplayed.Inallinstances,youwillalways seeonemessageortheother.

The if-else-if Form


Syntax:
if ( condition ) { [ statements; ] } else if ( condition ) { [ elseifstatements; ] [ } else { [ elsestatements; ] ] }

Thisformisbestsuitedforamultiplechoicescenariowhereyouwant toexecuteasinglesetofstatementsbasedonalistofconditions.Notice thattherearemultipleconditionsandtheadjacentcodeisonly executediftheentryconditionismet.Thefollowingcodeisan exampleofthisform:


if ( foo > 0 ) { pause("Positive"); } else if ( foo == 0 ) { pause("Zero"); } else { pause("Negative"); }

Whenthisexecutes,onlyonesetofTSLcodeisexecuted.The evaluationoftheconditionsbeginsfromthefirstlineandoncea conditionevaluatestotrue,therelatedcodeblocksareexecuted.You

maynoticethatatanytime,avaluecanonlybegreaterthanzero,zero, orlessthanzero. Youshouldbecarefultoensurethattwoconditionscannot evaluatetotrueatthesametime,iftheydo,onlythefirstscenario wheretheconditionevaluatestotrueisexecutedasshowninthe followingcode:


if ( foo > 0 ) { pause("Positive"); } else if ( foo > 20 ) { pause("Greater than 20"); } else if ( foo == 0 ) { pause("Zero"); } else { pause("Negative"); }

whenfoo > 20istrue,foo > 0isalsotrue.Butbecausefoo > 0isevaluated beforefoo > 20(duetoitslocationintheifstatement)themessage Greaterthan20canneverbeseen.Youshouldbecarefultoavoidthis inyourcode.

switch statement
Syntax:
switch ( testexpression ) { [ case value1[ , value2, value-n]: [ statements; ] ] [ default: [ defaultstatements; ] ] }

AnotherbranchingstatementthatissupportedinTSListheswitch statement.Theswitchstatementusesthevalueofasinglecontrolling expressiontodeterminetheappropriatesetofstatementstoexecute. Asshownabove,theswitchstatementcontainsalistofconstantvalues andwhichevermatchesthetestexpressiondeterminesthesetofcodeto execute. Theexecutionofaswitchstatementcanbedescribedtoruninthe followingorder: 1. Thetestexpressionisevaluated. 2. Eachcasestatementwithintheswitchstatementisevaluatedandif theconstantvaluematchesthevalueofthetestexpression,the embeddedstatementsareexecuted.

3. Ifnocasestatementhasamatchingvalue,theembedded statementsinthedefaultlabelareexecuted. 4. Ifnocasestatementhasamatchingvalueandthereisnodefault label,nocodeisexecutedintheswitchstatementandexecution continueswiththenextstatementaftertheswitchstatement. Thefollowingcodeusesaswitchstatementtoevaluateaninput variableanddeterminesifthevariablematchesYorN.


switch (foo) { case "Y", "y": pause("Yes"); break; case "N", "n": pause("No"); break; default: pause("Unkown value"); }

NoticethatthecasestatementhasbothYandybecausewewishto doacaseinsensitivecomparison.Youmayalsonoticethebreak statementthatisincludedaftereachcasestatement.Thisisusedto preventrunthrough,ifyoudontusethebreakstatement,allthecode followingyourcaselabelwillbeexecuted.

Loops
Loopsprovidetheabilitytorepeatexecutionofcertainstatements. Thesestatementsarerepeatedlyexecuteduntilaninitialcondition evaluatestofalse.TSLsupportsfourdifferenttypesofloopsandthese arethewhile, do..while, forandfor..inloops. Wewillnowlookcloselyateachofthesetypesofloops,butbefore wedo,wewillexaminetheconceptofinfiniteloops.

Infinte Loops
Becausealooprepeatstheexecutionofastatement,itispossiblefor thelooptokeeprunningwithoutstopping.Thisisknownasaninfinite loopanditisoneofthebiggestproblemsthatcanoccurwithloops.It occurswhentheconditionthatshutsofftheloopneverevaluatesto false.Topreventinfiniteloops,ensurethat: a.Youaremodifyingtheloopvariable.

b.Theloopconditionwilleventuallyevaluatetofalse.

The while Loop


Syntax:
while ( condition ) { [ statements; ] }

Thewhileloopisthesimplestformoftheloopanditsimplyrepeats executionuntiltheconditionevaluatestofalse.Thefollowingcode showsanexampleofusingthewhileloop.


foo = 1; while ( foo <= 3 ) { pause(foo); foo++; }

Thiscodedisplaysthenumbers1,2and3inamessageboxon execution.Noticethattheloopvariableisbeingincrementedusingthe ++(increment)operator.

NOTE: When using a while loop, you must modify the loop variable so you don't have an infinite loop.

The do..while Loop


Syntax:
Do { [ statements; ] } while ( condition );

Asecondformofloopingstatementsisthedo..whileloop.Thisloopis usedwhenatleastoneexecutioniterationisrequiredoftheloop. Noticethattheconditionislocatedatthebottomoftheloopstatement so,allstatementsembeddedwithintheloophavealreadybeen executedatleastonce.Theloopsimplyallowsustodeterminewhether torepeatexecutionoftheloop. Thefollowingexampleshowshowtousealooptoperformthe sameoperationasthewhileloopabove.


foo = 1; do

{ pause(foo); foo++; } while ( foo <= 3 );

Thiscodedisplaysthevalues1,2,and3justasyoumayexpect.Now lookatthisfollowingexample:
foo = 10; do { pause(foo); foo++; } while ( foo <= 3 );

Inthisexample,eventhoughtheloopvariablebeginsat10,theloop stillexecutesanddisplays10.Thisismessageisonlydisplayedonce becauseinordertocontinue,theconditionmustbeevaluatedandthe conditionfoo<=3evaluatestofalse. Agoodwaytolookatthedo..whileloopisthatitworksexactly likeawhileloopunlessincaseswhentheloopconditioninitially evaluatestofalse.Intheseinstances,thewhileloopwillnotrunatall butthedo..whileloopwillrunonce.

The for Loop


Syntax:
for ( initializer; condition; modifier ) { [ statements; ] }

Oneofthemaincriticismsoftheotherformsofloopsisthatitisoften difficulttotrackthestartingvalueandloopmodificationstatements. Thisisbecausethestartingvaluecanoccuranywherebeforethewhile ordo..whilestatement,andtheloopmodificationcanoccuranywhere withinthewhileanddo..whilestatement.Thiscanpotentiallycause errorswhereyoumodifyyourloopvariabletwice,orpossiblynotat all. Theforloopavoidsboththeseproblems,asshownabout,inthe definitionstatementoftheloop,theinitializer,conditionandmodifiers aredisplayedonthesameline.Thismakesiteasytoseewhatvalue yourloopstartsfrom,theconditionthatendstheloopandhowthe loopvariableismodifiedaftereveryiteration. Tobeclear,theforloopisverysimilarinnaturetothewhileloop withtheonlydifferencebeingthatitenforcesaloopmanagement

structurethatthewhilelooplacks.Thefollowingcode,showshowto useaforlooptorewritethecodewecreatedforourwhileloopearlier.
for ( foo=1; foo <= 3; foo++ ) { pause(foo); }

Noticethatinformationabouttheloopismucheasiertoreadinthis structure.Wheneverusingtheforloop,makesureyoudonotmodify theloopvariablewithinthebodyoftheloop.Thismistakeiseasyto makeifyouareusedtoworkingwiththewhileloop.

The for..in loop


Syntax:
for ( variable in array ) { [ statements; ] }

Thefinalloopstatementwhichwewilllookatisthefor..instatement. Thisloopdiffersfromthe3previousloopswehavelookedatbecause itisusedtoiterateoverthevaluesthatexistwithinanarrayandnot untilaconditionbecomesfalse. Asshownfromthesyntax,thefor..inlooprepeatsforeachvalue withinthearrayandwitheachexecution,thevariableissettoavalue withinthearray.Torecreatethesameoperationswehaveusedforthe otherloops,wewouldneedthefollowingcode:


bar = {1, 2, 3}; for ( foo in bar ) { pause(foo); }

ThesearethedifferentloopsthatexistinTSL.Youwillagreethatthe differencebetweeneachoneofthemismostlysubtle.Inmostcases, eachloopformcanbeusedinplaceoftheotherso,thetypeofloop youchoosetowriteismostlybasedonwhatyouaremostcomfortable with.

Loop Modification
Whenrepeatingcertainoperations,theremaybeinstancewhenyou wishto(a)skipexecutionforthecurrentiterationor(b)stoptheloop beforetheloopconditionevaluatetotrue.TSLprovideskeywordsthat canbeusedtohandlethesescenarios.

Skipping a loop iteration


Whenyouwanttoavoidexecutionforcertainvaluesinyour loop,youusethecontinuestatement.Thisstatementsimply transfersexecutiontothenextiterationoftheloop.
foo = 1; while ( foo < 10 ) { print( foo++ ); if ( foo % 2 == 0 ) continue; }

Whentheabovecodeexecutes,thevalues1,3,5,7&9are printed.Foreachevennumber,theconditionfoo % 2 ==0 evaluatestotrueandsothecontinuestatementisexecuted.This skipsthelooptothenextexecution.

Escaping from a Loop


Sometimesinthemidstofrepeatinganactivity,youmaywish toescapefromtheloop.Forthis,youwillusethebreak statementwhichallowsyoutoexitimmediatelyoutoftheloop andrestartprogramexecutiononthenextlineaftertheloop.
foo = 1; while ( foo < 10 ) { print( foo++ ); if ( foo % 2 == 0 ) break; }

Onexecution,thecodeprintsthevalues1andthenescapes fromtheloopbecausethefoo % 2 == 0conditionevaluatestotrue.

Functions
FunctionsareblocksofcodecontainingoneormoreTSLstatements. Thesecodeblocksareveryusefulinperformingactivitiesthatneedto beexecutedfromseveraldifferentlocationsinyourcode.TSLprovides manybuiltinfunctionsaswellasprovidesyoutheabilitytocreate yourownuserdefinedfunctions. InTSL,asinmostlanguages,youhavetheabilitytopass informationintoafunction.Thefunctioncanthenprocessthis information.Afunctionalsohastheabilitytoreturnsomeresultfrom itsprocessing. Therearetwostepsinvolvedwithworkingwithafunction.The firststepinvolvescreatingthefunctionbydeclaringit.Thestatements thatafunctionwillperformisaddedinthisstepandanyreturnvalues

thatwillbeprovidedisalsoaddedatthistime.Thenextstepaftera functionisdeclaredistocallthefunction.Thefunctioncallexecutes thecontentsofthepreviouslydeclaredfunction. Wewillbeginbylookingatthetwotypesoffunctionsandthen lookattheprocessinvolvedwithdefiningthefunctions.

Built-In Functions
TSLprovidesafewhundredfunctionsforvarioususes.Whilethismay sounddaunting,thankfullythesefunctionsarebrokendowninto groups.Table11.9showsthedifferentgroupsofbuiltinfunctions availableinTSL.Also,itisimportanttorememberthatcertain functionsmayonlybeavailablewheneveraspecificaddinisincluded withintheenvironment. YoumayrefertoChapter4onhowtoincludeanaddin. Function Type
Analog Description Functions that are used to track mouse motion over the screen as well as record the clicks of the mouse including the buttons that are clicked. These functions can also be used to track keyboard input. Functions for handling the various GUI objects that exist within the AUT. These functions are inserted by WinRunner into the test as you perform a matching operation in the AUT. Functions that allow you to extend the functionality of WinRunner. Using these functions, you can enhance WinRunner in any of the following ways. Add functions to the Function Generator Specify new functions to be used in your test during recording Create functions for interacting with the user interface Create new GUI checkpoints Standard Functions for performing several operations such as mathematical computation, string manipulation, date/time interactions, array handling etc.

Context Sensitive

Customization

Table 11.9: Function Types in TSL.

User Defined Functions


Whennobuiltinfunctionprovidesthefunctionalityyouwant,you mayneedtocreateauserdefinedfunction.Userdefinedfunctionsare differentfrombuiltinfunctionsonlybecauseyouhavetodefinethe functionsyourself(hencethenameuserdefined).Illshowyouhowto defineyourfunctions,andthendiscusshowtoinvokebothuser definedandbuiltinfunctions.

Defining Functions
Syntax:
[ class ] function functionname ( [ [ mode ] parameterlist ] ) { [ statements; ] [ return value; ] }

Thesyntaxstructureaboveshowsthestructuralelementsfordefininga function.Below,Ihaveprovidedadetaileddescriptionofeachitem fromafunctionsdefinition.


class:[optional]Validvaluesareeitherstaticorpublic.Usingpublicmakes thefunctionavailabletoothertests,andincontrast,usingstatic

limitsaccesstoonlythecurrenttestormodulethatdefinesthe function.
functionname:[required]Avalueconformingtotherulesspecifiedinthe

NamingRulessectiondefinedearlier.
mode:[optional]Avaluedeterminingthedirectionofinformationflow intoandoutofthefunction.Eachparameterintheparameterlisthas

adifferentmodeandthevalidchoicesare:
inpassesavalueintothefunction. outpassesavalueoutofthefunction. inoutpassesavalueintoandoutofthefunction. parameterlist:[requiredwhenamodeisspecified]Alistofcomma

separatedvariablesthatcanbeusedtopassvalueintoafunction andalsoretrievevaluesfromthefunction.Themodedetermines whetherthevariableisusedtopassvaluesintoorretrievevalues fromthefunction. Functionscanalsocontainareturnstatement.Thereturnstatementmay beusedtoreturnavaluefromthefunctionortoterminateexecutionof thefunction.Thereturnstatementisoptional

NOTE: All variables used in a function must be declared as either the static or auto class.

1 2 3 4 5 7

function sum(in var1, inout var2, out var3) { auto answer; answer = var1 + var2; var3 = time_str(); return answer; }

Listing 11.1: A TSL function definition.

Invoking Functions
Syntax:
functionname ( [parameterlist ] );

Touseafunction,thefunctionmustbeinvoked.Thisisalsoknownas callingafunction.Theprocessforcallingabuiltinfunctionisexactly thesameascallingauserdefinedfunction.Beforeyoucancallany function,youmustknowthefollowingdetails: Purpose:Whatthefunctiondoes. FunctionName:Thenameofthefunction. ParameterList:Thelistofvaluestopassintothefunction.Thislistis commaseparatedandshouldmatchthenumberofparametersin thefunctiondefinition.Themodeofeachofparameterisalso importantindeterminingwhethertopassavalueorvariabletoa function.Ihavelistedbelowwhatyoucanpassforeachmode.
inpassavalueoravariable. outpassavariable. inoutpassavariable.

ReturnValue:Anyvaluethatmaybereturnedfromthefunction.Some functionsdonotreturnavalueandwhentheydo,youmay choosetoignorethereturnvalue. InthecodeshowninListing11.2,Ihaveshownhowtoinvokethe functionthatwaspreviouslydefinedinListing11.1


1 2 3 static numVar, numResult, strExecution; numVar = 20; numResult = sum( 3, numVar, strExecution);

4 5

print(Result: & numResult); print(Execution Date/Time: & strExecution);

Listing 11.2: TSL code to invoke a function. Onexecution,thiscodewilldisplaythefollowinginmessagelog window:


Result: 23 Execution Date/Time: Thu Apr 26 13:38:41 2007

Thefollowingdescribeswhathappensineachthelineofcodefrom Listing11.2.
Line 1createsthreevariablesthatwewilluseinthistest.Dontforget thatvariabledeclarationisoptionalinTSL. Line 2initializesthenumVarvariabletothevalue2. Line 3invokesthesum()function.Wepassthevalue3tothefirst parameterofsum()whichhasamodeofin.Thesecondparameterhasan inoutmodesowemustpassavariable.Wepassthevalue20throughthe variablenumVar.Thethirdparameterismodeoutsowepassavariable strExecutiontothisparameter.Thevalueofthisvariablewillbechanged inthesum()function.Theresultofthefunctioncallisassignedtoour numResultvariable. Line 4printsoutthecontentsofnumResult.Thisisthesumofthefirst2 parameters. Line 5printsoutthecontentsofstrExecution.Thisisthedate/timewhenthe functionwascalled.

Useful TSL Function


IhaveincludedbelowsomeveryusefulTSLfunctions.Thesefunctions havesuchrepeatedusageintestcreationthatitisbeneficialtoknow thembyheart.Theyare:
callExecutesaWinRunnertest. call_exLaunchesQuickTestProfessionalandexecutesaQTPtest.QTP mustbeinstalledonthemachineforthisfunctioncalltowork. file_compareComparesthecontentsoftwofilesandwritestheresultof thiscomparisontothetestresultslog. invoke_applicationUsedtolaunchanapplication.Thisisthepreferred wayoflaunchinganapplicationinsteadofnavigatingthroughthe Windowsprogrammenu.

loadLoadsaWinRunnerfunctionlibraryintomemoryforusage. load_GUILoadsaGUIMapfileintomemoryforusage.Thecontentsof theGUIMapfilecanthenbeusedduringtestexecution. pauseDisplaysamessageinadialogandpausestestexecutionuntil theuserdismissesthedialog. printWritesoutvaluestotheprintlog.Thisisusefulwhenyoudont wanttopauseexecution,andalsodontneedthemessagesavedtothe testresultswindow. report_msgUsedtosendinformationtothetestresultwindow.This doesnotaffecttheresultofthetest. set_windowSetsthecontextwindowi.e.thewindowinwhichall subsequentoperationswillbeperformedin.Thisisperhapsthemost importsfunctioninTSL. tl_stepMarksastepaspass/failandsendthecorresponding informationtothetestresultwindow.

THINGS TO WATCH OUT FOR WHEN WRITING TSL


1. Case sensitivity. 2. Use semi-colon to complete every simple statement. 3. Use curly braces with each compound statement. 4. Pair up double quotes, parentheses and curly braces. 5. Use = for assignment and == for equality.

Summary
InthischapteryouhavelearnedabouttheTSLlanguage.Webeganby lookingatthecontentsofthelanguageandthedifferentsyntax structuresthateachoftheprogramelementsuse.Finally,Idescribed theuseoffunctionsandprovidedalistofusefulfunctionsthatexistin TSL.Inthenextchapterwewilluseeverythingwehavelearnedin createdsometests.

Вам также может понравиться