Академический Документы
Профессиональный Документы
Культура Документы
TESTSCRIPTLANGUAGE
TIP: To access the WinRunner help system at any time, press the F1 key.
History
TSLstandsforTestScriptLanguageandisoftenreferredtobyits acronym.CreatedbyMercuryInteractiveanusedinseveraloftheir productlineincludingWinRunner,XRunnerandLoadRunner,TSLhas similaritiesinfunctionalityandkeywordstotheClanguageandanyof itsderivatives.KnowledgeofsimilarlanguagesasJavaScript,Perlor JavawouldaidinyourquickunderstandingofTSL.
foo(); bar();
canthenbewrittenas:
foo(); bar();
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
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.
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;
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
Whenyouarereferringtofilenamesonacomputer,paycareful attentiontoescapesequences.Referringtothefile:
C:\newfile.txt
Willbeinterpretedbythesystemas
C: ewfile.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
Meaningthatthatyoueitherwrite
class variable;
or
class variable = value;
Constants
Syntax:
const CONSTANT = value;
Thisway,insteadofwriting:
foo = 30 / 7;
wheneveryouaredoingdatebasedcalculations,youcanwrite:
foo = 30 / DAY_IN_WEEK;
Arrays
Sometimesyoumaywanttostoreseveralpiecesofrelateddatasuchas names.Onewaytodothisistodeclaredifferentvariablesforeach valuee.g.
name1 = "John"; name2 = "Jane"; name3 = "Joe";
printsoutthethreenamesinmyarray.Ifthearrayhad50separate values,Iwouldstilluseasimilarlycompactamountofcodetoprintall
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";
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
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)
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)
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 = 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.
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; ] ] }
The if Form
Syntax:
if ( condition ) { [ statements; ] }
ThisdisplaysthemessagePositiveinadialogwhenthevalueofx exceeds0.Thisisthesimplestformoftheifstatement.
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.
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.
NOTE: When using a while loop, you must modify the loop variable so you don't have an infinite loop.
Thiscodedisplaysthevalues1,2,and3justasyoumayexpect.Now lookatthisfollowingexample:
foo = 10; do { pause(foo); foo++; } while ( foo <= 3 );
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); }
Loop Modification
Whenrepeatingcertainoperations,theremaybeinstancewhenyou wishto(a)skipexecutionforthecurrentiterationor(b)stoptheloop beforetheloopconditionevaluatetotrue.TSLprovideskeywordsthat canbeusedtohandlethesescenarios.
Functions
FunctionsareblocksofcodecontainingoneormoreTSLstatements. Thesecodeblocksareveryusefulinperformingactivitiesthatneedto beexecutedfromseveraldifferentlocationsinyourcode.TSLprovides manybuiltinfunctionsaswellasprovidesyoutheabilitytocreate yourownuserdefinedfunctions. InTSL,asinmostlanguages,youhavetheabilitytopass informationintoafunction.Thefunctioncanthenprocessthis information.Afunctionalsohastheabilitytoreturnsomeresultfrom itsprocessing. Therearetwostepsinvolvedwithworkingwithafunction.The firststepinvolvescreatingthefunctionbydeclaringit.Thestatements thatafunctionwillperformisaddedinthisstepandanyreturnvalues
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
Defining Functions
Syntax:
[ class ] function functionname ( [ [ mode ] parameterlist ] ) { [ statements; ] [ return value; ] }
limitsaccesstoonlythecurrenttestormodulethatdefinesthe function.
functionname:[required]Avalueconformingtotherulesspecifiedinthe
NamingRulessectiondefinedearlier.
mode:[optional]Avaluedeterminingthedirectionofinformationflow intoandoutofthefunction.Eachparameterintheparameterlisthas
adifferentmodeandthevalidchoicesare:
inpassesavalueintothefunction. outpassesavalueoutofthefunction. inoutpassesavalueintoandoutofthefunction. parameterlist:[requiredwhenamodeisspecified]Alistofcomma
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; }
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.
4 5
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.
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.
Summary
InthischapteryouhavelearnedabouttheTSLlanguage.Webeganby lookingatthecontentsofthelanguageandthedifferentsyntax structuresthateachoftheprogramelementsuse.Finally,Idescribed theuseoffunctionsandprovidedalistofusefulfunctionsthatexistin TSL.Inthenextchapterwewilluseeverythingwehavelearnedin createdsometests.