Reusing Code
There’s no way to get around it: Repetition is a fact of life in testing. Fortunately, there are several easy ways to let scripts and handlers do the repeating for you.
Calling Scripts from Other Scripts
One of the most common ways to reuse code is to call a script from a different script. To call a script, insert the script's name in your code, followed by any parameters that the script requires. The script call can be treated as if the script itself were a command or a function. For detailed information about calling other scripts, see Running Other Scripts and Handlers.
Following are examples of calling scripts from within a script:
CycleWindows // Calls a simple script name as a command
ConnectionScript "Old SUT", "New SUT" // Calls a simple script name with parameters
put CaptureTheScreen("SomePrefix",1) into myScreenCapture
// Calls a script as a function with parameters and puts the result in a variable
Whether you use the command call or the function call depends on the script itself. Both types can take input parameters, in which case the called script needs to begin with a params
declaration. The function call also returns values, in which case the called script must include a return
statement.
If you use a simple script name, with no spaces or special characters, and store scripts in the same suite or a helper suite, you can use the script name directly. See the examples above.
For a script in an unrelated suite, or a script with spaces or special characters in its name, you can type the Run
command, followed by the script path:
Run "/Users/Seiji/Documents/EggPlant Suites/Validation.suite/Scripts/ConnectionScript"
// Calls the Run command to open a script from an unrelated suite
Because of this ability to call a script from within another script, it's useful to think about writing scripts in segments that perform specific tasks or actions. This "modular" approach allows you the most opportunity to reuse scripts in different contexts. In such a case, your "main" script would include code for test or environment specifics but would call out to a different script to complete generic tasks.
More detailed information about using handlers and helper suites, which are both features that can help with code reuse and modular design, can be found below.
Handlers
To reuse code within the same script, you can write a handler
, which is essentially a subscript. A handler is a part of your main script that you can call anytime, as if you were calling another script.
Example: CaptureTheScreen
handler
to CaptureTheScreen prefix, count // Starts the handler
set fileName to prefix & "ScreenShot" & count // Puts prefixScreenShotCount into fileName
set tempFile to "/tmp/" & fileName // Puts "/tmp/filename" into tempFile
CaptureScreen tempFile //Captures a screenshot
return fileName // Sets fileName as the function return value
end CaptureTheScreen //Ends the handler