Está en la página 1de 76

http://www.geocities.

com/pammal_sureshbabu/silktest/ SilkTest Tutorial


Testing The primary reasons to test the applications are to identify the defects and measure the quality of the application. Types of testing Different kinds of testing There are different types of tests that can be executed depending on the objectives of the test engineer. Error testing Verify the products responses to error conditions. These tests ensure that the responses are meaningful, correct, and may include the display of context-sensitive, error-specific help screens. Reviewing error message lists may help to identify each error which can be generated by a specific screen or module. Stress testing Measure the systems response to large amounts of data. This may include singleusers manipulating large sets of data, or multiple machines running the application simultaneously. White - Box testing Places the focus on the internal structure of the software. Tests are designed using the code and the functional specification as input. Black - Box testing Views the software from the end-user perspective, and is unaware of the underlying code. Distributed testing Is concerned about the behavior of the client software as well as the data being stored and manipulated at the server. This may include verification of startup data, modifications to tables, verification that cascading deletes are correct, and that dependencies between database tables are correct. Multi - User testing Includes concurrency tests which verify the interaction of two simultaneous users on two separate machines. For example, if one user locks a record, a second user may receive an error message when attempting to lock the same record. Stress testing

verifies the response of the system when a large number of users are connected to the database. Other types of tests verify that a process on one machine is capable of initiating a process on another machine. SilkTest overview SilkTest: SilkTest is a tool specifically designed for doing regression1 and functionality testing. It is developed by Segue Software Inc. SilkTest is the industry's leading functional testing product for e-business applications, whether Window based, Web, Java, or traditional client/server-based. SilkTest also offers test planning and management, direct database access and validation, the flexible and robust 4Test scripting language, a built-in recovery system for unattended testing, and the ability to test across multiple platforms, browsers, and technologies. The version of SilkTest which is being used is the 5.0.3. You have two ways to create automated tests using silktest:

1. Use the Record Testcase command to record actions and verification steps as
you navigate through the application.

2. Write the testcase manually using the Visual 4Test scripting language.
1. Record testcase 2 The Record/Testcase command is used to record actions and verification steps as you navigate through the application. Tests are recorded in an object-oriented language called Visual 4Test. The recorded test reads like a logical trace of all of the steps that were completed by the user. The SilkTest point-and-click verification system allows you to record the verification step by selecting from a list of properties that are appropriate for the type of object being tested. For example, you can verify the text that is stored in a text field. 2. Write the testcase manually We can write tests that are capable of accomplishing many variations on a test. The key here is re-use. A testcase can be designed to take parameters including input data and expected results. This data-driven testcase is really an instance of a class of testcases that performs certain steps to drive and verify the application-undertest. Each instance varies by the data that it carries. Since far fewer tests are written with this approach, changes in the GUI will result in reduced effort in updating tests. A data-driven test design also allows for the externalization of testcase data and makes it possible to divide the responsibilities for developing testing requirements and for developing test automation. For example, it may be that a group of domain experts create the Testplan Detail while another group of test engineers develop tests to satisfy those requirements.
1

A set of baseline tests that are run against each new build of an application to determine if the current build has regressed in quality from the previous one. 2 In a script file3 , an automated testcase that ideally addresses one test requirement. Specifically, a 4Test function that begins with the testcase keyword and contains a sequence of 4Test statements. It drives an application to the state to be

tested, verifies that the application works as expected, and returns the application to its base state. 3 A script file is a file that contains one or more related testcases. A script file has a .t extension, such as find.t. Other Segue products The Silk products include SilkTest for functional and regression testing SilkPerformer for load and performance simulation SilkPilot for functional and regression testing CORBA and EJB servers SilkRadar for automated defect tracking SilkVision for enterprise application health monitoring SilkExpress for a scalability and load testing consulting

solution

Features of silktest SilkTest Features: Some of the features of silktest are given below. Easy-to-use interface Built-in recovery system The object oriented concept Record & Play Multi-kind application testing Automatic generation of results Browser & Platform independent Distributed testing 24x365 unattended testing Power Testing with the 4Test Language Centralized Testing of Distributed Applications Distributed Access to Test Results Extensive Component Testing Cross-Platform Java Testing Testing Across Multiple Browsers and Windows Versions Support for HTML, XML, JavaScript, Java, ActiveX, Windows controls, and Visual Basic Single-recording testing for cross-platform Java testing with the SilkBean Against Over 35 Databases Link Tester Validation of Advanced Database Structures and Techniques Creation of o Test Plan o Test Frame o Test Suite Integration with other silk products.

Components of silktest SilkTest architecture Normal use of an application consists of a person manipulating a keyboard and mouse to initiate application operations. The person is said to be interacting with the GUI (Graphical User Interface). During SilkTest testing, SilkTest interacts with the GUI to submit operations to the application automatically. Thus SilkTest can simulate the actions of a person who is exercising all the capabilities of an application and verifying the results of each operation. The simulated user (SilkTest) is said to be driving the application. The application under test reacts to the simulated user exactly as it would react to a human user. SilkTest consists of two distinct software components that execute in separate processes: The SilkTest host software The 4Test Agent software

SilkTest host software The SilkTest host software is the program you use to develop, edit, compile, run, and debug your 4Test scripts and testplans. This manual refers to the system that runs this program as the host machine or the SilkTest machine. The Agent The 4Test Agent is the software process that translates the commands in your 4Test scripts into GUI-specific commands. In other words, it is the Agent that actually drives and monitors the application you are testing. One Agent can run locally on the host machine. In a networked environment, any number of Agents can run on remote machines. This manual refers to the systems that run remote Agents as target machines. In a client/server environment, SilkTest drives the client application by means of an Agent process running on each applications machine. The application then drives the server just as it always does. SilkTest is also capable of driving the GUI belonging to a server or of directly driving a server database by running scripts that submit SQL statements to the database. These methods of directly manipulating the server application are intended to support testing in which the client application drives the server. Limitations of silktest Limitations of SilkTest: Some of the limitations of SilkTest are given below. SilkTest may not recognise some objects in a window / page due to some technical reasons. SilkTest may not recognise some window frames. The 'tag' value may get changed frequently. Sometimes it will be difficult to activate some window.

It may be necessary to make some modifications if testing should be shifted to other browser/operating system. In web based applications, sometimes silktest will take the links as simple text.

System requirements The minimum requirement, a system needs to run the silk test is given below. o o o o Windows NT, Windows 95, 98 or 2000 Pentium 466 Mhz or better processor (application dependent) 32 MB RAM 60MB Hard Disk

Supported Environments:
o o o o o o Netscape Navigator 4.x Internet Explorer 4 and 5 ActiveX, Visual Basic 5 and 6 Java JDK 1.3 Swing 1.1 Microsoft Web browser control

The automated testing process The automated testing process The testing process has these four steps: 1 Creating a testplan (if you are using the testplan editor) 2 Recording a test frame 3 Creating testcases 4 Running testcases and interpreting their results Creating a testplan If the testplan editor is used,the automated testing process is started by creating a testplan. A basic testplan is structured as a hierarchical outline and contains: Descriptions of individual tests and groups of tests.As many levels of description can be used. Statements that link the test descriptions in the plan to the 4Test routines, called testcases, that accomplish the actual work of testing.

Recording a test frame

Next, record a test frame, which contains descriptions, called window declarations, of each of the GUI objects in your application. A window declaration specifies a logical, cross-platform name for a GUI object, called the identifier, and maps the identifier to the objects actual name, called the tag. In addition, the declaration indicates the type of the object, called its class.

Creating testcases The 4Test commands in a testcase collectively perform three distinct actions: Drive the application to the state to be tested. Verify the state (this is the heart of the testcase). Return the application to its original state.

The powerful object-oriented recorder can be used to automatically capture these 4Test commands to interact with the application, or to write the 4Test code manually if one is comfortable withprogramming languages. For maximum ease and power,these two approaches can be combined, recording the basic testcase and then extending it using 4Tests flow of control features. Running testcases and interpreting results Next,run one or more testcases, either by running a collection of scripts, called a suite, or, if you are using the testplan editor, by running specific portions of the testplan. As each testcase runs, statistics are written to a results file. The results file and its associated comparison tools allow you to quickly pinpoint the problems in your application. SilkTest file type: Test Frame A Test Frame The test frame is the backbone that supports the testcases and scripts. It is a file that contains all the information about the applications GUI objects that SilkTest needs when you record testcases.This information minimally consists of a declaration for each GUI object, but can also include any data that you want to associate with each GUI object, as well as any new classes and methods that you want to define. A window declaration specifies a cross-platform, logical name for a GUI object, called the identifier, and maps the identifier to the objects actual name, called the tag. Because the testcases use logical names, if the objects actual name changes on the current GUI, on another GUI, or in a localized version of the application,only the tag in the window declarations need to be changed; dont need to change any of the scripts.Variables, functions, methods, and properties can be added to the basic window declarations recorded by SilkTest. To record declarations for the main window and menu hierarchy of your application: Start up your application and Silktest.

Select File/New. The New dialog appears. Select the Test Frame radio button and click OK.The New Test Frame frame file for an application displayed in the Application list box. Select the application from the Application list box.If a Web application is tested, different fields are seen. Click OK.The new test frame file is created. The file contains the 4Test declarations for the main window and all its menus, as well as a generic declaration that is valid for each of the standard message boxes in the application.

Test Plan A Test Plan A testplan is made up of a large amount of information, a structured, hierarchical outline provides an ideal model for organizing and developing the details of the plan. A testplan consists of two distinct parts An outline that describes the test requirements Statements that connect the outline to the 4Test scripts and testcases that implement the test requirements.

Using the testplan, we can create and run tests. To start a new testplan: Select File/New Select Testplan and click OK.

An empty testplan window opens. Test Suite A Test Suite A Test Suite is a collection of test scripts. Consider a case that we are having a set of script (.t) file. If we want run these scripts against our application, we have to select the required testcase or we have to run the the entire script file. But after the completion of that script file, the user has to manually change that to the next script file to run those testcases available in that script. Instead of that silktest provides a way to continously select a set of script files and run those script files at-a-stretch. This can be done by creating a new Test Suite file and declare the needed script files in that suite file. To start a new test suite: Select File/New. Select TestSuite and click OK. In that suite file enter the script file names to be run continously. Save that script file.

Compile the script file and run it. Now the process of running the script will not stop after the completion of the first script file, instead of that it will automatically pass to the next script file and run the testcases available there.

Assume a case where there is a folder called silkscripts in c drive with five test script files. Here in the suite file, we are calling all the script files instead of running those script files separately. The suite file will look like as given below. // Clickinglinks.t use c:\silkscripts\script1.t use c:\silkscripts\script2.t use c:\silkscripts\script3.t use c:\silkscripts\script4.t use c:\silkscripts\script5.t Test Script A testscript file contains various testcases for various test conditions. Test Case In a script file, a testcase ideally addresses one test requirement. Specifically, a 4Test function that begins with the testcase keyword and contains a sequence of 4Test statements. It drives an application to the state to be tested, verifies that the application works as expected, and returns the application to its base state. Steps to create a testcase

bar.

In the silktest tool, select the File -> New option from the menu

In the resulting dialog box New; there will be options for selecting different kind of files. Select the file type 4 Test script option. It will open a new script file. Before start writing the testcase, declare the necessary file that is to be used in that script file. Start with the keyword testcase followed by the testcase name. The name of the testcase is whatever as selected by the user. But make sure that by looking at the name of the testcase, the objective of the testcase should be understandable. Start the tests from the scratch so that the silktest will start the application and do the testing from the base state. Use necessary conditions / loops if necessary. At the end of each and every script, print a statement to know whether the testcase has achieved its objective or not. The user can make sure that the particular part of the application is error free by looking at the message you print. Try to make the testcase effective and time consuming (say) by keeping the second tests continue from the place where the first tests finishes. A sample testcase for registering in to the yahoo mail.

testcase registration () Browser.LoadPage("mail.yahoo.com") SignInYahooMail.SetActive() SignInYahooMail.objSignInYahooMail.SignUpNow.Click() sleep(3) WelcomeToYahoo.SetActive WelcomeToYahoo.objWelcomeToYahoo.LastName1.SetText("las tname") WelcomeToYahoo.objWelcomeToYahoo.LanguageContent1.Sele ct(5) WelcomeToYahoo.objWelcomeToYahoo.ContactMeOccasionallyA bout.Click() WelcomeToYahoo.objWelcomeToYahoo.SubmitThisForm.Click() if RegistrationSuccess.Exists() else Session II: Lab I : Installation of SilkTest SilkTest installation tips Run the Silk Test setup from the CD or through the Network. The SilkTest software is available in the 'Firesip\Europa\software\silktest5.0.1\silktest' directory in your Network Neighbourhood. Get in to the above folder and select the setup.exe file to start the installation. During installation, it will ask for the licence file. Set the path ''Firesip\Europa\software\silktest5.0.1\licence' for the "licence.dat" file. In the installation process, it will ask for the SilkTest/ SilkTest Agent only option. Select the Silk Test option if you are installing this for testing applications in the stand-alone machine. For the Will you be testing browsers? message box, select Yes if you are going to test web based applications. It will ask for the default browser option. Select the appropriate Browser you want to test the application using Silk Test. Note that you are allowed to select only one Browser option. By default SilkTest goes fine with Netscape browsers. After installing, it will open the SilkTest tool with the Quick start wizard open. The quickstart wizard will assist you in creating various silk files. If you are a first time user of silktest, then continue with that. logerror("Test Fail") print("Test Pass")

Getting started with the QuickStart Wizard

If you are using SilkTest with the testplan editor, you can use the QuickStart Wizard, which greatly simplifies the four steps of automated testing. When you start SilkTest the first time (or whenever you start and have no open windows), the QuickStart Wizard is displayed automatically. You can also invoke the wizard at any time by selecting File/New and clicking the QuickStart Wizard icon. You can use the QuickStart wizard to: 1 Create a testplan. You simply name the file (giving it the .pln extension) and its directory. 2 Create a test frame, which contains descriptions of the GUI objects in your application that you want to test.As prompted, you simply open your application and open the various windows and dialogs that you want to test in the application. The wizard automatically records all the declarations in a file called frame.inc. You dont have to do any coding. 3 Record testcases. You name the testcase and provide a description for the testplan, then simply record the testcase. Again, you dont have to do any coding. The wizard automatically saves the testcase in a script (.t) file with the same name as the testplan. 4 Run testcases. Procedure To use the wizard: 1 Invoke the wizard by selecting File/New and clicking the QuickStart Wizard icon. Now you will name a new testplan, which will organize and manage your tests. 2 Click Next. 3 Name the file edit.pln and click Next. The next step is to record the test frame, which defines all the windows, dialogs, menus, and so on that you want to test. 4 To create a new test frame, leave New Test Frame selected and click Next. At this point, the wizard lists all the open (running and not minimized) applications. If Text Editor is not open, you can open it now (it is in the directory where you installed SilkTest). After you open the Text Editor, click on the QuickStart Wizard title bar to see Text Editor added to the list of applications. 5 Select Text Editor and click Next. 6 The Capture Windows panel displays, describing the procedure. 7 Click Next. 8 Now you simply open a document window and open all the dialogs that you want to test in the Text Editor. When you place the mouse pointer on a window or dialog, the wizard records all the declarations that SilkTest needs in a file called frame.inc in the same directory as your testplan. 9 When you have finished capturing the windows and dialogs in Text Editor, click Return to Wizard in the Capturing New Windows dialog. Now that you have created your test frame, you are ready to create a testcase. 10 Click Next twice. 11 Name the test FindBox and enter the description Verify controls in Find dialog. Click Next. Your test is now being recorded, as indicated by the Record Status window on your screen.

12 Now go to Text Editor, select Search/Find to open the Find dialog, place your mouse pointer over the dialogs title bar, and press Ctrl+Alt to verify its state. The Verify Window dialog displays. Click OK to verify all properties for the dialog. Close the Find dialog (to return to your base state), then click Done in the Record Status window. You return to the Wizard and are asked to confirm that the test is what you want. 13 Click Next. 14 Run the test by clicking the Run Test Button. 15 The wizard reports the results. You can move the wizard to the side and look at the results file that is created whenever you run a test. 16 In the wizard, click Next to save your testcase. The testcase is saved in a script (.t) file with the same name as the testplan (in this case, edit.t). 17 Click Close to close the wizard. You see a window containing the results file from the test you just ran. In another window is the testplan.

Configuration & Enabling the options Configuring the settings In SilkTest, select Option -> Extentions menu from the menu bar. It will load the Extentions dialog box. In that dialog box, check the kind of application you are testing. Say, if you are testing the web based application in the Netscape browser, Enable the Netscape option by checking against it and un-check all the other options. Click on the OK button. Now click on the Options -> Runtime option. Set the 'use path' option to point to the silktest installed folder. Say if the silktest has been installed in your c:\ drive then set the use files = "C:\Program Files\Segue\SilkTest\EXTEND". This is to use the common include files as per the application. Since we have selected the Extentions, the use file will have the declaration 'extend\netscape.inc' of the include file. Now the script is ready to open the Netscape browser by default and run the scripts. From the status bar Go to the Start -> Programs -> SilkTest -> Extention Enabller option, to declare the same set of extentions ( as in step 4) in the 'Extention Enabler' dialog box.

Exposure to SilkTest IDE To start the SilkTest tool Select the 'Start' button in Windows status bar. Go to 'Programs -> SilkTest -> SilkTest' option (with green color icon) It will open the silktest tool. If you get the QuickStart wizard, close the wizard if you dont need it or else, refer to the 'Installation tips' to go with the wizard.

To compile & run scripts Open the testscript file (with the extention .t). Select the Run -> Compile option from the menu bar. Also we can select the icon with the 'tick' mark to compile the scripts. The files that are associated with the script files will also get compiled. Hence if there is any problem with the include file, you will get error by compiling the testscript file itself. To compile a selected file, keep the mouse cursor on that particular file and give the Run-Compile option. The 'Run' option will get enabled only for the testscript files. We cannot run a include file or a test frame. We can run a testcase selectively, compile the testscript file and click the "=>t" icon in the tool bar. To run the entire set of testcases in a testscript file, click the "==>" icon or select the Run -> Run option. If there is any syntax error in the script file, it will show that if you move to the next line of the code. But the other errors are known only at the time of compilation or during the run.

To open a new or existing files In Silktest, Select the File -> New menu from the menu bar. (or) select from the 'white icon' in the left top corner of the window. It will ask for various kind of files to open. Select the '4Test include file' to declare the window objects from the application. The '4Test Script file' option is to open the script file where we will be writing testscript. The above two files are more important for building the scripts. Open the application you want to test. If you are going to test the Yahoo site, then open the browser load the page you want to start testing. The page that you start testing the application will be assumed as the 'BaseState'. Even we can explicitily declare the window base state. The Test Script file will be used only after creating the include file. We will be using the include file to write the script file. Hence we have to declare the include file that we are calling in the testscript files. To open an existing file, select File -> Open and select the existing file.>

How to start... To write a new plug & play testcase (using Action) This example is to write the script for logging in to the yahoo site. Start the SilkTest by selecting from the 'Start' menu. Configure the settings as given in lab I. Click 'File -> New' menu, and select the '4Test script file' option. Click on the OK button.

Start with the keyword 'testcase Action()' and press Enter key in your keyboard. The testcase is the default keyword for any testcase and the name Action is the name of the testcase. The testcase name can be anything but it is advisable to name it clearly so that will represent the functionality of the test. Now start writing the testcase (Follow the below instrutions). Open the application in parallel. ie., open the browser in which the application has to be run.(say Netscape) Go to SilkTest Click Record -> Actions.. menu from the menu bar. It will load the 'Record Actions' dialog box. Keep the dialog box as it is, go to the application and do the action what ever you want to perform. The silktest will record the events you do sequentially and you can view it in the 'Record Actions' dialog. After completing your task (till whatever you want to record), click on the 'paste to editor' button in the 'Record Action' dialog box. Then click the close button to close the Record actions dialog box and go to your application. Now the recorded code will be readily available in the testscript editor, inside the testcase. Now delete the keyword 'recording' in your first line of the recorded code. Now, select the entire recorded code by keeping the mouse arrow at the leftmost dot (.) in your editor at the first line, and drag it till the end. Right click on the selected code and select the 'Move Left' option. The code is ready now. Now, compile the code from the 'Run -> compile' option and run the script by selecting the 'Run -> Run' menu. Now the testcase will automatically start the application and perform the events recorded and throws the results. The sample recorded testcase for yahoo login look like this: testcase Action() o //[-] recording o BrowserPage.SetActive () o Browser.Location.SetText ("www.yahoo.com") o Browser.Location.TypeKeys ("") o Yahoo.HtmlLink("Mail|#26|$http:??www.yahoo.com?r?m2").Click () o BrowserPage.HtmlTextField("Yahoo! ID:|#1").SetPosition (1, 1) o BrowserPage.HtmlTextField("Yahoo! ID:|#1").SetText ("username") o BrowserPage.HtmlTextField("Yahoo! ID:|#1").TypeKeys ("") o BrowserPage.HtmlTextField("Password:|#2").SetText ("password") BrowserPage.HtmlPushButton("Sign In|#1").Click () Record and play a testcase to login into the hotmail site and logout.

Session III :
The 4Test language The 4Test language

The 4Test language is an object-oriented fourth-generation language (4GL) designed specifically with the needs of the QA professional in mind. 4Tests powerful features are organized into three basic kinds of functionality: A robust library of object-oriented classes and methods that specify how a testcase can interact with an applications GUI objects. A set of statements, operators, and data types that you use to add structure and logic to a recorded testcase. A library of built-in functions for performing common support tasks. Note This section provides a high-level look at 4Test.

Setting the runtime options Customization of scripts by runtime options The Runtime option are set by the user according to the kind of the software that is to be tested. This option should reflect the kind of the application that is to be tested. There are two default settings that has to be done to make a minimal code run. In the Options -> Runtime menu, Set the use path = the path of the 'extend' directory in the installed silktest folder, say "c:\programfiles\segue\silktest\EXTEND" Set the use files = The file you are including for the extension type. This will be automatically set if you select the kind of application you are testing. In the Options -> Extentions menu, set the primary extensions 'Enabled' and disable all the other extentions if not needed. This will automatically add the include file in to the 'use files' option in Options->Runtime. If there is any common file that is used in many areas of the script, then set the path of that file in this 'use files' option. For testing across networks, the protocol should be set in the runtime option. How to declare windows Declaring a window: Take the example of a Yahoo Mail web site.The window declarations are recorded by using the Record-> Window Declarations option available in the silk test. The agent captures all the variables relevant to that screen. Then these variables can be pasted to the silk test editor by using the Ctrl+Alt keys, which will activate the Paste to Editor button in the Record Window Declaration dialog, and these window names & variables will be pasted to the silk test editor. Now captured window will be pasted to the editor as [-] window BrowserChild Yahoo

tag "Yahoo - Netscape" parent Browser [+] HtmlText Home o tag "Home" [+] HtmlText ClickforMail o tag " ClickforMail "

In the above example, the keyword 'Yahoo' is called as the identifier. Using this declaration file, we can start writing testscripts. Creating simple scripts A Sample Testcase with the declaration file Let us consider the sample testcase for registering in the yahoo mail site.

//------------------------------------------------------------------------------------------------------// a sample Window Declaration include file ( decregistration.inc )

//decregistration.inc use "c:\scripts\clsregistration.inc" [-] window BrowserChild SignInYahooMail


o o o o tag "Sign in - Yahoo! Mail" parent Browser [-] HtmlLink SignUpNow tag "Sign up"

[-] window BrowserChild WelcomeToYahoo


o o o o o o o tag "Welcome to Yahoo!" parent Browser [+] HtmlTextField SignUpForYourYahooID1 [+] HtmlTextField SignUpForYourYahooID2 [-] HtmlButton SubmitThisForm tag "Submit this *"

//------------------------------------------------------------------------------------------------------// a sample script file ( registration.t ) use "c:\scripts\decregistration.inc" testcase registration()

Browser.LoadPage("mail.yahoo.com") SignInYahooMail.SetActive() SignInYahooMail.SignUpNow.Click() sleep(3) WelcomeToYahoo.SetActive WelcomeToYahoo.SignUpForYourYahooID1.SetText ("newuser@yahoo.com") WelcomeToYahoo.SignUpForYourYahooID2.SetText("password") WelcomeToYahoo.objWelcomeToYahoo.Entertainment.Click() WelcomeToYahoo.objWelcomeToYahoo.SubmitThisForm.Click() if RegistrationSuccess.Exists() print("Test Pass") else logerror("Test Fail")

//------------------------------------------------------------------------------------------------------Brief Description: The general syntax for performing any operation on the window is as follows <window-name>.<control-name>.<operation> If an operation is to be done on the window itself (not in its controls, say activating a window), Window object need not be mentioned. thus, <window-name>.<operation> CONTROLS / OBJECTS: Controls are the various text fields, html links, buttons, popuplists, check boxes etc., in a browser window or dialog box or in any non web application. OPERATIONS: Depending upon the different type of controls, respective operations are defined. It can be SETTEXT for TEXTFIELDS; CLICK for BUTTONS, CHECK BOXES, LINKS; SELECT for POPUPLISTS etc. In the above example, resister(), is the function name used to do registration in the Yahoo site. Function name can be anything, as the User's choice. Windows are declared in decregistration. The corresponding classes, which consists of the various controls in the window are initialized in clsregistration.inc The command statement, o Browser.LoadPage("www.yahoo.mail.com"), is used to load the site. The command line, SignInYahooMail.SignUpNow.Click(), clicks the link 'signupnow'. Here, 'SignInYahooMai' is the window name, 'SignUpNow', is the name of the control link and 'CLICK()' is the operation performed to click that control link. Similarly Text Values are entered into various text fields in the window 'WelcomeToYahoo' with the help of 'SetText' operator.Note that the inverted commas is necessary with Settext operation, other than when passing parameters. 'WelcomeToYahoo.SubmitThisForm.Click()'will click the button SubmitThisForm. SetActive(), IsActive(), Exists() are some of the methods

used to verify the browser window status. Here there is no need to specify the window object. Print is the method used to print a particular statement on the result file, once the testcase completes execution. logerror behaves similarly like print, except the statement will be printed in red colour in the .res file

How to compile & run scripts? Running the silkscripts The basic silk scripts will be in two forms. One as an include file and the other as a script file. The include file with the extention *.inc can be used for the declaration of window names, window objects, variables, constants, structures and classes. The core objects of the scripts lies here. The script file will be used in writing scripts. It will be with the extention *.t. The body of the scripts will be defined here. ie. the testcases that meets various test conditions will be written in the script file.

The script file (*.t) can be used for declaring objects and the include file (*.inc) for writing testcases. But to make the code clear we use different files for different purposes. If no testcases is written in a file (include) , then the include file can be compiled but cannot be run. It will show error that the file does not contain any testcases.Only the file with the testcase present will be allowed to run. Before running the scripts, seperate declaration file have to be written ( for declaring the objects) and the script file (for writing scripts using that declaration file) and compile them. The steps to be followed for running the scripts are as below. Open the silk test tool. Open the script (*.t) file that has to be run. Compile the script by selecting the Run-> Compile menu from the menu bar (or) from the compile icon. It will compile that particular script and the other related files, called by that script. The user can confirm that by looking at the progress status (in yellow color ) in the bottom-right corner of the silktest tool. If there is any error, the error details are displayed in the compile time. The user has to make necessary changes. Then, select the Run->Testcase from the menu bar (or) else select the Run icon. The testcases can be run by selectively or at-a-stretch. If the selective method is selected, it will ask for the testcase to be run from a list of testcases. After selecting the testcase and start running, the silktest will automatically start the application and start the test from the basestate.

Results file Automatic generation of results

One or more testcases can be run, either by running a collection of scripts, or by running only the selected script (or) testcases. As each testcase runs, statistics are written to a results file. The results file and its associated comparison tools allow you to quickly pinpoint the problems in your application. At the end of the running of each and every testcases, the status of the test will be saved in a result (.res) file and is displayed. The state of the testing can also be known by stopping the test, by pressing the two 'shift' keys simultaneously. The result file contains details such as script name, machine name, started time, elapsed time, total scripts run, total passed, total failed, errors or progress of each and every test case,and whether the testcase run is aborted automatically or externally. For examples: Consider the situation that a script (say login.t) is aborted manually, the generated result file will be as below. Script login.t - 1 error Machine: (local) Started: 04:26:19PM on 25-Jul-2001 Elapsed: 0:00:09Totals: 1 error, 0 warnings *** Program aborted by user Consider the situation that a script (say login.t) is passed, the generated result file will be as below. Script login.t - Passed Machine: (local) Started: 03:13:11PM on 02-Aug-2001 Elapsed: 0:19:47 [ ] Passed: 1 tests (100%) Failed: 0 tests (0%) Totals: 1 tests, 0 errors, 0 warnings [+] Testcase NewGroupMembersDelete - Passed Delete current Member Test Pass *** Warning: DefaultBaseState is closing Browser windows ----------------------------------------------------------Consider the situation that a script (say login.t) is failed due to some error, the generated result file will be as below. Script login.t - 1 error Machine: (local) Started: 03:13:11PM on 02-Aug-2001 Elapsed: 0:19:47 [ ] Passed: 1 tests (100%) Failed: 0 tests (100%) Totals: 1 tests, 1 errors, 0 warnings [+] Testcase NewGroupMembersDelete - 1 error *** Error: Window '[HtmlTable]NAME' was not found Occurred in Yahoo.objYahoo.tblName.hcml1.lnkMail.Click()Called from LoginTahoo at tlogin.t(109)

Naming conventions

Naming conventions SilkTest uses various files that contains declaration and uses the objects. Sometimes There may be chances for the programmer to get confused by looking at the name of the declarerd identifiers. For example assume a case where we are declaring a window (say yahoo page) [-] window BrowserChild SignInYahooMail tag "Sign in - Yahoo! Mail" parent Browser [-] HtmlImage HtmlImage1 o tag "#1" [-] HtmlText HelpYahoo // o tag "Help - Yahoo!" [-] HtmlLink HelpYahoo // o tag "Help" [+] HtmlLink Yahoo

In the above case, there are two variables in same name 'HelpYahoo' but of different data types. Here after declaring the objects, it will be confused to use those objects in the testscript file. Hence we can follow a naming method to make the variables more presice and clear. Consider the below code. It is the same code given above with the naming conventions used. [-] winclass clsSignInYahooMail [-] HtmlImage imgHtmlImage1 o tag "#1" [-] HtmlText txtHelpYahoo // o tag "Help - Yahoo!" [-] HtmlLink lnkHelpYahoo // o tag "Help" [+] HtmlLink lnkYahoo

Here, declaring the window name with a pre-name 'cls' is to show it as a class name. Also the text and links are preceded by 'txt' & 'lnk'. Consider the code for a window declaration file. [-] window BrowserChild winSignInYahooMail tag "Sign in - Yahoo! Mail" parent Browser clsSignInYahooMail objSignInYahooMail

Here, the window name is preceded by the keyword 'win', and so the class name and its objects. Note: This convention is not a must to follow but to make the coding more easy to understand

Debugging Scripts Debugging the scripts If a testcase fails (for example, if the expected value doesnt match the actual value in a verification statement), SilkTest by default calls its built-in recovery system, which: Terminates the testcase Logs the error in the results file Restores your application to its default base state in preparation for the next testcase These runtime errors are called exceptions. They indicate that something did not go as expected in a script. They can be generated automatically by SilkTest, such as when a verification fails, when there is a division by zero in a script, or when an invalid function is called. You can also generate exceptions explicitly in a script. However, suppose you dont want SilkTest to transfer control to the recovery system when an exception is generated, but instead want to trap the exception and handle it yourself. Using do...except Using do...except you can handle exceptions locally, instead of passing control to SilkTests built-in error handler (which is part of the recovery system). The statement has the following syntax: do except statements statements

If an exception is raised in the do clause of the statement, control is immediately passed to the except clause, instead of to the recovery system. If no exception is raised in the do clause of the statement, control is passed to the line after the except clausethe statements in the except clause are not executed. The debugging feature allows you to do most of what you need to troubleshoot a script. Some of these features are: Set break points Single step Step into and Step out Access the Call Stack

The debugger runs in a separate state and produces output helps you to better locate any errors that may have arisen. Recording Application state Application State An application state is typically used to put an application into the state it should be in at the start of a testcase. You can define the application state from scratch or base the definition on another application state, which in turn can be based on another application state, and so on. The base state is the lowest level of application state in this chain of inheritance. The application state DefaultBaseState is predefined for your use by SilkTest. To associate an application state with a testcase, use the appstate keyword when you define the testcase. The second example below associates the application state MyAppState (which is based on MyBaseState) with the testcase MyTestCase. By default, SilkTest call the SetAppState function when you enter a testcase, in the DefaultTestCaseEnter function. The SetAppState function executes the statements defined in the application state and in each of the application states upon which it is based, starting with the statements in the base state and working up to the application state chain. By default, SilkTest calls the SetBaseState function when you exit a testcase, in the DefaultTestCaseExit function. The SetBaseState function executes the statements defined in the lowest level application state only (the base state). For example, suppose a testcase uses the application state AppState3, based on AppState2, based on AppState1. Calling the SetBaseState function executes only the statements in AppState1. Record & Play Recording the Events / Action Writing scripts in SilkTest includes steps of commands with declaration of window names and its objects before that. To avoid these difficulties and to make the process easier ( this is an alternate for writing line-by-line steps of the scripts ) silktest provides a special feature of recording events. The steps are given below.

1. Create a new Testcase. 2. Select the option Record - Actions menu. 3. After getting the 'Record Actions' dialog box, the sequence of steps to be 4.
tested, should be done. ie., the programmer has to simply do the ordinary testing process by selecting or useing the windows & its objects.

5. After completing these steps, the user has to click the 'Paste to Editor' button 6. 7.
in the 'Record Actions' dialog box. Now the scripts are automatically available in the script file. Save the script and run that testcase.

A recorded statements for logging in to the yahoo site, will look line the sample given below. [-] recording

BrowserPage.SetActive () Browser.Location.SetText ("www.yahoo.com") Browser.Location.TypeKeys ("") Yahoo.HtmlLink("Mail|#26|$http:??www.yahoo.com?r? m2").Click () BrowserPage.HtmlTextField("Yahoo! ID:|#1").SetPosition (1, 1) BrowserPage.HtmlTextField("Yahoo! ID:|#1").SetText ("username") BrowserPage.HtmlTextField("Yahoo! ID:|#1").TypeKeys ("") BrowserPage.HtmlTextField("Password:|#2").SetText ("password") BrowserPage.HtmlPushButton("Sign In|#1").Click ()

The alternate for the above recorded statements will be as below: Browser.Loadpage("www.yahoo.com") // Loads the yahoo homepage as the default page if Yahoo.Exists() // checking for the existence of the homepage print("Yahoo window exists") // confirming that the window exists Yahoo.objYahoo.Loginname.SetText("username") Yahoo.objYahoo.Password.SetText("password") Yahoo.objYahoo.Submit.Click()

The difference between the above two different scripts are, the method II needs windows & its objects to declared before the scripts are to be written. It is not in the case of the recording kind of the code.

Implementing:
Classes & Objects Basic Object-oriented features The following object-oriented programming terms and concepts are used Classes Methods Objects Properties

Inheritance

Classes Classes are the core of object-oriented languages and are common to basic GUI architecture. A class contains a collection of information about a type of object. The following figure shows several classes in the main window of a sample application. Methods For each GUI object in your application, there is an associated class that defines the actions, called methods, that can be performed on all objects of that type. For example, the CheckBox class defines the actions that can be performed on all the checkboxes in your application. Methods defined for one class cannot be used to perform actions on a different class. For example, you cannot use methods defined for the CheckBox class to perform actions on objects in the PushButton class. Objects An object is a specific instance of a class. For example, in the 4Test language, the Exit button on a window is an object of the PushButton class. The methods that are available to an object are dictated by the class to which the object belongs. Properties A property is the physical characteristic of an object that you can access directly. Each class has an associated set of properties, although some properties are common among classes. Inheritance Classes are organized in a hierarchy. The reason for this is that classes are related to each other, sharing characteristics common to their parent classes. For example, the parent class Control defines all the characteristics common to all kinds of controls: check boxes, text fields, pushbuttons, and so on. In this way, each class does not need to define all the methods it needs; the class can just inherit the existing definition from its ancestor classes. For example, one action you can perform on objects of class DialogBox is the GetDefaultButton method. This method returns the identifier of the default pushbutton, which is the pushbutton that is pressed when the Return or Enter key is pressed. You could not use this method with objects that were not dialog boxes, such as menus or text fields. When you record testcases, the proper 4Test methods for each of your manual actions are recorded automatically for you, so it really is transparent to you which class the recorded methods belong to. However, if you decide to write or augment a testcase by hand, you can look up the class and the methods it supports in the online Help or Library Browser. Methods & Properties Methods in 4Test Some of the methods used in silktest are given below. Click() method (HtmlLink) Class : HtmlLink class Action : Clicks a mouse button on the HtmlLink. Syntax link.Click ( [iButton, iXpos, iYpos] )

Notes Click moves the mouse to the HtmlLink and clicks the specified mouse button. The coordinates are relative to the HtmlLink. If you do not specify coordinates, the click occurs in the center of the link. Example The following example clicks the Sign In Button of Yahoo Mail in the Welcome Page of the Yahoo Mail page. The button is declared as SignIn. YahooMail. SignIn.Click () SetText method (TextField) Class : TextField class Action : Substitutes new text for all or part of the text in the text field. Syntax textfield.SetText (sText [, iStartChar, iNumChars]) Variable Description sText The text to substitute. STRING. iStartChar Optional. The character position in the text field (starting from 1) at which to begin the substitution. INTEGER. iNumChars Optional. The number of characters in the text field to substitute with sText. INTEGER. Notes SetText substitutes the characters sText for the text in the text field. This method works only with the first line of multi-line text fields. If iStartChar is specified, SetText substitutes sText for the characters starting with the iStartChar character, and continuing to the end of the line. If both iStartChar and iNumChars are specified, it substitutes sText for iNumChars characters starting with the iStartChar character. If iStartChar is omitted, SetText substitutes sText for the entire contents of the text field. Example STRING sHello = "Hello, world"Find.FindWhat.SetText (sHello) Close() method

Class : MoveableWin class Action : Closes the window. Syntax window.Close ([bConfirm, bSetActive]) The Close method attempts to close the window by trying the following events, in this sequence, stopping when the window closes: 1 If a Close method is defined for the window, call it. Even if this method does not close the window, none of the following steps are executed. 2 Call window.SysMenu.Close.Pick ( ) (on platforms and windows that have system menus). 3 Call window.CloseBox.Click ( ) (only on the Macintosh). 4 If the window is a dialog, type the keys specified in OPT_CLOSE_DIALOG_KEYS and wait one second for the dialog to close. 5 If there is a single button in the window, click that button. 6 Click the list of buttons specified with OPT_CLOSE_WINDOW_BUTTONS. 7 Select the menus specified with OPT_CLOSE_WINDOW_MENUS. Close may fail. For example, if closing a window causes the application to display a message box and bCloseConfirm is set to FALSE, or if the buttons used to close the message box are not covered under the OPT_CLOSE_CONFIRM_BUTTONS option, the call will fail and raise the exception E_CANT_CLOSE_WINDOW. This method supports several specifications you can make to help SilkTest closes a window: Example // Set the line number in GotoLine dialog to a stringGotoLine.LineNumber.SetText ("A")GotoLine.Accept () // TextEditor displays a message boxMessageBox.Message.Verify ("Must enter a number.") // close the message boxMessageBox.Close () Exists() method Class : AnyWin class Action : Tests whether the window exists.

Syntax bDoesExist = window.Exists ([nTimeout]) Notes Exists returns TRUE if the window exists before the nTimeout seconds elapse, or FALSE if the window does not exist. The window does not have to be active, enabled, or exposed for it to exist. If you specify nTimeout, Exists waits up to the specified number of seconds for the window to exist. Exists does not raise an error if the window does not exist. To check whether a window exists and raise an error if it does not, use Exists with the Verify function, as in the following: Verify (SaveMessage.Exists (5), TRUE) Exists should always be part of another statement, so that the value returned by Exists is used. If the window is not unique, SilkTest raises the E_WINDOW_NOT_UNIQUE exception, unless the OPT_VERIFY_UNIQUE option is set to FALSE. If you set the OPT_MENU_PICK_BEFORE_GET option to TRUE, you may see menus pop up on the screen when calling Exists on a menu item, even though your code does not explicitly call Pick. Example TextEditor.File.New.Pick ()if (SaveMessage.Exists (5)) SaveMessage.Dismiss () LoadPage() method Window : LoadPage is declared for the Browser window. Action : Loads the specified page. Syntax browser.LoadPage (blLocation [, sUser, sPassword]) Notes As part of its normal operation, LoadPage calls the OnLoadPage method, which checks for and handles windows invoked by LoadPage operations, for example, authentication dialogs, security dialogs, and browser messages and warnings. BROWSERLOCATION is the union of the STRING and WINDOW data types. Passing in a string as blLocation

If blLocation is a string, LoadPage calls the OnLoadpage method and passes the string to it as the first argument, sLocation, along with values for sUser and sPassword, if these were specified. Passing in a window as blLocation The main benefit of passing in a window to the LoadPage method is that it gives you the opportunity to customize the loading of a browser page. You accomplish this by defining your own OnLoadPage method for the window. You might want to redefine OnLoadPage, for example, to bypass unwanted windows that pop up before the desired page appears, such as sound clips or videos. Note that in order to pass in a window as the value of blLocation, the window declaration must define a member or property, sURL, which specifies the URL to load. In this sense, passing in a window is equivalent to passing in a string as the value of blLocation. The LoadPage method calls your custom OnLoadPage method and passes to it the definition of the windows sURL as the first argument, sLocation. In addition, LoadPage passes for sUser and sPassword, if these were specified. If the page cannot be loaded. If the page cannot be loaded, the AppError function is called. Example To display the Yahoo mail home page, you can pass in a string. Browser.LoadPage ("www.mail.yahoo.com") or pass in a window: Browser.LoadPage (YahooMail) Maximize() method Class : MoveableWin class Action : Maximizes the window. Syntax window.Maximize ( ) Notes Maximize resizes the window to its full (maximized) size. If the window is already maximized, Maximize does nothing. Example

TextEditor.Maximize ()Print (TextEditor.GetState ()) // prints WS_MAXIMIZEDTextEditor.Restore ()Print (TextEditor.GetState ()) // prints WS_NORMAL Minimize() method Class : MoveableWin class Action : Reduces the window to an icon. Syntax window.Minimize ( ) Notes Minimize does nothing if the window is already an icon. Example TextEditor.Minimize ()TextEditor.Restore Operators Operators in SilkTest Operators: The 4Test language provides the programmer with operators which are similar to the operators which are used in the other programming languages. The most commonly used operators are discussed in here briefly These can be classified as Arithmetic Operators Logical Operators Bit wise Operators

Arithmetic operators Definition The arithmetic operators perform addition, subtraction, multiplication, division, exponentiation, and modulus operations. Addition+Adds one operand to the other Subtraction -Subtracts the second operand from the first Multiplication *Multiplies one operand by the other Division /Divides the first operand by the second Modulo%Divides the first INTEGER operand by the second, and returns the remainder Exponentiation**Lets you refer to a number in terms of a base value and an exponent Operand type

Operands for the arithmetic operators can be integers or real numbers. Arithmetic operators with sets The plus (+) and minus (-) operators are valid operators for sets. The plus operator is the equivalent of the SetUnion and SetAddMember functions; it performs the union of two sets: SuperSet = SubSetA + SubSetB SuperSet contains all members of both subsets with no duplicates. If either of the subsets is a single member, then the plus operator is the equivalent of the SetAddMember function. The minus operator is the equivalent of the SetExclude and SetRemoveMember functions; it performs the exclusion of two sets, either of which could be a single member: SubSet = SuperSetA - SuperSetB SubSet is the set containing all members of SuperSetA that are not also contained in SuperSetB. NoteThe exclusion of set B from set A is equivalent to: SetIntersection (A, SetComplement (B)) The following examples should make the behavior of set exclusion operations more clear: OperationResulting set Red - [COLORS]{Green, Blue}Red Red - [COLORS]{Red, Green, Blue}empty set [COLORS]{Red, Green, Blue} - Red{Green, Blue} In the third example above, the specification of a single member as the right operand works like the SetRemove function to remove that member from the left operand set. -- (operator) and ++ (operator) The ++ (increment) and -- (decrement) operators take a single argument. ++ adds one to its operand. -- subtracts one from its operand. In an assignment statement, the operands placement before or after the operand determines whether the increment/decrement operation takes place before or after the assignment. If the operator appears before the operand (++n), the increment or decrement operation occurs before the assignment If the operator appears after the operand (n++), the increment or decrement operation occurs after the assignment Examples // The following three statements are equivalent: i++

i=i+1 i +=1 // Increment n before assignment. // Afterwards, both x and n have the value 11. n = 10 x = ++n // Increment n after assignment. // Afterwards, x is 10 and n is ll. n = 10 x = n++ Logical Operators Definition The logical operators perform logical and, or, and not operations. They work by evaluating the first operand and then, if necessary the second. The second operand is evaluated only if its value is needed to determine the result. Logical and&&Returns TRUE if both operands evaluate to TRUE; returns FALSE if either operand is FALSE. Logical or||Returns TRUE if either operand evaluates to TRUE; returns FALSE if both operands are FALSE. Logical not!Takes only one operand. If the operand evaluates to TRUE, ! makes the resulting value FALSE. If the operand evaluates to FALSE, ! makes the resulting value TRUE. Operand type Operands to logical operators must all have type BOOLEAN. Result type The logical operators return one of the BOOLEAN values TRUE or FALSE. Scope resolution operator Use the scope resolution (::) operator inside a window or class declaration to refer to a method, property, child window, or variable that is inherited by the window or class, rather than the method, property, child window, or variable of the same name which the class itself defines. Bitwise operators Definition The bitwise operators perform bitwise AND, bitwise inclusive OR, left shift, right shift, and ones complement (unary). Bitwise AND&Masks off the specified bits Bitwise inclusive OR|Turns on the specified bits Bitwise exclusive OR^Sets to 1 each bit position where the operands have different bits, and sets to 0 each bit position where the operands have the same bits. Bitwise 1s complement~Changes each 1-bit into a 0-bit and vice-versa. Left Shift<<Shifts to the left the left operand by the number of bit positions indicated by the right operand. Right Shift>>Shifts to the right the left operand by the number of bit positions indicated by the right operand. Operand type These operators apply to integers. Result type The following table shows each of the possible results for bitwise AND, OR, and exclusive OR (XOR).

01 AND (&)010001 OR ( | )010111 XOR ( ^ )010110 Statements Statements in SilkTest There are various statements available in 4Test language for writing testcases. By using 4Test flow-of-control statements, we can add logic and robustness to a recorded testcase. The following table summarizes the statements. To Use one of these 4Test statements Execute statement blocks more than once for each executes a statement block once for each element in a list. for executes the loop once for each increment of a counter. while executes a loop until a test condition (boolean expression) is false. Conditionally execute a statement block if...else executes a statement block based on the value of a boolean expression. select executes one case from a group of cases. switch executes one of the statements that follow, depending on the value of an expression. Handle exceptions do...except handles an exception (error) rather than having it halt the script. raise raises a user-defined exception. reraise reraises an

exception the testcase is handling itself within a do...except statement. Transfer flow of control break transfers control of the script out of the innermost nested for, for each, while, switch, or select statement. continue begins the next iteration of a for, for each, or while statement without completing the current iteration. exit ends the execution the current script. goto transfers control to the statement prefixed with the specified label. return returns control back to the calling function, optionally passing back a return value.

For statement numeric iteration Action : Uses numeric iteration to control the number of times a statement executes. Syntax for loop-var = start-expr to end-expr [step step-expr] statement VariableDescription loop-var A loop variable to hold the current value of the for loop. start-expr A number which specifies the starting value of loop-variable. end-expr A number which specifies the end value of loop-variable. step-expr Optional for incrementing loop-variable by a value other than 1. Specify a positive number to increment, 2. A negative number to decrement. Note You must specify an explicit step-expr to decrement a loop. For example, to decrement a loop by 1, specify step -1. If you fail to do this, the for statement skips the loop but does not generate an error. statementCode to be executed a specified number of times until loop-var is outside the range start-expr to end-expr; either a single statement or a series of statements. Example testcase ForExample ()

INTEGER i = 0 for i = 2 to 9 step 2 Print (i) // This script prints: //2 //4 //6 //8

for each statement Action Iterates over the elements of a list or a set. Syntax for each item in expr statement

VariableDescription itemA variable name. exprAn expression that evaluates to a list or a set. statementA single statement or a series of statements. Notes The for each iterator executes once for each element in the list or set specified by expr. Each time it executes, the iterator sets item to the value of another list or set element, the statement section executes for that value, and then control passes back to the iterator to check for another item. When every element in the list or set has been processed, control passes to the next statement in the script. Example testcase foreachExample () LIST OF STRING lsFruit = {...} "apple" "mango" "kiwi" STRING sFruit for each sFruit in lsFruit Print (sFruit) // This script prints: //apple //mango //kiwi If Statement Action : Executes particular statements depending on the value of a condition. Syntax if boolean-expr

statement [else statement] VariableDescription boolean-exprA boolean expression. statementA single statement, or a series of statements. Notes If the value of the boolean expression is TRUE, the statement immediately below it is executed. If the value of the boolean expression is FALSE, control passes to the else clause, if any. If there is no else clause in an if statement, and if boolean-expr is FALSE, statement is not executed, and control passes to the next statement in the script (which could be another if statement). Example testcase ifExample () INTEGER i = 1, j = 2 BOOLEAN b = TRUE if (i == j) Print ("Equal") else Print ("Not Equal") Print ("Not even in the ballpark!") if (b) Print ("TRUE") // Prints: // Not Equal // Not even in the ballpark! // TRUE switch statement Action: Executes a particular statement depending on the value of an expression. Syntax switch (expr) case case-value(s) statement [ case case-value(s) statement ]... [ default statement ]...

VariableDescription exprAn expression. statementsOne or more statements. case-valuesOne or more expressions, separated with commas. If the value of expr equals one of the case-values, control passes to the first statement in the case-values clause. See the Notes below. Notes A switch statement can take the place of a series of if statements. Your script evaluates expr once and compares this value to the value of each of the expressions in case-values. If the value equals one of the expressions, control passes to the statement that follows. Otherwise control transfers to the statement following the default label, if one exists. There can be only one default label, and it must be the last. Although C requires a break statement in each case to explicitly transfer control out of the switch, 4Test does not require it. Once the last statement in the case has been executed, control automatically passes to the next statement after the switch statement. The syntax shown above is correct for Visual 4Test. Classic 4Test requires colons after the case and default labels. Example The following example illustrates all of the ways you can specify case-values. testcase switchExample () INTEGER i for i = 1 to 12 switch (i) case 1 // Compares i to 1 Print (i, "Case 1") case 2, 4 // Compares i to 2 and 4 Print (i, "Case 2, 4") case 5 to 7 // Compares i to 5, 6, and 7 Print (i, "Case 5 to 7") case 8 to 9, 11 to 12 // Compares i to 8,9,11,12 Print (i, "Case 8 to 9 and 11 to 12") default // If i is none of the above Print (i, "Default Case") // This script prints: //1Case 1 //2Case 2, 4 //3Default Case //4Case 2, 4 //5Case 5 to 7 //6Case 5 to 7 //7Case 5 to 7 //8Case 8 to 9 and 11 to 12 //9Case 8 to 9 and 11 to 12

//10Default Case //11Case 8 to 9 and 11 to 12 //12Case 8 to 9 and 11 to 12 Select method (PageList) Class : PageList class Action : Sets the current page to the specified page. Syntax pagelist.Select (sPage) VariableDescription sPageThe page to select. LISTITEM Notes Select causes the specified page to become the current (active) page in the pagelist. For information on specifying sPage, see the PageList class. For TabList controls, Select generates a click on the specified tab. Example MyDialog.MyPageList.Select ("/Options/Agent") do ... except statement Action :Handles (ignores) an exception without halting a script. Syntax do statements1 except statements2 VariableDescription statements1A single statement or series of statements that may generate an exception. statements2A single statement or series of statements (executed only if exception is raised in statements1). Example TestVerification (STRING sExpectedValue, STRING sTestValue) if ( sExpectedValue == sTestValue ) Print ("Test was successful") else raise 1, "ERROR: Test verification failed" return ErrorHandler () Print (ExceptData()) //This script prints: //ERROR: Test verification failed return testcase do_except_example () STRING sTestValue = "xxx" STRINGsExpectedValue = "yyy" do TestVerification (sExpectedValue, sTestValue) except

ErrorHandler () // Continue with testcase ... Notes The do...except statement allows a possible exception to be handled by the testcase instead of automatically terminating the testcase. If an exception is raised while the do clause (statements1) has control of the script, control immediately jumps to the first statement in statements2 in the except clause (often a call to one of the built-in 4Test functions that gets information on exceptions). If no exception is raised while statements1 has control of the script, control jumps to the first statement beyond the do ... except statement (the statements in statements2 are not executed). Session IV: Lab II : How to login into the yahoo site: Write a script to check for the existence of the mail in yahoo site. (save it as testscript1.t) - use any maid id to check for mail Write a script to delete all the mails in the yahoo inbox. (save it as testscript2.t) Create a test suite to run the above two testscripts at-once. (refer Session I) Look at the result files and if you see any error or warning, try to rectify it. To write a testcase using 4test include file & 4test script file

This example is to write the script for logging in to the yahoo site. To declare the window objects Start the SilkTest by selecting from the 'Start' menu. Configure the settings as given in lab I. Set it to Netscape. Click 'File -> New' menu, and select the '4Test include file' option and click OK. Click on the OK button.

It will open a new include file (of type .inc) Open the application in parallel. ie., open the browser in which the application has to be run.(say Netscape) In the netscape browser, load the page 'www.yahoo.com'. Go to the silktest. Select 'Record -> Window Declarations' option from the menu bar and go to the browser (your application) Wait till the 'Record Declarations' dialog box appears. Till that the application will be scrolled up and down to trap all the objects in that window. In the resultant 'Record Declarations' dialog box, all the objects of the yahoo home page declared can be viewed. Press the 'Ctrl'+ 'Alt' keys simultaneously. It will activate the button 'paste to editor' in the 'Record Declarations' dialog box. Click on the 'paste to editor' button to paste the window objects in the silk editor. Now it will display a code as given below. (say) [-] window BrowserChild Yahoo //identifier for window tag "Yahoo - Netscape" //tag for window parent Browser [+] HtmlLink Mail [+] HtmlImage LoginInfo [+] HtmlText Newsletter [-] HtmlPushButton Search // identifier for variiable search of type HtmlPushButton tag "Search" // tag value for the control pushbutton search. [+] HtmlPushButton Submit

Now click on the 'Mail' link in the home page. It will load the SignIn page. Now you have to declare that page in to your include / declaration file. Go to silktest. Select 'Record -> Window Declarations' option from the menu bar and go to the browser. Wait till the 'Record Declarations' dialog box appears. Till that your application will be scrolled up and down to trap all the objects in that window. In the resultant 'Record Declarations' dialog box,all the objects of the yahoo SignIn page declared can be viewed. Press the 'Ctrl'+ 'Alt' keys simultaneously. It will activate the button 'paste to editor' in the 'Record Declarations' dialog box. Click on that button and paste the second page of the application in to the editor. Now the include file will look as below. [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser [+] HtmlLink Mail [+] HtmlImage LoginInfo [+] HtmlText Newsletter

[+] HtmlTextField Search [+] HtmlPushButton Submit [-] window BrowserChild SignInYahoo tag "Sign In Yahoo - Netscape" parent Browser [+] HtmlLink CheckMail [+] HtmlImage SignIn [+] HtmlText Mails [-] HtmlTextField Password tag "Pasword" o [+] HtmlPushButton Submit

Login into the site by supplying the username and password and get into it. Now the browser will contain the 'Yahoo Mail' page. Now using the above few steps declare the objects available in 'Yahoo Mail' page. Now the include file will be (say): [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser [+] HtmlLink Mail [+] [+] [+] [+] HtmlImage LoginInfo HtmlText Newsletter HtmlTextField Search HtmlPushButton Submit

[-] window BrowserChild SignInYahoo tag "Sign In Yahoo - Netscape" parent Browser [+] HtmlLink CheckMail [+] [+] [+] [-] HtmlImage SignIn HtmlText Mails HtmlTextField username HtmlTextField Password tag "Pasword"

o [+] HtmlPushButton Submit [-] window BrowserChild YahooMail tag "Yahoo Mail - Netscape" parent Browser [+] HtmlLink Mail [+] HtmlImage LoginInfo [+] HtmlText Newsletter

[+] HtmlTextField Search [+] HtmlPushButton Submit Create a folder called myscripts (say) in any drive to save the include file. Assume that the folder is created in c:\ drive. It is not necessary to save the scripts in that same drive where the silktest has been installed. Create a folder myscripts in c:\ drive. Save the above inlcude file as 'decyahoo.inc' in 'c:\myscripts' folder. The dec is just to mark that it is a declaration/include file. include the code given below in the above file. const wMainWindow = Yahoo // default window name. const sLocation="www.yahoo.com" This is to mark that the 'Yahoo' window will be the application base state and every testcase will start with the above window. Also the silktest will automatically load the home page as we have declared the sLocation variable. The above two variables are declared in the 'c:\program files\segue\silktest\defaults.inc' file.

To write testscript using the above include file Already the include file 'decsample.inc' is in the folder. Now, click on the File -> New option and open a new '4Test include file' file. Declare the inlcude file in your script file by including the below line in the beggining. use "c:\myscripts\decsample.inc" Open a new testcase by marking the keyword 'testcase'. Start with the keyword 'testcase Login()' and press Enter key in your keyboard. The testcase is the default keyword for any testcase and the name Login is the name of the testcase. The name of the testcase should be meaningful so that it represents the functionality of the test. Now start writing the testcase (write the below code). use "c:\myscripts\decsample.inc" testcase Login() Yahoo.SetActive() // this is to activate the window Yahoo.Mail.Click() // to click the mail link in home page if SignInYahoo.Exists() print("The yahoo sign in page is loaded") SignInYahoo.Username.SetText("username") SignInYahoo.Password.SetText("pasword") SignInYahoo.Submit.Click() if YahooMail.Exists() print("You have sucessfully logged in") else LogError("Sorry, Cannot log in") else LogError("Cannot Load Yahoo sign in page")

After completing the script, save it in the folder. Save it as 'sample.t' in the 'c:\myscripts' folder. Now you can compile the above tetscase and run it. At the end of the run, you will get a result file where you can know the status of the test.For running the scripts, refer Lab I.

Note: Here various methods are available for every control. Assume the above code. Here SetActive() method for the windows is to activate the given window. The window can be checked using Exists(),IsActive() methods. The SetText() method is for the type textfield. Value can be entered into the textbox/textfield using the SetText() method. Click() method is used to click the text, links and images. For dropdown control,Select(n) function can be used where 'n' value depends on our selection. Your code is ready now. Now start writing the next testcase.. testcase login() testcase checkmail() ............... .............. If we need to write a new testscript file, it can be done and saved in another name.

Differentiating the Window & Dialog box If the application is opened in the browser, then the window declaration can be as above. Many times we have to come across the dialog boxes that is apart from a browser. The Pop-Up window is what we call as dialog box in SilkTest. Assume composing a mail in yahoo,with some attachment. In the composing page, on clicking the 'Add attachment' link, a pop-up window 'Yahoo! Mail' will be loaded. For that dialog box, we cannot cannod do the declaration as the other browsers.We need to follow the following steps. Assume that all the windows in yahoo are declared and the current window is in 'Yahoo! Mail' dialog box. Open the declaration / include file 'decsample.inc'. Select the Record -> Window Declarations menu, and click on the 'Yahoo! Mail' popup window. Wait till the 'Record Declarations' dialogbox appears. Now, keep the cursor on the top of the window frame of the pop-up window (a blue pane that contains the window name 'Yahoo! Mail - Netscape'. Press the 'Ctrl' + 'Alt' keys simultaneously and paste the dialog name into the editor. But dont close the 'record Declarations' dialogbox. The declaration will be as below.

[-] window DialogBox PreferencesNetscape [ ] tag "Preferences - Netscape" Now go to the application and in the 'Record Declarations' dialogbox, click the 'Resume Tracking' button to continue tracking the window objects. Now, keep the mouse cursor inside the dialogbox (not on the dialog frame name) and press 'Crtl'+'Alt' keys. This will save the exact contents of the windows as below. [-] window BrowserChild Preferences [ ] tag "Preferences" [ ] parent PreferencesNetscape [+] HtmlTextField ChangePassword [+] HtmlPushButton OK [+] HtmlPushButton Cancel Now check for the difference between the two. The dialogbox name bears the declaration of the window name browserchild bears the contents of the window. Here the name dialogbox can be used for activating / maximizing / minimizing while the name of the browserchild can be used for performing the window.

and the of the the window the action in

Make sure that the parent name of the browserchild is same as that of the dialogbox name, and the name of the browserchild and the dialogbox should not be the same. Consider the following testcase that uses the above window declarations. ..............in decsample.inc.................. [-] window DialogBox PreferencesNetscape [-] window BrowserChild Preferences ............in sample.t........................ PreferencesNetscape.SetActive() PreferencesNetscape.Maximize() Sleep(2) PreferencesNetscape.SetActive() Preferences.ChangePassword.SetText("newpassword") Preferences.OK.Click() ................... .................. Session V :

Changing window declarations for implementing classes

Let us take the example of a Yahoo mail web site. We record the window declaration by using the Record-> Window Declarations option available in the silk test. The agent captures all the variables relevant to that screen. Then these variables can be pasted to the silk test editor by using the Ctrl+Alt keys, which will activate the Paste to Editor button in the Record Window Declaration dialog, and these window names & variables will be pasted to the silk test editor. Now captured window will be pasted to the editor as [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser [+] HtmlText Home o tag "Home" [+] HtmlText ClickforMail o tag " ClickforMail "

In the above example, the keyword 'Yahoo' is called as the identifier. Now copy the variables only (i.e., from the HtmlText Home) and put it under the class which is defined under the classes directory. Now our class is defined. Once the class is defined we need to create an instance of the class to use the variable that has been captured. Now in the directory declarations create a new file called decYahoo.inc (an include file). Now we have the window declaration for the yahoo web site and create an object for the winclasss clsYahoo. [-] window BrowserChild Yahoo clsYahoo objYahoo // creating an object for the class clsYahoo under the window yahoo

Now the class file for the window Yahoo will be as below. [-] winclass clsYahoo //tag "Yahoo - Netscape" //parent Browser [+] HtmlText Home o tag "Home"

From the above code, we have to make sure that after window declaration, In the class file, change the window BrowserChild to winclass. and remove the tag value, with the variables retained. In the declaration file, remove the variables, retain the tags, and create the object of that class. Declare the class file (clsYahoo.inc) in the declaration file (decYahoo.inc) Declare the declaration file (decYahoo.inc) in the script file (Yahoo.t).

How to create classes

Using the OOPS concept in Silk Test Oops offers many benefits to program designers of the users. Object orientation contributes to solutions of many problems associated with the development of quality of software products. The new technology promises greater programmer productivity, better quality of software and lesser maintenance of cost. By default, SilkTest uses the object oriented concepts for the built in custom controls and other features. Let us consider that we are declaring a window from the Yahoo home page. The declaration will contain the window name followed by the controls. Advantages of Oops: Through inheritance, we can eliminate redundant code and extend the use of existing classes. We can build programs from standard working modules that communicate with one another rather than having to start writing codes from the scratch. This saves development time and ensures higher productivity. The principles of data hiding help programmers to build secure programs that cannot be invaded by codes in other parts of the program. It is possible to have multiple objects to exist without any interference. It is possible to map objects in the problem domain to those objects in the program. It is easy to partition the work in a project based on objects.

Object oriented systems can be easily upgraded from small to a large system. Software complexity can be easily managed. In silk test, we can apply this OOPs concept to write better test scripts and test plan. Here we can define a class. We also make sure that the data it contains and the code that operates on the date goes with it. The syntax for declaring a class in silk test is winclass <class-name> Here the class name is preceded by the winclass keyword. The variables that are declared inside the winclass are got from capturing the window declarations. For ex: let us take the example of a Yahoo mail web site. We record the window declaration by using the Record-> Window Declarations tool available in the silk test. The agent captures all the variables relevant to that screen. Then these variables can be pasted to the silk test editor by using the Ctrl+Alt keys, which will activate the Paste to Editor button in the Record Window Declaration dialog, and these variables will be pasted to the silk test editor. Under the Classes directory create a class winclass clsYahoo Now captures window will be pasted to the editor as [-] window BrowserChild Yahoo tag "Yahoo - Netscape"

parent Browser [+] HtmlText Home o tag "Home" [+] HtmlText ClickforMail o tag " ClickforMail "

Now copy the variables only (i.e., from the HtmlText Home) and put it under the class which is defined under the classes directory. Now our class is defined. Once the class is defined we need to create an instance of the class to use the variable that has been captured. Now in the directory declarations create a new file called decYahoo.inc (an include file). Now we have the window declaration for the yahoo web site and create an object for the winclasss clsYahoo. [-] window BrowserChild Yahoo clsYahoo objYahoo // creating an object for the class clsYahoo under the window yahoo

Make sure that you inport clsYahoo.inc before creating the object. Now the object objYahoo for the winclass winYahoo has been created. Now we can start writing a testcase for the website. Writing a testcase using classes & declarations: Before writing the testcase create a new script file (say yahoo.t) in the testscripts folder. Before start writing the testcases import the folder silktest/declarations/decyahoo.inc file into the testscript file yahoo.t. The syntax for writing the testcase is testcase loginyahoo() The name itself indicates that this testcase does the job of logging into the yahoo site. What we are trying to achieve here is to load the page www.mail.yahoo.com into the browser and set the login and password values. Then we have to click the submit button and check whether the expected result has been achieved or not. If the process gets over correctly, the test passes and if not the test fails. So, now let us start writing the testcase // yahoo.t use "c:\silktest\declarations\decYahoo.inc" // declaring the declaration file. testcase loginYahoo() Browser.LoadPage(mail.yahoo.com) If Yahoo.Exists() Yahoo.objYahoo.user.SetText(username) Yahoo.objYahoo.password.SetText(password) Yahoo.objYahoo.submit.Click() If YahooMail.Exists() Print(Yahoo mail exists Test Pass) Else LogError(Yahoo mail doesnt exists Test Fail) Else LogError(Cannot load yahoo mail page)

Here, we are loading the url using the BrowserLoadPage() method where we pass the url as a parameter to browser. Then we check if the yahoo page is loaded by using the if condition. After the page has been loaded, we set the username and password in the respective textfield using the SetText() method. Here you will notice that the object is used to refer to the user and password variable of winclass clsYahoo. But before we instantiate the class, we have refer to the object with the browser name of the window where the variable has been recorded from. So we use Yahoo.objYahoo.user.SetText(username) After doing so, we check for the existence of the YahooMail page. According to that, we will print the result. Even if we did not specify the user defined result message, the silktest will by default print the test status. How to use structures Using Structures Consider a case as given below. Let us consider a function in which we need to pass two parameters, Log ID and PWD, for logging into the Yahoo site, in your test case. Files that you are going to use: One .inc file for declaring a structure, for the two login fields (User ID and password). One .inc file for declaring a class for the window where the login fields occur, and to declare a function, through which you are setting the text values for login and password. A .t file for describing your test case.

DECLARING A STRUCTURE: //decstructure.inc type login is record // here the structure name is 'login' string usrid string usrpwd DECLARING THE CLASS FOR THE WINDOW OF LOGIN FIELDS & FUNCTION TO SET TEXT FIELD VALUES FOR LOGIN: // clsstructure.inc use "decstructure.inc" winclass clssigninyahoomail HtmlTextField logid HtmlTextField logpwd

void Login(login x) logid.SetText(x.usrid) logpwd.SetText(x.usrpwd)

DESCRIBING YOUR TESTCASE FOR LOGIN: file://tlogin.t use clsstructure.inc use "decsigninyahoomail.inc" login loginfo // object declared for the structure testcase login() loginfo{"USER_ID", "USER_PWD") // passing parameter for the object of a struct Browser.LoadPage("www.yahoomail.com") SignInYahooMail.SetActive() SignYahooMail.objSignYahooMail.Login(loginfo) // passing the parameter for setting the values

Advanced 4Test language More on 4test language Data types and variables Built-in data types 4Test provides the following built-in data types: ANYTYPELIST ARRAY BOOLEAN BROWSERTYPE DATACLASS DATATYPE DATE DATETIME FONTSTYLE GUITYPE HANDLE INTEGER LIST LONG NUMBER REAL SEMAPHORE SET STRING TABLECOL

TABLEROW TIME WINDOW

C data types for DLL functions In addition to the 4Test data types, the following C data types are supported for use in calling functions in DLLs. char int short long unsigned char unsigned int unsigned short unsigned long float double

The first two columns above show data types that correspond to the 4Test INTEGER data type. The third column corresponds to the REAL data type. User-defined types You can also create new data types, including enumerated types and records. For example: type FILE is LIST OF STRING type COLOR is enum red green

Built-in functions 4Test contains a function library to handle the most common programming tasks. The following table summarizes the functions by category: Application state Array manipulation Char/string conversion Data type manipulation Distributed processing

Exception handling File manipulation List manipulation Numeric operations Random values Results file operations Script information Semaphore operations Set manipulation Startup String manipulation System calls Timers, time/date info Window information

Sample script for 4Test statements Consider an example of testing a web based application. testcasesample() Browser.Loadpage("www.yahoo.com") // Loads the yahoo homepage as the default page if Yahoo.Exists() // checking for the existence of the homepage print("Yahoo window exists") // confirming that the window exists Yahoo.objYahoo.Loginname.SetText("username") // Setting the login name in the corresponding textfield Yahoo.objYahoo.Password.SetText("password") Yahoo.objYahoo.Submit.Click() if !YahooMail.Exists() LogError("Cannot login - test fail") // printing the error message print("Yahoo mail logged in") YahooMail.objYahooMail.CheckMessage.Click() // checking the mail

In the above example, the 4Test statements, framename used, its objects,properties & methods are clearly defined. The Line 1 is for loading the the homepage of the yahoo site. In the next line, the exists is a method that belongs to the window class 'Yahoo'. In line 3, the SetText is the method belong to the class textfield, HtmlTextField Loginname. The concepts of the classes are described in the 'How to write scripts' portion of the index page. A sample script Sample code with description Let us consider the sample testcase for registering in the yahoo mail site. //------------------------------------------------------------------------------------------------------// a sample script file ( registration.t )

use "c:\scripts\decregistration.inc" testcase registration() Browser.LoadPage("mail.yahoo.com") SignInYahooMail.SetActive() SignInYahooMail.objSignInYahooMail.SignUpNow.Click() sleep(3) WelcomeToYahoo.SetActive WelcomeToYahoo.objWelcomeToYahoo.SignUpForYourYahooID1.SetText ("newuser@yahoo.com") WelcomeToYahoo.objWelcomeToYahoo.SignUpForYourYahooID2.SetText("pas sword") WelcomeToYahoo.objWelcomeToYahoo.SignUpForYourYahooID3.SetText("conf irmpassword") WelcomeToYahoo.objWelcomeToYahoo.HtmlPopupList1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField4.SetText("AnswerToSec urrityQuestion") WelcomeToYahoo.objWelcomeToYahoo.HtmlPopupList2.Select(3) WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField5.SetText("birthmonth") WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField6.SetText("birthyear") WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField7.SetText("currentmailid ") WelcomeToYahoo.objWelcomeToYahoo.FirstName1.SetText("firstname") WelcomeToYahoo.objWelcomeToYahoo.LastName1.SetText("lastname") WelcomeToYahoo.objWelcomeToYahoo.LanguageContent1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.ZipPostalCode1.SetText("zipcode") WelcomeToYahoo.objWelcomeToYahoo.Gender1.Select(2) WelcomeToYahoo.objWelcomeToYahoo.Occupation1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.Industry1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.ContactMeOccasionallyAbout.Click() WelcomeToYahoo.objWelcomeToYahoo.Entertainment.Click() WelcomeToYahoo.objWelcomeToYahoo.SubmitThisForm.Click() if RegistrationSuccess.Exists() print("Test Pass") else logerror("Test Fail")

//------------------------------------------------------------------------------------------------------// a sample Window Declaration include file ( decregistration.inc ) file://decregistration.inc use "c:\scripts\clsregistration.inc" [-] window BrowserChild SignInYahooMail o o o tag "Sign in - Yahoo! Mail" parent Browser clsSignInYahooMail objSignInYahooMail

[-] window BrowserChild WelcomeToYahoo


o o o tag "Welcome to Yahoo!" parent Browser clsWelcomeToYahoo objWelcomeToYahoo

//------------------------------------------------------------------------------------------------------// a sample class include file (clsregistration.inc) [-]winclass clsSignInYahooMail [+] HtmlImage HtmlImage1 o tag "#1" [+] HtmlText HelpYahoo o tag "Help - Yahoo!" [+] HtmlLink Help o tag "Help" [+] HtmlLink Yahoo o tag "Yahoo!" [+] HtmlHeading WelcomeToYahooMail o tag "Welcome to Yahoo! Mail" [+] HtmlHeading YouMustSignInToRead o tag "You must sign in to read" [+] HtmlHeading NewToYahoo o tag "New to Yahoo!?" [+] HtmlHeading ExistingYahooUsers o tag "Existing Yahoo! users"

//------------------------------------------------------------------------------------------------------Brief Description: The general syntax for performing any operation on the browser is as follows <window-name>.<object-name>.<control-name>.<operation> It is not necessary to use class to write testscripts. We can also write using the Window name followed by control name. In that case the syntax will be as below <window-name>.<control-name>.<operation> If an operation is to be done on the window itself (not in its controls, say activating a window), Window object need not be mentioned. thus, <window-name>.<operation> CONTROLS / OBJECTS: Controls are the various text fields, html links, buttons, popuplists, check boxes etc., in a browser window or dialog box or in any non web application. OPERATIONS: Depending upon the different type of controls, respective operations are defined. It can be SETTEXT for TEXTFIELDS; CLICK for BUTTONS, CHECK BOXES, LINKS; SELECT for POPUPLISTS etc. In the above example,

resister(), is the function name used to do registration in the Yahoo site. Function name can be anything, as the User's choice. The file clsregistration.inc is included in decregistration.inc, which in turn is included in tregistration.t. Windows are declared in deregistration. The corresponding classes, which consists of the various controls in the window are initialized in clsregistration.inc The command statement, o Browser.LoadPage("www.yahoo.mail.com"), is used to load the site. The command line, SignInYahooMail.objSignInYahooMail.SignUpNow.Click(), clicks the link 'signupnow'. Here, 'SignInYahooMai' is the window name, 'objSignInYahooMail' is the object of that particular window, 'SignUpNow', is the name of the control link and 'CLICK()' is the operation performed to click that control link. Similarly Text Values are entered into various text fields in the window 'WelcomeToYahoo' with the help of 'SetText' operator. 'objWelcomeToYahoo' is the object of 'WelcomeToYahoo' window. Note that the inverted commas is necessary with Settext operation, other than when passing parameters. Select is the operation used to select a particular value from a popup list. Select(3), will select the third value from the list. 'WelcomeToYahoo.objWelcomeToYahoo.Entertainment.Click()', will check the check box Entertainment and 'WelcomeToYahoo.objWelcomeToYahoo.SubmitThisForm.Click()'will click the button SubmitThisForm. SetActive(), IsActive(), Exists() are some of the methods used to verify the browser window status. Here there is no need to specify the window object. Print is the method used to print a particular statement on the result file, once the testcase completes execution. logerror behaves similarly like print, except the statement will be printed in red colour in the .res file

Built-in recovery system Sample code with description Let us consider the sample testcase for registering in the yahoo mail site. //------------------------------------------------------------------------------------------------------// a sample script file ( registration.t ) use "c:\scripts\decregistration.inc" testcase registration() Browser.LoadPage("mail.yahoo.com") SignInYahooMail.SetActive() SignInYahooMail.objSignInYahooMail.SignUpNow.Click() sleep(3) WelcomeToYahoo.SetActive WelcomeToYahoo.objWelcomeToYahoo.SignUpForYourYahooID1.SetText ("newuser@yahoo.com") WelcomeToYahoo.objWelcomeToYahoo.SignUpForYourYahooID2.SetText("pas sword")

WelcomeToYahoo.objWelcomeToYahoo.SignUpForYourYahooID3.SetText("conf irmpassword") WelcomeToYahoo.objWelcomeToYahoo.HtmlPopupList1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField4.SetText("AnswerToSec urrityQuestion") WelcomeToYahoo.objWelcomeToYahoo.HtmlPopupList2.Select(3) WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField5.SetText("birthmonth") WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField6.SetText("birthyear") WelcomeToYahoo.objWelcomeToYahoo.HtmlTextField7.SetText("currentmailid ") WelcomeToYahoo.objWelcomeToYahoo.FirstName1.SetText("firstname") WelcomeToYahoo.objWelcomeToYahoo.LastName1.SetText("lastname") WelcomeToYahoo.objWelcomeToYahoo.LanguageContent1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.ZipPostalCode1.SetText("zipcode") WelcomeToYahoo.objWelcomeToYahoo.Gender1.Select(2) WelcomeToYahoo.objWelcomeToYahoo.Occupation1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.Industry1.Select(5) WelcomeToYahoo.objWelcomeToYahoo.ContactMeOccasionallyAbout.Click() WelcomeToYahoo.objWelcomeToYahoo.Entertainment.Click() WelcomeToYahoo.objWelcomeToYahoo.SubmitThisForm.Click() if RegistrationSuccess.Exists() print("Test Pass") else logerror("Test Fail")

//------------------------------------------------------------------------------------------------------// a sample Window Declaration include file ( decregistration.inc ) file://decregistration.inc use "c:\scripts\clsregistration.inc" [-] window BrowserChild SignInYahooMail o o o tag "Sign in - Yahoo! Mail" parent Browser clsSignInYahooMail objSignInYahooMail

[-] window BrowserChild WelcomeToYahoo


o o o tag "Welcome to Yahoo!" parent Browser clsWelcomeToYahoo objWelcomeToYahoo

//------------------------------------------------------------------------------------------------------// a sample class include file (clsregistration.inc) [-]winclass clsSignInYahooMail [+] HtmlImage HtmlImage1

o tag "#1" [+] HtmlText HelpYahoo o tag "Help - Yahoo!" [+] HtmlLink Help o tag "Help" [+] HtmlLink Yahoo o tag "Yahoo!" [+] HtmlHeading WelcomeToYahooMail o tag "Welcome to Yahoo! Mail" [+] HtmlHeading YouMustSignInToRead o tag "You must sign in to read" [+] HtmlHeading NewToYahoo o tag "New to Yahoo!?" [+] HtmlHeading ExistingYahooUsers o tag "Existing Yahoo! users"

//------------------------------------------------------------------------------------------------------Brief Description: The general syntax for performing any operation on the browser is as follows <window-name>.<object-name>.<control-name>.<operation> It is not necessary to use class to write testscripts. We can also write using the Window name followed by control name. In that case the syntax will be as below <window-name>.<control-name>.<operation> If an operation is to be done on the window itself (not in its controls, say activating a window), Window object need not be mentioned. thus, <window-name>.<operation> CONTROLS / OBJECTS: Controls are the various text fields, html links, buttons, popuplists, check boxes etc., in a browser window or dialog box or in any non web application. OPERATIONS: Depending upon the different type of controls, respective operations are defined. It can be SETTEXT for TEXTFIELDS; CLICK for BUTTONS, CHECK BOXES, LINKS; SELECT for POPUPLISTS etc. In the above example, resister(), is the function name used to do registration in the Yahoo site. Function name can be anything, as the User's choice. The file clsregistration.inc is included in decregistration.inc, which in turn is included in tregistration.t. Windows are declared in deregistration. The corresponding classes, which consists of the various controls in the window are initialized in clsregistration.inc The command statement, o Browser.LoadPage("www.yahoo.mail.com"), is used to load the site. The command line, SignInYahooMail.objSignInYahooMail.SignUpNow.Click(), clicks the link 'signupnow'. Here, 'SignInYahooMai' is the window name, 'objSignInYahooMail' is the object of that particular window, 'SignUpNow', is the name of the control link and 'CLICK()' is the operation performed to click that control link.

Similarly Text Values are entered into various text fields in the window 'WelcomeToYahoo' with the help of 'SetText' operator. 'objWelcomeToYahoo' is the object of 'WelcomeToYahoo' window. Note that the inverted commas is necessary with Settext operation, other than when passing parameters. Select is the operation used to select a particular value from a popup list. Select(3), will select the third value from the list. 'WelcomeToYahoo.objWelcomeToYahoo.Entertainment.Click()', will check the check box Entertainment and 'WelcomeToYahoo.objWelcomeToYahoo.SubmitThisForm.Click()'will click the button SubmitThisForm. SetActive(), IsActive(), Exists() are some of the methods used to verify the browser window status. Here there is no need to specify the window object. Print is the method used to print a particular statement on the result file, once the testcase completes execution. logerror behaves similarly like print, except the statement will be prined in red colour in the .res file

Tips for making programming clear To make programming clear To make the coding clear we can create three separate folders for testscripts, classes, and declarations. We can also write scripts without using classes. But to increase the effectiveness and easy updation, classes are used. Here what ever we specify as testcases/testscripts should be available at the (say) testscripts folder, the classes and its fields, variables (say HtmlText) at the classes folder, the window declarations in the declarations folder. It will be easy to find the path of all these files if we put these folders in a separate folder called silktest. Silktest Declarations Classes Testscripts for keeping the window declarations for keeping the winclasses & its contents for keeping the testscripts.

If we follow the above style of programming, we can write the scripts effectively with easy understanding and it will be usefull if there is any need for future updation of scripts. Scripts have to be tuned fine by putting in sleep() commands so that the script will wait for actions which may take some time to complete. Also to activate the window, we can use SetActive(),Maximize() commands. This will enable quick access to objects that are hidden fomr the window, that are available in the viewport. How to write different testcases? A Testcase A testcase ideally addresses one test requirement. But there are certain conditions that each and every test should be performed with various criteria checked. Let us consider a case of a text field Name in a window. Here the normal way of testing is done by entering a text and checking whether that value is passed correctly. But we have to

look at the negative side too, to ensure that the data entered by the end user is a valid one. Sometimes, even an invalid value entered will take the application to crash the whole process and stops the application from progressing further. In that case, we can write the following testcases for testing the HtmlTextfield Name (as viewed by silktest). [+] testcase Blank_Field() [+] testcase Valid_Text() [+] testcase Long_Text() [+] testcase Valid_Html() [+] testcase Invalid_Html() [+] testcase Invalid_Character() [+] testcase Valid_Character() [+] testcase Integer_Value() [+] testcase Valid_URL() [+] testcase Invalid_URL() There should be a test plan to be followed while writing the testcases. The conditions given in the test plan should be covered in the testcases. An experiment with the tags An experiment with the tags A Tag: is an objects actual name or index as it appears in the GUI. It is the name by which SilkTest locates and identifies objects in the application. We identify the controls and windows / frames of the application by looking at the identifiers. An Identifier: Name used in test scripts to refer to an object in the application. Logical, GUI- Independent name. Identifier is mapped to the tag in a window declaration. For example consider the sample code given below. [-] window BrowserChild Yahoo

tag "Yahoo - Netscape" parent Browser

[-] HtmlImage CheckMail //expanded form of the variable tag "#2"

[-] HtmlText Messenger tag "Messenger"

[+] HtmlLink PhotoGallery In the above example, there is a window declaration of the Yahoo home page (only some variables are given above for example). It contains the BrowserChild (window) name followed by its tag value and the parent information. The 'parent Browser' text shows that the window is a main window and not a dialog box. Because only the window name or browser window name contains this keyword in the declaration part. Next comes the three variables. The first variable is of datatype HtmlImage.Here, the identifier name is 'CheckMail' and the tag value of it is '#2'. The user/programmer will write the script using the identifier name and it can be changeable. But the tag value should not be changed since the silktest will identify the objects in the window (or) the window itself by only looking at the tag values. Hence, the tag value should be same as of that when declared. From the above example, let us change the tag value for the HtmlImage CheckMail. After changing the tag value from '#2' to '#3', the code will look like this. Here no need to change the identifier name. [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser

[-] HtmlImage CheckMail tag "#3" // tag changed

[-] HtmlText Messenger tag "Messenger"

[+] HtmlLink PhotoGallery It is advisable to use muititags to avoid frequent change in tag values. To select multitag option, Select the Record -> Window Declarations option from the menu bar. You will get the Record Window Declarations dialog box waiting on your applicatoin to capture the window and its objects. In the 'Record Window Declarations' dialog box, select the 'options' button. You will get another dialog box 'Record window declarations options' .

In that dialog box, chech the 'Record Multiple tags' option and click on the 'OK' button. Now the silktest will capture the objects as multitags.

A multitag will look like as below. [-] window BrowserChild Yahoo [-] multitag "Yahoo - Netscape" [ ] "#12" [ ] "$http:??yahoohomepage.jsp" parent Browser

[-] HtmlImage CheckMail [-] multitag "Check Mail" [ ] "#1"

When to change the tag: Consider a situation that the testing process stops due to some error. We will check for the result file for the kind of error. If the error is something like HtmlLink not found, BrowserCustomClass not found then it might happen because of the change in tag value. In Silktest, the tag value will get changed rarely. It can be considered as a limitation of the tool. How to change the tag: By making some changes in the script, we have to continue the testing process, in order to check for errors. Follow the steps given below, to rectify the error in your code: Take the error file (result file). Click on the [+] image in the error statement. Double click on the error by keeping the cursor in the leftmost end of the error statement (that is indicated in red color) The control will take you to the statement where you get the error message. Double click on the object, which gives you the error. For example, if the error is HtmlText not found, then double click on the variable text, if the error is BrowserCustomClass Not Found then click on the Window name. After double clicking on the object that gives the error, press the Ctrl+Dot(.) buttons simultaneously. It will take you the file where that object has been declared. Also the cursor will wait in the same line of the object. Click on the [+] image in the object name. Check for the tag value. Then go to menu Window-> Declaration in the silktest, and activate your application manually. Check for the tag value of the control that gives you the error. Say if you get the error HtmlText Name not found, then check for the tag value of the text Name to that of the value in the previously available identifier. If the tag value matches, then leave it as it is. The tag values are available in the third column of the Record Window Declaration dialog box.

If the tag value doesnt match, then copy the tag value of the entire window in a file, temporarily. Copy the tag (only) of that particular object and overwrite it on the existing tag of that object. Make sure that you have to copy only the tag value and not the entire line / the identifier name. Save that file, compile it and run it again. Now the chances of getting the error are minimal. In silktest, the tag value of the window / objects will get changed rarely. Hence applying these steps is a necessary one in letting the testcase errorfree to make your application bug-free.

Session VI:

Lab III :
How to login into the yahoo site using classes: Write a testcase using classes to compose and send a yahoo mail with an attachment. Use any file to attach. Write a testcase to perform a stress test by adding 100 addresses into the addressbook of the yahoo site.

Write a testcase for registering into the yahoo mail-id. Use doexcept statement to verify whether the email id already exists. To write a testcase using classes This example is to write the script for logging in to the yahoo site. To declare the window objects Start the SilkTest by selecting from the 'Start' menu. Configure the settings as given in lab I. Set it to Netscape. Click 'File -> New' menu, and select the '4Test include file' option and click OK. Click on the OK button. It will open a new include file (of type .inc) Open the application in parallel. ie., open the browser in which application has to be run.(say Netscape) In the netscape browser, load the page 'www.yahoo.com'. Go to the silktest. Select 'Record -> Window Declarations' option from the menu bar and go to the browser (your application) Wait till the 'Record Declarations' dialog box appears. Till that your application will be scrolled up and down to trap all the objects in that window. In the resultant 'Record Declarations' dialog box, you can view all the objects of the yahoo home page declared. Press the 'Ctrl'+ 'Alt' keys simultaneously. It will activate the button 'paste to editor' in the 'Record Declarations' dialog box.

Click on the 'paste to editor' button to paste the window objects in the silk editor. Now it will display a code as given below. (say) [-] window BrowserChild Yahoo //identifier for window tag "Yahoo - Netscape" //tag for window parent Browser [+] HtmlLink Mail [+] HtmlImage LoginInfo [+] HtmlText Newsletter [-] HtmlPushButton Search // identifier for variiable search of type HtmlPushButton tag "Search" // tag value for the control pushbutton search. [+] HtmlPushButton Submit

Now click on the 'Mail' link in the home page. It will load the SignIn page. Now declare that page in the include / declaration file. Go to silktest. Select 'Record -> Window Declarations' option from the menu bar and go to the browser. Wait till the 'Record Declarations' dialog box appears. Till that the application will be scrolled up and down to trap all the objects in that window. In the resultant 'Record Declarations' dialog box,all the objects of the yahoo SignIn page declared can be viewed. Press the 'Ctrl'+ 'Alt' keys simultaneously. It will activate the button 'paste to editor' in the 'Record Declarations' dialog box. Click on that button and paste the second page of the application in to the editor. Now the include file will look as below. [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser [+] HtmlLink Mail [+] [+] [+] [+] HtmlImage LoginInfo HtmlText Newsletter HtmlTextField Search HtmlPushButton Submit

[-] window BrowserChild SignInYahoo tag "Sign In Yahoo - Netscape" parent Browser [+] HtmlLink CheckMail [+] HtmlImage SignIn [+] HtmlText Mails [-] HtmlTextField Password tag "Pasword"

[+] HtmlPushButton Submit

Login into the site by supplying the username and password and get into it. Now the browser will contain the 'Yahoo Mail' page. Now using the above few steps declare the objects available in this page too. Now the include file will be (say): [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser [+] HtmlLink Mail [+] [+] [+] [+] HtmlImage LoginInfo HtmlText Newsletter HtmlTextField Search HtmlPushButton Submit

[-] window BrowserChild SignInYahoo tag "Sign In Yahoo - Netscape" parent Browser [+] HtmlLink CheckMail [+] [+] [+] [-] HtmlImage SignIn HtmlText Mails HtmlTextField username HtmlTextField Password tag "Pasword"

o [+] HtmlPushButton Submit [-] window BrowserChild YahooMail tag "Yahoo Mail - Netscape" parent Browser [+] HtmlLink Mail [+] [+] [+] [+] HtmlImage LoginInfo HtmlText Newsletter HtmlTextField Search HtmlPushButton Submit

Create a folder called myscripts (say) in any drive to save the include file. Assume that the folder is created in c:\ drive. It is not necessary to save the scripts in that same drive where the silktest has been installed. Create a folder myscripts in c:\ drive. Save the above inlcude file as 'decyahoo.inc' in 'c:\myscripts' folder. The dec is just to mark that it is a declaration/include file. include the code given below in the above file. const wMainWindow = Yahoo // default window name. const sLocation="www.yahoo.com"

This is to mark that the 'Yahoo' window will be the application base state and every testcase will starts with the above window. Also the silktest will automatically load the home page as the sLocation variable has been declared. The above two variables are declared in the 'c:\program files\segue\silktest\defaults.inc' file.

Differentiating the Window & Dialog box If we are opening the application in the browser, then we can make the window declaraiton as given above. Many times we have to come across the dialog boxes that is apart from a browser. The Pop-Up window is what we call as dialog box in SilkTest. Assume composing a mail in Yahoo,with some attachment. In the composing page, on clicking the 'Add attachment' link, a pop-up window 'Yahoo! Mail' will be loaded. For that dialog box, the declaration cannot be done as the other browsers.The following steps has to be performed. Assume that all the windows in Yahoo are declared and thye current window is in 'Yahoo! Mail' dialog box. Open the declaration / include file 'decsample.inc'. Select the Record -> Window Declarations menu, and click on the 'Yahoo! Mail' popup window. Wait till the 'Record Declarations' dialogbox appears. Now, keep the cursor on the top of the window frame of the pop-up window (a blue pane that contains the window name 'Yahoo! Mail - Netscape'.

Press the 'Ctrl' + 'Alt' keys simultaneously and paste the dialog name into the editor. But don't close the 'Record Declarations' dialogbox. The declaration will be as below.
[-] window DialogBox PreferencesNetscape [ ] tag "Preferences - Netscape"

Now go to the application and in the 'Record Declarations' dialogbox, click the 'Resume Tracking' button to continue tracking the window objects. Now, keep the mouse cursor inside the dialogbox (not on the dialog frame name) and press 'Crtl'+'Alt' keys. This will save the exact contents of the windows as below. [-] window BrowserChild Preferences [ ] tag "Preferences" [ ] parent PreferencesNetscape [+] HtmlTextField ChangePassword [+] HtmlPushButton OK [+] HtmlPushButton Cancel

Now check for the difference between the two. The dialogbox name bears the declaration of the window name browserchild bears the contents of the window. Here the name dialogbox can be used for activating / maximizing / minimizing while the name of the browserchild can be used for performing the window.

and the of the the window the action in

Make sure that the parent name of the browserchild is same as that of the dialogbox name, and the name of the browserchild and the dialogbox should not be the same.

Consider the following testcase that uses the above window declarations. ..............in decsample.inc.................. [-] window DialogBox PreferencesNetscape [-] window BrowserChild Preferences ............in sample.t........................ .... PreferencesNetscape.SetActive() PreferencesNetscape.Maximize() Sleep(2) PreferencesNetscape.SetActive() Preferences.ChangePassword.SetText("newpassword") Preferences.OK.Click() ................... To write the class file using the above declaration file: Now the declaration / include file that contains the declaration of the following windows (say).

Yahoo, SignInYahoo, YahooMail, Preferences. To start with the class file, select the File -> New menu, in which select the '4Test include file' type. Copy the first window declaration from the decsample.inc file into this new include file. Here, copy the declaration Yahoo. [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser [+] HtmlLink Mail [+] HtmlImage LoginInfo [+] HtmlText Newsletter [+] HtmlTextField Search o [+] HtmlPushButton Submit

Since this is a class file, it should contain only the class definition and its variables. No detail regarding window should exists. Hence change the text 'window BrowserChild' to the keyword 'winclass'.

Then change the name 'Yahoo' to 'clsYahoo' (say)since the name of the window should not be the same as that of its class. The name can be changed to anything but to make it clear that it is a class file,precede it with the word cls. Then remove the tag value for the window name only. Don't remove the tag value for the variables. After performing the above, the class file will look like as below: [-] winclass clsYahoo [+] HtmlLink Mail [+] HtmlImage LoginInfo [+] HtmlText Newsletter [+] HtmlTextField Search o [+] HtmlPushButton Submit Now go to the 'decsample.inc' file and make the changes given below. Delete all the variables. ie., whatever comes next to the 'parent browser', delete it. Create an object for that class to where you have put all those variables that comes under this window. ie., that class should contain all the variables or controls that belong to this window. After performing the above changes the window declaration for the Yahoo will look like as below. [-] window BrowserChild Yahoo tag "Yahoo - Netscape" parent Browser clsYahoo objYahoo // object of the class clsYahoo Perform the above set of task for all the windows. Now save the class file in any name, say 'clsSample.inc', in the location 'c:\myscripts'. Declare the declaration file in the testscripts file Declare the Class file in the declaration file. ie., put 'use "c:\myscripts\decsample.inc"' in the sample.t file put 'use "c:\myscripts\clssample.inc"' in the decsample.inc file For the dialog boxes, create objects for the BrowserChild 's and not for the 'DialogBox'es.

To write testscript using the above include file: Already the include file 'decsample.inc' in the folder c:\myscripts. Now, click on the File -> New option and open a new '4Test include file' file. Declare the inlcude file in your script file by including the below line in the begining. use "c:\myscripts\decsample.inc" Open a new testcase by marking the keyword 'testcase'. Start with the keyword 'testcase Login()' and press Enter key in your keyboard. The testcase is the default keyword for any testcase and the name

Login is the name of the testcase. The name of the testcase can be anything but it is advisable to name it clearly so that it will represent the functionality of the test. Now start writing the testcase (write the below code). Assume that classes have been created for all the windows. use "c:\myscripts\decsample.inc" testcase Login() Yahoo.SetActive() // this is to activate the window Yahoo.objYahoo.Mail.Click() // to click the mail link in home page if SignInYahoo.Exists() print("The yahoo sign in page is loaded") SignInYahoo.Username.SetText("username") SignInYahoo.Password.SetText("pasword") SignInYahoo.Submit.Click() if YahooMail.Exists() print("You have sucessfully logged in") else LogError("Sorry, Cannot log in") else LogError("Cannot Load Yahoo sign in page")

After completing the script, save it in the folder. Save it as 'sample.t' in the 'c:\myscripts' folder. Now compile the above tetscase and run it. At the end of the run, a result file will be obtained where the status of the test can be known.For running the scripts, refer Lab I.

Session VII :
Browser & Platform independence Platform Independent Silk Test doesn't care about how the application is created, in which software the application is written, what kind of design is used, which browser it is being worked, in which operating system the application is running. All that needs for an application to be tested using silktest is that it needs a frame ( like window). The SilkTest recognizes the objects as they appear in the screen. For example, in a web based application, the silkiest sees a link as a HTML Link, an image as a HTML Image, a table as a HtmlTable,...regardless of the technology behind them.

Browser Independent There are various kinds of browsers used by various people for running their applications. The user may use any browser of his choice to test the standard application. Each and every browser acts differently with different applications. They show the same page differently. The web objects they display can also be aligned or displayed in different manner.

SilkTest just looks at these browser contents as objects and hence they cannot avoid any images, texts,... that they are not identifiable. Also we can write a test in one browser and run it in any other browser (to some extend). i.e.., using SilkTest, we can do cross browser testing. With minor modifications, your tests are robust enough to support different browsers and different versions of these browsers.

Technology Independent Silktest does not care how the application was built. It seamlessly works with the different web technologies commonly used today.

How to use the same code for multiple browsers: Start writing the silk scripts. Capture the window declarations (.inc file) and write the .t file. Say if you are capturing the declarations from Internet Explorer & runs successfully on it. As we captured the declarations from I.E., we now have to make the same test case run on Netscape since the tag value changes from multiple browsers. An Include file ----------------[-] window BrowserChild MyWebsite

[-] HtmlImage Join


[+] multitag "Be Smarter, Feel Healthier. Join Today Go!" [ ] "#12" [ ] "$http:??images.test.webmd.net?mywebmd?images? misc?JoinToday.gif" ------------------------------------The .t file for this we would write is MyWebsite.Join.Click() and this worked fine on IE5.0 If the same objects have different tags, you can use the browser tag specifiers to change the object for IE and Netscape. For example -------------------------------------------------------------------------------HtmlLink SomeLink explorer tag "Checkout" // for IE netscape tag "#2" // for Netscape -----------------------------------------------------------------------//Window Use [-] window BrowserChild MyToica [ ] tag "^?my?" [ ] !netscape4 tag "Toica: My Toica-New" [ ] netscape4 tag "Toica: My Toica"

[ ] parent Browser //Object Use [-] HtmlTextField FirstName [ ] netscape4 tag "[TextField]First Name:" [ ] !netscape4 tag "$ufn"

Using the above you can run the same script across browsers. Testing non-web applications Testing the Windows based applications Before start writing scripts, enable the settings given below.

1. Declare all the window names and its objects (used in writing scripts) starting
from the first window.

2. In the File -> New option in the menu bar, select the test frame. 3. In the resulting New Test Frame dialog box, specify the path of the
executable file of your application.

4. After submitting that dialog box, the silktest will automatically create a
declaration file with the default window declared.

5. Use that file to create your testscripts.


Testing the Java based applications Before you start testing the java applications or applets, you have to set the java classpath. Point to a Java archive (.jar file) that contains the software that powers SilkTest's Java support for JDK 1.2 and JRE 1.2. This file is called SilkTest_Java2.jar. When you install SilkTest, SilkTest_Java2.jar is installed in this directory: <SilkTest install directory>\JavaEx If you will use only JDK 1.2 for testing, you can activate Java support for JDK 1.2 by copying SilkTest_Java2.jar from <SilkTest install directory>\JavaEx to <JDK 1.2 install directory>\jre\lib\ext. If you do not copy SilkTest_Java2.jar to your JDK 1.2 install directory, you must point to it from your CLASSPATH.

Database Tester & its functions Database tester SilkTest provides facilities for testing a distributed application that accesses a database or directly testing database software itself for the following reasons. To exercise certain database functions that are present in a GUI that runs directly on the server machine and is not a client application. To set the server database to a known state.

To verify an application's database results without using the application. To read information from the database to use as input to a testcase.

The database tester provides direct access, using SQL, from a test script to any database supported by ODBC drivers. These database functions enable you to read and write database records without using the client application. Thus we can verify client test results without assuming the ability of the client to do that verification. In addition to using the SQL functions in your tests, we can also use these functions to help manage our testing process by Maintain a bug database, updating it with the results of your testing. Manage your test data in a database instead of in a text file.

The database functions, among other things, allow you to connect to a database, submit an SQL statement, read data from the selected record(s) if the SQL statement was SELECT, and subsequently disconnect from the database. About a dozen of these functions allow you to access your databases catalog tables. Overview of DBTester DBTester provides direct access, using SQL, from a SilkTest script to a database supported by ODBC drivers. DBTester comprises six functions that allow you to read and write database records without using the application's user interface. Thus, you can test an application's database or database software without using the application itself. The functions that support these operations begin with the letters DB_. DB_Connect : Opens a database connection and returns a handle to that system. SQL statements can be submitted to the database. DB_Disconnect : Closes the connection between SilkTest and the database and releases all resources. DB_ExecuteSql : Sends an SQL statement to the database for execution. DB_FetchNext :Retrieves the next row from the database. DB_FetchPrevious : Retrieves the previous row from the database. DB_FinishSql : Removes the result of the SQL statement and releases the associated system resource (statement handle).

An example showing the database testing functions used together This example shows how to use the DBTester functions together to access a database. It uses all the DBTester functions except DB_FetchPrev, which you use exactly as you use DB_FetchNext. While the example is based on a sample database, but the technique is the same regardless of which ODBC database you are accessing. testcase DBTest () // This test uses the functions in DBTester // to directly access an ODBC database INTEGER id, iheadID STRING sDeptName HDATABASE hdbc HSQL hstmnt

// connect to Powersoft Demo DB hdbc = DB_Connect ("dsn=Powersoft Demo DB V5;PWD=sql;UID=dba") // retrieve info from Department table hstmnt = DB_ExecuteSql (hdbc, "SELECT * FROM department") // process the information that came back print ("Here's the info in the Department table:") print () while (DB_FetchNext (hstmnt, id, sDeptName, iheadID)) print ("Dept: {id} Name: {sDeptName} Head: {iheadID}") // release resources (unneeded really because immediately followed by disconnect) DB_FinishSQL (hstmnt) // disconnect DB_Disconnect (hdbc) // // // // // // // Timer functions The main use of timer function is to measure the time taken for an particular operation . It can be used like a stop watch to measure elapsed time. 4Test timers are accurate to the millisecond (.001 seconds). There are set of timer functions to accomplish the above tasks . Illustration to timer functions : This illustration used to calculate the time taken for the testcase to complete execution . STRING sOverallTime HTIMER TotalTimer TotalTimer = TimerCreate () TimerStart (TotalTimer) // Statements to accomplish any task . ( For Ex : The time taken by the browser to load a page ) TimerStop (TotalTimer) sOverallTime = TimerStr (TotalTimer) Results: Here's the Dept: 100 Dept: 200 Dept: 300 Dept: 400 Dept: 500

info in the Department table: Name: R & D Head: 501 Name: Sales Head: 902 Name: Finance Head: 1293 Name: Marketing Head: 1576 Name: Shipping Head: 703

Print ("All code executed in {sOverallTime} seconds") TimerDestroy (TotalTimer) TimerCreate function creates a timer to keep track of an operation time .TimerStart function starts the specified timer. TimerStop stops the specified timer. Total time taken for an operation to complete is difference between timer stop and start minus the time paused. . TimerDestroy destroys the specified timer. File functions We may have to deal with files in regular course of testing for different needs like getting data for input for data entry purpose, writing the data retrieved from the application for validation purpose and also for creating custom output files. Find the sample code below for creating and working with the files. The following code creates a file with 100 lines [-] testcase WorkingWithFile () [ ] HFILE NewFile [ ] NewFile = FileOpen ("C:\MyFile.txt", FM_WRITE) [ ] string stext [] [ ] integer i [-] for i = 1 to 100 [ ] stext = "Sample Text" + str(i) [ ] FileWriteLine (NewFile, stext)

The following sample code shows how to read from a file and print contents into results (*.res) file. [-] testcase ReadFromFile () [ ] HFILE ReadFromFile [ ] ReadFromFile = FileOpen ("C:\MyFile.txt", FM_READ) [ ] string soutput [-] while (FileReadLine (ReadFromFile, soutput)) [ ] print (soutput)

the contents are written to the variable soutput; the content can be used anywhere in the testcase to enter the data on user interface.
Lab IV: Source code for testing non-web application: Write a script to test the non-web application provided above and check whether the number being displayed, changes after clicking the button provided. Write a testcase to find the time taken to add 100 addresses in Yahoo address book, using timer function. Source code for a simple Java application The given java application contains a button, and on clicking it will display the number of times it has been clicked. Copy the code given below in a text editor. Save the code as SwingApplication.java Go to the command prompt. Compile the code by giving the command 'javac SwingApplication.java' in the command prompt. Run it by giving the command 'java SwingApplication'. Now leave the application as it is and Create a new Test Frame. Specify the path of the source file in Runtime -> Extentions. Write the test script using that test frame.

----------------------------------------------------------------------------------------import javax.swing.*; //This is the final package name. //import com.sun.java.swing.*; //Used by JDK 1.2 Beta 4 and all //Swing releases before Swing 1.1 Beta 3. import java.awt.*; import java.awt.event.*; public class SwingApplication { private static String labelPrefix = "Number of button clicks: "; private int numClicks = 0; public Component createComponents() { final JLabel label = new JLabel(labelPrefix + "0 "); JButton button = new JButton("I'm a Swing button!"); button.setMnemonic(KeyEvent.VK_I); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { numClicks++; label.setText(labelPrefix + numClicks); } }); label.setLabelFor(button);

/* * An easy way to put space between a top-level container * and its contents is to put the contents in a JPanel * that has an "empty" border. */ JPanel pane = new JPanel(); pane.setBorder(BorderFactory.createEmptyBorder( 30, //top 30, //left 10, //bottom 30) //right ); pane.setLayout(new GridLayout(0, 1)); pane.add(button); pane.add(label); return pane; } public static void main(String[] args) { try { UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); } catch (Exception e) { } //Create the top-level container and add contents to it. JFrame frame = new JFrame("SwingApplication"); SwingApplication app = new SwingApplication(); Component contents = app.createComponents(); frame.getContentPane().add(contents, BorderLayout.CENTER); //Finish setting up the frame, and show it. frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.pack(); frame.setVisible(true); } } ---------------------------------------------------------------------------------------Session IX:

Using silktest in functionality, regression and stress testing in real time application.

Session X: Lab V:

Write the following testcases for Yahoo site. Use Internet Explorer 5.0 / Win NT combination to test the application. Start from the beginning to declare the windows and its objects in IE. Enable the extension to 'IE - DOM' for Internet Explorer 5.0 in Options -> Extensions. Login to yahoo mail and check for the existence of mails. Delete all the mails in the inbox and send a new mail to your id. Open that mail and delete that after opening. Send a mail with the subject 'subject', and search for the word 'subject' in the 'Search' option. In the option menu, change the password to the same word. Add Invalid addresses and check for errors.

Concluding the session. Frequently Asked Questions

How to start testing the web based applications? Before start writing scripts,

Declare all the windows and its objects (used in writing scripts)
starting from the home page.

Set the Home page as the default window in your declaration file.
(see declarations below).

Const sLocation = www.yahoo.com // say if the URL of the home


page is as specified.

Const wMainWindow = Yahoo // say if Yahoo is the name of the


window, in home page.

The above-specified constant variables are already declared in the


defaults.inc file in your silktest-installed directory.

Use that file to create your scripts.


How to start testing the window based applications? Before start writing scripts,

Declare all the window names and its objects (used in writing scripts) starting from the first window. In the File -> New option in the menu bar, select the test frame. In the resulting New Test Frame dialog box, specify the path of the executable file of your application. After submitting that dialog box, the silktest will automatically create a declaration file with the default window declared. Use that file to create your scripts.

Why do I get the message "Window not found"? I know the window exists It may be that you are using windows that are dynamic, and if so, you need to use the multitag features. Timing often plays a role in this issue. Some objects or windows may take longer to load than SilkTest is expecting. In this case, depending on your application performance and your machine's speed, you can experiment with the setting in the Agent Options dialog to increase the window time-out. Use the "Sleep" command in your 4Test script as well to slow down the script while waiting for a particular window to appear. This is useful with Java applets since they are known to be slow when downloading into a browser. The "Exists" method in 4Test is useful in a situation where timing is an issue. If you want to check for the existence of a window with a specific number of seconds as a limit, then try the following 4Test code in your script: Verify (SaveMessage.Exists (5), TRUE) The "Verify" command is wrapped around the test so that an error will be raised. If you do not want an error to be raised then use the method without the Verify statement, and check the value returned by the Exists method. When will the multitag work, and when will it not work? Multitags are meant to make your scripts less sensitive to changes at runtime. In general, when a testcase is running, the SilkTest Agent will try to resolve the object's tag by searching from the top of the declaration to the bottom until it finds the object. The multitag functions as a logical OR, that is, it matches a window or object if any of its components match. Multitags are very useful in many situations, which are either dynamic or inconsistent for some reason. You can specify as many tag-strings as you want in a multitag statement. You can even specify more than one value for each tag type. My window tags are very dynamic. How can I handle this? The "Window not found" error occurs for many reasons. However, in a dynamic environment, the

problem is usually related to window tags. If you watch the script run, try to see what is on the screen at the time of the error. When the error occurs, if you can see the window on the screen, it may rule out a timing issue and point more toward a tag issue. In dynamic environments, this error usually occurs because the tag that was generated is no longer appropriate. If you do not see the window on the screen, then it may be a timing issue, and you might want to try the suggestions in why do I get the message Window not found? I know the window exists. How do I create 4Test scripts that will work in cross browser situations? Browsers such as Internet Explorer and Netscape behave differently, and in general it is not good practice to run the same script across browsers. When recording test cases for browsers, it is best to record and playback in the same browser version to avoid problems such as inconsistent window IDs, captions, and tags. How do I update tags in a declaration file without recording declarations again? To activate the "Record Tags" menu item in SilkTest 5.0, select Options/Agent, and then click on the Compatibility tab. Select Add Window Tags to the Record Menu. You will then be able to record the tags that have changed. Save the new tags to your .INC file so that you can continue to use them in subsequent tests. Why doesn't SilkTest 5.0 with IE4 see some of the objects on my page? If you are using Windows98 the Active Desktop co-exists with SilkTest without any known issues. If you are using Windows95 or WindowsNT, remove the Active Desktop before installing and running SilkTest. One of the major symptoms encountered with Active Desktop and NT or 95 is that the objects inside IE4 are ignored or invisible to SilkTest. Installing SilkTest under Win95/98, an error message refers to the GDI32.DLL file? If you get a message stating that there is a problem with the GDI32.dll file, it usually means that a previous version of SilkTest was not un-installed properly. This can occur in both Win95 and Win98, but not WinNT. In Win95 and Win98 environments, SilkTest modifies the GDI32.dll file for its own use during an install. Normally, you will see a message that SilkTest is inspecting the GDI32.dll file, which takes a few minutes, and then the installation continues. During installation, SilkTest modifies the GDI32.dll file, after making a backup of the original into the Segue sub directory. During a un-install, the original GDI32.dll is restored back to the Windows System directory. If for some reason the SilkTest un-install process is interrupted or corrupted, it is possible that the original dll will not be successfully copied back into the Windows System directory. To remedy this

situation, replace the original GDI32.dll by placing it in the Windows System directory. How do I install and start SilkTest 5.0 agents? Unlike some previous versions, the SilkTest 5.0 agent installation is the same as the general installation. If you have the appropriate license for your agent machine, you should have no problems with the installation. However, to set up the agent machines for distributed or remote testing, you will need to perform these steps: In the Options/Runtime tab, enter the host name of the agent machine (if you are testing against one agent machine). In the Options/Runtime tab, enter the network protocol in use between the host and the agent. If you are using more than one agent machine in a test, you will need to connect to all agents from your 4Test script. If you plan to use the Silk Bean for distributed testing of Java applications, see what is the Silk Bean and in what environments can it be used. What are the requirements for a test environment for Java applications and applets? There are a number of issues to consider in setting up a Java testing environment. It can get complicated since there are many vendors who supply Java classes, and each vendor has setup requirements, which are necessary for the Java application to run properly. Some vendors build their own JVMs. In addition, Segue's SilkTest requirements need to be added to the mix. Below is a table listing the issues that you need to consider before taking the steps to set up your Java test environment.

También podría gustarte