Table of Contents
QImage
ObjectScreen
ObjectToplevelWindow
Objectsquishinfo
ObjecttestInteraction
FunctionstestSettings
ObjectRemoteSystem
ObjectThis section introduces the APIs that Squish provides in addition to the standard features of the scripting languages it supports. The Squish APIs provide the facilities that test engineers need to test GUI applications, and offer a wide range of functionality, from interacting with AUT objects, to recording information in test logs, performing verifications, controlling the AUT, and more.
Here are some quick links to the Squish API functions (not including the Squish objects or the toolkit-specific convenience functions):
|
|
|
![]() | Squish API Function Parameters |
---|---|
For all of the Squish API functions that take an
|
Some of the Squish API functions can take a
modifierState
argument which indicates which
special keys are pressed at the time of a mouse click. And some of the
functions can also take a mouseButton
argument
which indicates which mouse button was clicked.
The modifierState
can be 0 (Modifier.None
,
the default), or the following:
Modifier.Alt
,
Modifier.Control
,
Modifier.Shift
.
If more than one modifier is used, they must be
OR
-d together, for example,
Modifier.Alt|Modifier.Shift
. The form shown here works for
Python and JavaScript. For Perl and Ruby replace the period with two
colons, e.g., Modifier::Control
, and for Tcl use the
enum
function, e.g., enum Modifier Control
.
The mouseButton
can be any one of:
MouseButton.LeftButton
,
MouseButton.MiddleButton
,
MouseButton.RightButton
.
For Perl use this: MouseButton::LeftButton
, etc.
For Ruby use this: MouseButton::LEFT_BUTTON
, etc.
For Tcl use this: enum MouseButton LeftButton
, etc.
![]() | Note |
---|---|
Windows test suites also support two more possible mouse button specifiers,
|
Many of the APIs' functions apply to particular objects, so being able to identify the object of interest is particularly important.
Squish provides several naming schemes, but the ones normally used are symbolic names and real names. Symbolic names are the most robust in the face of AUT changes, but real names can sometimes be more convenient to use. See How to Identify and Access Objects (Section 5.1) for more about names.
For Qt programs the easiest and most reliable way of identifying an
object in code is to set an object name in C++ for all the objects of
interest (using the
QObject::setObjectName method), and then in test scripts use a
real (multi-property) name specifying the object's
objectName
and its type
. For example:
textEdit = findObject("{objectName='ConfigEditor' type='QTextEdit'}")
var textEdit = findObject("{objectName='ConfigEditor' type='QTextEdit'}");
my $textEdit = findObject("{objectName='ConfigEditor' type='QTextEdit'}");
textEdit = findObject("{objectName='ConfigEditor' type='QTextEdit'}")
set textEdit [findObject "{objectName='ConfigEditor' type='QTextEdit'}"]
In practice it would be tedious to give every single widget a unique object name (and currently only Qt supports it), so this approach is most often used when there are two or more identical widgets in the same form. For those toolkits that don't have object names we can use introspection when there are two or more identical widgets. (Examples of both approaches are given in the User Guide (Chapter 5).)
The most common situation is where we need to identify unnamed objects. This can be done using symbolic names or by matching an object's unique set of property values. The necessary information can be obtained using the Spy tool (How to Use the Spy (Section 5.21.3)). This tool can provide an object's symbolic name and its property-based (real) name. Another approach is to create a dummy test, interact with the objects of interest and then look in Squish's object map to see the names that Squish uses, and copy any that are needed.
Here's an example that shows both approaches for finding an unnamed
object of type QTextEdit
. The object is in a
QMainWindow
whose title is "My App":
# symbolic name textEdit = waitForObject(":MyApp_QTextEdit") # real (multi-property) name textEdit = waitForObject("{type='QTextEdit' unnamed='1' " + "visible='1' window=':MyApp_MainWindow'}")
// symbolic name var textEdit = waitForObject(":MyApp_QTextEdit"); // real (multi-property) name var textEdit = waitForObject("{type='QTextEdit' unnamed='1' " + "visible='1' window=':MyApp_MainWindow'}");
# symbolic name my $textEdit = waitForObject(":MyApp_QTextEdit"); # real (multi-property) name my $textEdit = waitForObject("{type='QTextEdit' unnamed='1' " . "visible='1' window=':MyApp_MainWindow'}");
# symbolic name textEdit = waitForObject(":MyApp_QTextEdit") # real (multi-property) name textEdit = waitForObject("{type='QTextEdit' unnamed='1' " + "visible='1' window=':MyApp_MainWindow'}")
# symbolic name set textEdit [waitForObject ":MyApp_QTextEdit"] # real (multi-property) name set textEdit [waitForObject "{type='QTextEdit' unnamed='1' \ visible='1' window=':MyApp_MainWindow'}"]
The waitForObject
function waits for the
identified object to be ready (visible and enabled) and then returns a
reference to it.
On the whole it is best to use symbolic names since they are more robust
in the face of AUT changes, since they only require us to update the Object Map (Section 7.11) rather than our test script code if an object's
properties change. (Note that for most GUI toolkits the
type
property is mandatory when using real names.)
Squish objects blend in seamlessly with the scripting language's native objects. This means that you can use standard language features to construct objects of the wrapped types, invoke member functions, and get, set, and iterate over properties on these objects.
Here are some simple examples; many more examples are shown in the User Guide (Chapter 5).
# create an object of type QPoint point = QPoint(10, 20) # read a widget's width property width = widget.width # set widget's y-coordinate property widget.y = 240 # call a member function widget.setWindowTitle("My Widget") # call a static function QApplication.setOverrideCursor(Qt.WaitCursor)
// create an object of type QPoint var point = new QPoint(10, 20); // read a widget's width property var width = widget.width; // set widget's y-coordinate property widget.y = 240; // call a member function widget.setWindowTitle("My Widget"); // call a static function QApplication.setOverrideCursor(Qt.WaitCursor);
# create an object of type QPoint my $point = new QPoint(10, 20); # read a widget's width property my $width = widget->width; # set widget's y-coordinate property $widget->y(240); # call a member function $widget->setWindowTitle("My Widget"); # call a static function QApplication::setOverrideCursor(Qt::WaitCursor);
# create an object of type QPoint point = QPoint.new(10, 20) # read a widget's width property width = widget.width # set widget's y-coordinate property widget.y = 240 # call a member function widget.setWindowTitle("My Widget") # call a static function QApplication.setOverrideCursor(Qt::WAIT_CURSOR)
# create an object of type QPoint set point [construct QPoint 10 20] # read a widget's width property set width [property get $widget width] # set widget's y-coordinate property property set $widget y 240 # call a member function invoke $widget setWindowTitle "My Widget" # call a static function invoke QApplication setOverrideCursor [enum Qt WaitCursor]
For Tcl we must use the enum
function to get enum values.
(See Tcl Notes (Section 6.15).)
The function names in the scripting language API use the following
convention: each colon (:) in the selector name is replaced
by an underscore (_). So, for example, the
+stringWithCString:encoding:
selector becomes the script
function stringWithCString_encoding_
(note the underscore
at the end of the function).
Here are some examples to illustrate the usage.
# create an object of type NSString and initialize it with a value s = NSString.stringWithUTF8String_("Ambient") # read an object's intValue property n = acontrol.intValue # set an object's intValue property acontrol.intValue = 33 # call an instance method s.characterAtIndex_(1) # call a class method s = NSString.stringWithCString_encoding_("Zenith", 4)
// create an object of type NSString and initialize it with a value var s = NSString.stringWithUTF8String_("Ambient"); // read an object's intValue property var n = acontrol.intValue; // set an object's intValue property acontrol.intValue = 33; // call an instance method s.characterAtIndex_(1); // call a class method s = NSString.stringWithCString_encoding_("Zenith", 4);
# create an object of type NSString and initialize it with a value my $s = NSString::stringWithUTF8String_("Ambient"); # read an object's intValue property my $n = $acontrol->intValue; # set an object's intValue property $acontrol->intValue(33); # call an instance method $s->characterAtIndex_(1); # call a class method $s = NSString::stringWithCString_encoding_("Zenith", 4);
# create an object of type NSString and initialize it with a value s = NSString.stringWithUTF8String_("Ambient"); # read an object's intValue property n = acontrol.intValue # set an object's intValue property acontrol.intValue = 33 # call an instance method s.characterAtIndex_(1) # call a class method s = NSString.stringWithCString_encoding_("Zenith", 4)
# create an object of type NSString and initialize it with a value set s [invoke NSString stringWithUTF8String_ "Ambient"] # read an object's intValue property set n [property get $acontrol intValue] # set an object's intValue property property set $acontrol intValue 33 # call an instance method invoke $s characterAtIndex_ 1 # call a class method set s [invoke NSString stringWithCString_encoding_ "Zenith" 4]
This function finds and returns (a reference to) the object identified
by the symbolic or real (multi-property) name
objectName
or raises a LookupError
exception if no such object can be found. The given name can also be a native
script dictionary (resp. hash) value. This function is best used for
non-visible objects. For visible objects it is much better to use the
waitForObject
function instead.
This function finds and returns a list of object references identified
by the symbolic or real (multi-property) name objectName
.
Because it can return multiple object references, the name must not contain the
occurrence property. The given name can also be a native script dictionary
(resp. hash) value.
This function takes an object
reference (as
returned by the findObject
function or by
the waitForObject
function), and returns a
list of the object
's child objects. The return type
is scripting language-specific, e.g., a tuple in Python, and an array in
the other languages. Examples are given below.
![]() | Order/contents of child-list is fragile! |
---|---|
Test Cases that rely on the order of the children encountered in this list, may find that the order changes (or even possibly, new children appear in the list) due to many different factors, such as:
|
obj = waitForObject(":MyWidget") children = object.children(obj) # iterate over tuple for child in children: ...
var obj = waitForObject(":MyWidget"); var children = object.children(obj); // iterate over array for (var i = 0; i < children.length; ++i) { var child = children[i]; ... }
my $obj = waitForObject(":MyWidget"); my @children = object::children($obj); # iterate over array foreach $child (@children) { ... }
obj = waitForObject(":MyWidget") children = Squish::Object.children(obj) # iterate over array for child in children # ... end
set obj [waitForObject ":MyWidget"] set children [object children $obj] foreach child $children { ... }
This function converts the given object
to an
object of the type specified by the typeName
string. (A suitable object can be obtained using the waitForObject
function or the findObject
function.) For example:
font = object.convertTo(variant, "QFont")
In this example, if variant
is a variable of type
QVariant
and it holds a QFont
object, the
underlying QFont
object will be returned. If the
object
is invalid or null or if the
typeName
is unrecognized or if the conversion
isn't possible (e.g., QFont
to int
), a
catchable exception will be raised.
This function can also do other kinds of conversions, e.g.,
int
to String
. See also, the cast
function which can be used for downcasting
(which object.convertTo
cannot do).
![]() | Note for Qt5 Users |
---|---|
In Qt5, Squish can extract pointers to custom
|
This function creates a null pointer or object with the specified
type
as type.
widget = object.createNull(QWidget)
This function returns a true value if the object with the symbolic or
real (multi-property) name objectName
exists;
otherwise it returns a false value. The given name can also be a native script
dictionary (resp. hash) value.
If you know that a particular object exists and you just want to access
it (for example, to examine its properties or to perform an action on it
or with it), then use the waitForObject
function if the object is visible; or use the findObject
function if the object is hidden.
This function takes an object
reference (as
returned by the findObject
function or by
the waitForObject
function), and returns the
parent object.
If the given object has no parent, the function returns a null value -
the exact type of which depending on the scripting language (i.e.
None
in Python, null
in
JavaScript, nil
in Ruby etc.).
This function takes an object
reference (as
returned by the findObject
function or by
the waitForObject
function), and returns a
key–value map that holds all of the
object
's properties. The keys are property names
and the values are the property values. The return type is scripting
language-specific, e.g., a Python dict, a JavaScript Object, or a Perl
hash. Examples are given below.
For Tcl the data is written to an array whose name must be given as an
additional parameter. The same array should not be used in a second or
subsequent call unless you call array unset
on it before each use.
widget = waitForObject(":MyWidget") properties = object.properties(widget) # Best to use .iteritems(), .iterkeys(), or .itervalues() in Python 2 for name, value in properties.iteritems(): test.log("%s = %s" % (name, value))
var widget = waitForObject(":MyWidget"); var properties = object.properties(widget); for (var name in properties) { test.log(name + " = " + properties[name]); }
my $widget = waitForObject(":MyWidget"); my %properties = object::properties($widget); while (($name, $value) = each(%properties)) { test::log("$name = $value"); }
widget = waitForObject(":MyWidget") properties = Squish::Object.properties(widget) properties.each {|key, value| Test.log("#{key} = #{value}")}
set widget [waitForObject ":MyWidget"] object properties $widget properties foreach key [array names properties] { set value [toString $properties($key)] test log "$key = $value" }
This function takes an object
reference (as returned by
the findObject
function or by the waitForObject
function), and returns the bounding
rectangle for the object in screen coordinates. These values are identical to
what Squish uses during object highlight. The values may however not be
identical to toolkit specific geometry information since Squish may further
limit the global bounding rectangle to what is really visible on screen (i.e.
if parts of an object are clipped away by one of its parent objects).
var obj = waitForObject(":MyWidget"); var rect = object.globalBounds(obj); test.verify(rect.width > 200);
y $obj = waitForObject(":MyWidget"); my $rect = object::globalBounds($obj); test::verify($rect->width > 200);
obj = waitForObject(":MyWidget") rect = object.globalBounds(obj) test.verify(rect.width > 200)
obj = waitForObject(":MyWidget") rect = Squish::Object.globalBounds(obj) Test.verify(rect.width > 200)
set obj [waitForObject ":MyWidget"] set rect [object globalBounds $obj] test verify [expr [property get $rect width] > 200]
This function takes an object
reference (as returned by
the findObject
function or by the waitForObject
function), and returns a screenshot of its
current visual as an Image Object (Section 6.3.14).
The screenshot behavior can be configured through entries passed via the
optional parameterMap
argument.
delay
- The delay before taking the
screenshot in milliseconds. The default value is 1000
(1 second) to allow the AUT to react to the latest inputs and reach a stable
state before taking a screenshot. Reducing it to 0
may
be useful to improve the test execution time, especially in case of a series
of consecutive grabScreenshot()
calls.
var obj = waitForObject(":MyWidget"); var img = object.grabScreenshot(obj, {delay: 0}); test.attachImage(img);
y $obj = waitForObject(":MyWidget"); my $img = object::grabScreenshot($obj, {"delay" => 0}); test::attachImage($img);
obj = waitForObject(":MyWidget") img = object.grabScreenshot(obj, {"delay": 0}) test.attachImage(img)
obj = waitForObject(":MyWidget") img = Squish::Object.grabScreenshot(obj, {"delay" => 0}) Test.attachImage(img)
set obj [waitForObject ":MyWidget"] set img [object grabScreenshot $obj {delay 0}] test attachImage $img
This function returns a list of all of the AUT's top-level objects. The return type is scripting language-specific, e.g., a tuple in Python, and an array in the other languages. Examples are given below.
topLevels = object.topLevelObjects() # iterate over tuple for obj in topLevels: children = object.children(obj) ...
var topLevels = object.topLevelObjects(); // iterate over array for (var i = 0; i < topLevels.length; ++i) { var obj = topLevels[i]; var children = object.children(obj) ... }
my @topLevels = object::topLevelObjects(); # iterate over array foreach $obj (@topLevels) { my @children = object::children(obj) ... }
topLevels = Squish::Object.topLevelObjects() # iterate over array for obj in topLevels children = Squish::Object.children(obj) #... end
set topLevels [object topLevelObjects] foreach obj $topLevels { set children [object children $obj] ... }
This function will perform a search of the template image as stored
in imageFile
on the display also showing the
currently running application. On success the location of the found
image is returned as a
ScreenRectangle. Functions
like mouseClick()
or tapObject()
can then
emulate a user interaction on the detected location.
The search for the sub-image is performed left to right, top to
bottom. The first successful match is returned. For selection of other
matches use the occurrence
parameter as described
below.
All available screens making up the desktop will be searched. At least on Windows and X11-based systems. For searches on multi-screen setup on macOS please inquire with technical support.
The search behavior can be configured through entries passed
via the optional parameterMap
argument.
occurrence
- The occurrence
index. By default the first match (with index 1) will be returned.
Index values 2 and higher will select consecutive matches as far as
available.
tolerant
- Boolean switch
that enables tolerant image search mode. In this mode some differences
between the template image and the desktop screenshot are allowed. The
default value is the value of
testSettings.imageSearchTolerant property.
threshold
- Threshold on the
correlation between template image and a desktop screenshot,
expressed as a percentage. A correlation higher than the threshold is
considered a match against the template image. Usable values for this
parameter usually fall between 99.0
and
100.0
. The default value is the value of the
testSettings.imageSearchThreshold property.
This parameter is ignored if the tolerant
parameter is
set to false
.
multiscale
- Boolean switch
that enables scaled image search mode. In this mode the template image
is expanded into a series of images of different sizes. Those image
are subsequently used as template images for the image search. The
default value is the value of the
testSettings.imageSearchMultiscale property.
This parameter is ignored if the tolerant
parameter is
set to false
.
minScale
- Lower bound on the
template image series sizes, expressed as a percentage. The resized
template image sizes will span between minScale
and
maxScale
of the original image size. The default value
is the value of the
testSettings.imageSearchMinScale property.
This parameter is ignored if either the tolerant
or the
multiscale
parameters are set to false
.
maxScale
Upper bound on the
template image series sizes, expressed as a percentage. The resized
template image sizes will span between minScale
and
maxScale
of the original image size. The default value
is the value of the
testSettings.imageSearchMaxScale property.
This parameter is ignored if either the tolerant
or the
multiscale
parameters are set to false
.
# Click on icon.png mouseClick( findImage("icon.png") ) # Click on second occurrence of icon.png mouseClick( findImage("icon.png", {"occurrence": 2}) )
// Click on icon.png mouseClick( findImage("icon.png") ); // Click on second occurrence of icon.png mouseClick( findImage("icon.png", {"occurrence": 2}) );
# Click on icon.png mouseClick( findImage("icon.png") ); # Click on second occurrence of icon.png mouseClick( findImage("icon.png", {"occurrence" => 2}) );
# Click on icon.png mouseClick( findImage("icon.png") ) # Click on second occurrence of icon.png mouseClick( findImage("icon.png", {"occurrence" => 2}) )
# Click on icon.png invoke mouseClick [waitForImage "icon.png"] # Click on second occurrence of icon.png invoke mouseClick [waitForImage "icon.png" {occurrence 2 timeout 10000}]
This function will perform a single check of the screen
content only. If it fails to find the sub-image an exception will be
thrown. A call is useful in case a) the presence of the sub-image is
almost certain or b) a quick check of the presence is wanted. In all
other cases the waitForImage
function is
preferred for timing-independent look-ups.
The matching algorithm performs a pixel-by-pixel color value comparison. The screen content and sub-image content therefore have to match 100% unless the tolerant search mode is enabled.
# Click on icon.png mouseClick( findImage("icon.png", {'tolerant': True, 'threshold': 99.7, 'multiscale': True, 'minScale': 100.0, 'maxScale': 150.0}) )
// Click on icon.png mouseClick( findImage("icon.png", {tolerant: true, threshold: 99.7, multiscale: true, minScale: 100.0, maxScale: 150.0}) );
# Click on icon.png mouseClick( findImage("icon.png", {tolerant => true, threshold => 99.7, multiscale => true, minScale => 100.0, maxScale => 150.0}) );
# Click on icon.png mouseClick( findImage("icon.png", {"tolerant" => true, "threshold" => 99.7, "multiscale" => true, "minScale" => 100.0, "maxScale" => 150.0}) )
# Check whether icon.png is displayed on screen invoke mouseClick [ findImage "icon.png" {tolerant true \ threshold 99.7 \ multiscale true \ minScale 100.0 \ maxScale 150.0} ]
In case a searchRegion is specified as the last argument, the search is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the search scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section.
# Find icon.png on the MyWidget object findImage("icon.png", {}, waitForObject( names.MyWidget ) ) # Find icon.png on multiple objects findImage("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) # Find icon.png on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 findImage("icon.png", {}, bounds ) # Find icon.png in the specified area findImage("icon.png", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) # Find icon.png on all top-level objects findImage("icon.png", {}, "all" )
// Find icon.png on the MyWidget object findImage("icon.png", {}, waitForObject( names.MyWidget ) ); // Find icon.png on multiple objects findImage("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); // Find icon.png on the left half of the MyWidget object var bounds = object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 findImage("icon.png", {}, bounds ); // Find icon.png in the specified area findImage("icon.png", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ); // Find icon.png on all top-level objects findImage("icon.png", {}, "all" );
# Find icon.png on the MyWidget object findImage("icon.png", {}, waitForObject( names::MyWidget ) ); # Find icon.png on multiple objects findImage("icon.png", {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ); # Find icon.png on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; findImage("icon.png", {}, bounds ); # Find icon.png in the specified area findImage("icon.png", {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ); # Find icon.png on all top-level objects findImage("icon.png", {}, "all" )
# Find icon.png on the MyWidget object findImage("icon.png", {}, waitForObject( names.MyWidget ) ); # Find icon.png on multiple objects findImage("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); # Find icon.png on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 findImage("icon.png", {}, bounds ); # Find icon.png in the specified area findImage("icon.png", {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ); # Find icon.png on all top-level objects findImage("icon.png", {}, "all" );
# Find icon.png on the MyWidget object findImage "icon.png" {} [ waitForObject $names::MyWidget ] # Find icon.png on multiple objects findImage "icon.png" {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } # Find icon.png on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] findImage "icon.png" {} $bounds # Find icon.png in the specified area findImage "icon.png" {} [ construct ScreenRectangle 100 100 200 300 ] # Find icon.png on all top-level objects findImage "icon.png" {} "all"
This function will perform optical character recognition on the display also showing the currently running application and return all text lines.
The OCR will be performed over all available screens making up the desktop. At least on Windows and X11-based systems. For OCR on multi-screen setup on macOS please inquire with technical support.
The search behavior can be configured through entries passed
via the optional parameterMap
argument.
language
- The language hint
for OCR engine. Use an empty string to use the OCR engine defaults.
The default value is the value of
testSettings.defaultOcrLanguage property.
profiles
- An array of OCR
engine specific profile names. This parameter is used only with
engines that support profiles.
options
- A map of
engine-specific option names and values. These options are passed to
the OCR engine after loading the specified profiles.
scaleFactor
- Image up-scale
factor. The source image is upscaled by that factor before it is
passed to the OCR engine. The default value is
3.5
. It can be set to a lower value to improve
the OCR performance in case the text is rendered with a large font.
# Get all text using German language hint test.log( getOcrText( { "language": "German" } ) )
// Get all text using German language hint test.log( getOcrText( { language: "German" } ) )
# Get all text using German language hint test::log( getOcrText( { language => "German" } ) )
# Get all text using German language hint Test.log( getOcrText( { "language" => "German" } ) )
# Get all text using German language hint test log [ getOcrText { language "German" } ]
In case a searchRegion is specified as the last argument, the OCR is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the OCR scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section.
# Find all text on the MyWidget object test.log( getOcrText( {}, waitForObject( names.MyWidget ) ) # Find all text on multiple objects test.log( getOcrText( {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ) # Find all text on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 test.log( getOcrText( {}, bounds ) ) # Find all text in the specified area test.log( getOcrText( {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) ) # Find all text on all top-level objects test.log( getOcrText( {}, "all" ) )
# Find all text on the MyWidget object test.log( getOcrText( {}, waitForObject( names.MyWidget ) ) ); // Find all text on multiple objects test.log( getOcrText( {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ); // Find all text on the left half of the MyWidget object var bounds = object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 test.log( getOcrText( {}, bounds ) ); // Find all text in the specified area test.log( getOcrText( {}, new UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) ); // Find all text on all top-level objects test.log( getOcrText( {}, "all" ) );
# Find all text on the MyWidget object test::log( getOcrText( {}, waitForObject( names::MyWidget ) ) ); # Find all text on multiple objects test::log( getOcrText( {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ) ); # Find all text on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; test::log( getOcrText( {}, bounds ) ); # Find all text in the specified area test::log( getOcrText( {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ) ); # Find all text on all top-level objects test::log( getOcrText( {}, "all" ) )
# Find all text on the MyWidget object Test.log( getOcrText( {}, waitForObject( names.MyWidget ) ) ); # Find all text on multiple objects Test.log( getOcrText( {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ); # Find all text on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 Test.log( getOcrText( {}, bounds ) ); # Find all text in the specified area Test.log( getOcrText( {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ) ); # Find all text on all top-level objects Test.log( getOcrText( {}, "all" ) );
# Find all text on the MyWidget object test log [ getOcrText {} [ waitForObject $names::MyWidget ] ] # Find all text on multiple objects test log [ getOcrText {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } ] # Find all text on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] test log [ getOcrText {} $bounds ] # Find all text in the specified area test log [ getOcrText {} [ construct ScreenRectangle 100 100 200 300 ] ] # Find all text on all top-level objects test log [ getOcrText {} "all" ]
This function will perform optical character recognition on the display also showing the currently running application and search for the specific text within the result set. It will return a ScreenRectangle object corresponding to the location of the text.
The OCR will be performed over all available screens making up the desktop. At least on Windows and X11-based systems. For OCR on multi-screen setup on macOS please inquire with technical support.
The search behavior can be configured through entries passed
via the optional parameterMap
argument.
occurrence
- The occurrence
index. By default the first text match (with index 1) will be
returned. Index values 2 and higher will select consecutive matches as
far as available.
language
- The language hint
for OCR engine. Use an empty string to use the OCR engine defaults.
The default value is the value of
testSettings.defaultOcrLanguage property.
profiles
- An array of OCR
engine specific profile names. This parameter is used only with
engines that support profiles.
options
- A map of
engine-specific option names and values. These options are passed to
the OCR engine after loading the specified profiles.
scaleFactor
- Image up-scale
factor. The source image is upscaled by that factor before it is
passed to the OCR engine. The default value is
3.5
. It can be set to a lower value to improve
the OCR performance in case the text is rendered with a large font.
# Click on text mouseClick( findOcrText( "Test Text" ) ) # Click on text in German mouseClick( findOcrText( "Test Text", { "language": "German" } ) )
// Click on text mouseClick( findOcrText( "Test Text" ) ); // Click on text in German mouseClick( findOcrText( "Test Text", { language: "German" } ) );
# Click on text mouseClick( findOcrText( "Test Text" ) ); # Click on text in German mouseClick( findOcrText( "Test Text", { "language" => "German" } ) );
# Click on text mouseClick( findOcrText( "Test Text" ) ) # Click on text in German mouseClick( findOcrText( "Test Text", { "language" => "German" } ) )
# Click on text invoke mouseClick[ findOcrText "Test Text" ] # Click on text in German invoke mouseClick[ findOcrText "Test Text" { language "German" } ]
This function will perform a single OCR of the screen
content only. If it fails to find the specified text an exception will
be thrown. A call is useful in case a) the presence of the text is
almost certain or b) a quick check of the presence is wanted. In all
other cases the waitForOcrText
function is
preferred for timing-independent look-ups.
In case a searchRegion is specified as the last argument, the OCR is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the OCR scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section.
# Click on text on the MyWidget object mouseClick( findOcrText( "Click me", {}, waitForObject( names.MyWidget ) ) # Click on text on multiple objects mouseClick( findOcrText( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ) # Click on text on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 mouseClick( findOcrText( "Click me", {}, bounds ) ) # Click on text in the specified area mouseClick( findOcrText( "Click me", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) ) # Click on text on all top-level objects mouseClick( findOcrText( "Click me", {}, "all" ) )
# Click on text on the MyWidget object mouseClick( findOcrText( "Click me", {}, waitForObject( names.MyWidget ) ) ); // Click on text on multiple objects mouseClick( findOcrText( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ); // Click on text on the left half of the MyWidget object var bounds = object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 mouseClick( findOcrText( "Click me", {}, bounds ) ); // Click on text in the specified area mouseClick( findOcrText( "Click me", {}, new UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) ); // Click on text on all top-level objects mouseClick( findOcrText( "Click me", {}, "all" ) );
# Click on text on the MyWidget object mouseClick( findOcrText( "Click me", {}, waitForObject( names::MyWidget ) ) ); # Click on text on multiple objects mouseClick( findOcrText( "Click me", {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ) ); # Click on text on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; mouseClick( findOcrText( "Click me", {}, bounds ) ); # Click on text in the specified area mouseClick( findOcrText( "Click me", {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ) ); # Click on text on all top-level objects mouseClick( findOcrText( "Click me", {}, "all" ) )
# Click on text on the MyWidget object mouseClick( findOcrText( "Click me", {}, waitForObject( names.MyWidget ) ) ); # Click on text on multiple objects mouseClick( findOcrText( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ); # Click on text on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 mouseClick( findOcrText( "Click me", {}, bounds ) ); # Click on text in the specified area mouseClick( findOcrText( "Click me", {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ) ); # Click on text on all top-level objects mouseClick( findOcrText( "Click me", {}, "all" ) );
# Click on text on the MyWidget object invoke mouseClick [ findOcrText "Click me" {} [ waitForObject $names::MyWidget ] ] # Click on text on multiple objects invoke mouseClick [ findOcrText "Click me" {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } ] # Click on text on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] invoke mouseClick [ findOcrText "Click me" {} $bounds ] # Click on text in the specified area invoke mouseClick [ findOcrText "Click me" {} [ construct ScreenRectangle 100 100 200 300 ] ] # Click on text on all top-level objects invoke mouseClick [ findOcrText "Click me" {} "all" ]
This function will perform optical character recognition on the display also showing the currently running application and search for the specific text within the result set. It will return a sequence of ScreenRectangle objects corresponding to the locations of the specified text.
The OCR will be performed over all available screens making up the desktop. At least on Windows and X11-based systems. For OCR on multi-screen setup on macOS please inquire with technical support.
The search behavior can be configured through entries passed
via the optional parameterMap
argument.
language
- The language hint
for OCR engine. Use an empty string to use the OCR engine defaults.
The default value is the value of
testSettings.defaultOcrLanguage property.
profiles
- An array of OCR
engine specific profile names. This parameter is used only with
engines that support profiles.
options
- A map of
engine-specific option names and values. These options are passed to
the OCR engine after loading the specified profiles.
scaleFactor
- Image up-scale
factor. The source image is upscaled by that factor before it is
passed to the OCR engine. The default value is
3.5
. It can be set to a lower value to improve
the OCR performance in case the text is rendered with a large font.
# Check whether 'Test Text' is displayed on screen 3 times test.compare( len( findAllOcrText( "Test Text", { "language": "German" } ) ), 3 )
// Check whether 'Test Text' is displayed on screen 3 times test.compare( findAllOcrText( "Test Text", { "language": "German" } ).length, 3 )
# Check whether 'Test Text' is displayed on screen 3 times my @locations = findAllOcrText( "Test Text", { language => "German" } ); test::compare( scalar @locations, 3 )
# Check whether 'Test Text' is displayed on screen 3 times Test.compare( findAllOcrText( "Test Text", { "language" => "German" } ).length, 3 );
# Check whether 'Test Text' is displayed on screen 3 times test compare [ llength [ findAllOcrText "Test Text" { language "German" } ] ] 3
In case a searchRegion is specified as the last argument, the OCR is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the OCR scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section.
# Check whether 'Test Text' is displayed on MyWidget 3 times test.compare( len( findAllOcrText( "Test Text", {}, waitForObject( names.MyWidget ) ) ), 3 ) # Check whether 'Test Text' is displayed on multiple widgets 3 times test.compare( len( findAllOcrText( "Test Text", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ), 3 ) # Check whether 'Test Text' is displayed on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 test.compare( len( findAllOcrText( "Test Text", {}, bounds ) ), 3 ) # Check whether 'Test Text' is displayed on the specified area test.compare( len( findAllOcrText( "Test Text", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) ), 3 ) # Check whether 'Test Text' is displayed on all top-level objects test.compare( len( findAllOcrText( "Test Text", {}, "all" ) ), 3 )
// Check whether 'Test Text' is displayed on MyWidget 3 times test.compare( findAllOcrText( "Test Text", {}, waitForObject( names.MyWidget ) ).length , 3 ) // Check whether 'Test Text' is displayed on multiple widgets 3 times test.compare( findAllOcrText( "Test Text", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ).length, 3 ) // Check whether 'Test Text' is displayed on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 test.compare( findAllOcrText( "Test Text", {}, bounds ) .length, 3 ) // Check whether 'Test Text' is displayed on the specified area test.compare( findAllOcrText( "Test Text", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ).length, 3 ) // Check whether 'Test Text' is displayed on all top-level objects test.compare( findAllOcrText( "Test Text", {}, "all" ).length, 3 )
# Check whether 'Test Text' is displayed on MyWidget 3 times my @locations = findAllOcrText( "Test Text", {}, waitForObject( names::MyWidget ) ); test::compare( scalar @locations, 3 ) # Check whether 'Test Text' is displayed on multiple widgets 3 times my @locations = findAllOcrText( "Test Text", {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ); test::compare( scalar @locations, 3 ) # Check whether 'Test Text' is displayed on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; my @locations = findAllOcrText( "Test Text", {}, $bounds ); test::compare( scalar @locations, 3 ) # Check whether 'Test Text' is displayed on the specified area my @locations = findAllOcrText( "Test Text", {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ); test::compare( scalar @locations, 3 ) # Check whether 'Test Text' is displayed on all top-level objects my @locations = findAllOcrText( "Test Text", {}, "all" ); test::compare( scalar @locations, 3 )
# Check whether 'Test Text' is displayed on MyWidget 3 times Test.compare( findAllOcrText( "Test Text", {}, waitForObject( names.MyWidget ) ).length, 3 ); # Check whether 'Test Text' is displayed on multiple widgets 3 times Test.compare( findAllOcrText( "Test Text", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ).length, 3 ); # Check whether 'Test Text' is displayed on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 Test.compare( findAllOcrText( "Test Text", {}, bounds ).length, 3 ); # Check whether 'Test Text' is displayed on the specified area Test.compare( findAllOcrText( "Test Text", {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ).length, 3 ); # Check whether 'Test Text' is displayed on all top-level objects Test.compare( findAllOcrText( "Test Text", {}, "all" ).length, 3 );
# Check whether 'Test Text' is displayed on MyWidget 3 times test compare [ llength [ findAllOcrText "Test Text" {} [ waitForObject $names::MyWidget ] ] ] 3 # Check whether 'Test Text' is displayed on multiple widgets 3 times test compare [ llength [ findAllOcrText "Test Text" {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } ] ] 3 # Check whether 'Test Text' is displayed on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] test compare [ llength [ findAllOcrText "Test Text" {} $bounds ] ] 3 # Check whether 'Test Text' is displayed on the specified area test compare [ llength [ findAllOcrText "Test Text" {} [ construct ScreenRectangle 100 100 200 300 ] ] ] 3 # Check whether 'Test Text' is displayed on all top-level objects test compare [ llength [ findAllOcrText "Test Text" {} "all" ] ] 3
The condition
is a piece of code to evaluate, passed as
a string or as a function reference, and that is expected to return a Boolean
value.
The waitFor
function loops one or more times, and on each
iteration it executes the condition
code and
reads its return value. After each execution, if the
condition
code's return value is
true
, waitFor
will finish and return
true
. Otherwise, the waitFor
function will
perform another iteration, that is, execute the
condition
code again, and again check its return
value, repeating endlessly—or until the
condition
code returns true
, in
which case waitFor
will finish and return
true
.
This function is designed as a quick and easy way to poll for a
condition in the AUT, where each condition
execution takes a very short time (typically a fraction of a second),
and always returns true
or false
. This is
useful if you want to synchronize your script execution to a certain
state in the AUT.
See How to Create and Use Synchronization Points (Section 5.11) for examples of use.
Boolean waitFor(
condition, timeoutMSec)
;
The condition
is a piece of code to evaluate, passed as
a string or as a function reference, and that is expected to return a Boolean
value.
The waitFor
function loops one or more times, and
on each iteration it executes the condition
code
and reads its return value. After each execution, if the
condition
code's return value is
true
, waitFor
will finish and return
true
. If the condition
code returned
false
, the waitFor
function checks to see if
the time it has been running has exceeded the
timeoutMSec
—if it has,
waitFor
finishes and returns false
;
otherwise it does another iteration, starting with another execution of
the condition
code.
This function is designed as a quick and easy way to poll for a
condition in the AUT, where each condition
execution takes a very short time (typically a fraction of a second),
and always returns true
or false
. This is
useful if you want to synchronize your script execution to a certain
state in the AUT.
See How to Create and Use Synchronization Points (Section 5.11) for examples of use.
ApplicationContext waitForApplicationLaunch(
timeoutSecs)
;
Waits for a new application to start up, which Squish then hooks into. If the hooking succeeds it returns an ApplicationContext object representing the application that was started. This is used by Squish for test scripts which access multiple applications which are started by the AUT. (See also, Application Context (Section 6.3.12).)
The optional parameter timeoutSecs
(an integer number of
seconds) can be specified to tell Squish how long it should be prepared to
wait for the application to appear before throwing an error. If specified, this
value overrides squishrunner's default AUT timeout. If not specified the
squishserver's default is used—this is 20 seconds, unless it has been
changed; see Squish Server Settings dialog (Section 8.3.22).
Object waitForObject(
objectOrName, timeoutMSec)
;
Waits until the objectOrName
object is accessible
(i.e., it exists and is visible and
enabled). It returns a reference to
the object if successful or raises a (catchable)
LookupError
exception on failure, i.e., if the function
times out.
The function waits for the time defined by the testSettings.waitForObjectTimeout property or if the
optional timeoutMSec
parameter is used, that many
milliseconds. This function is useful if you want to synchronize your script
execution.
The given name can also be a native script dictionary (resp. hash) value.
This function is only suitable for objects that are (or become) visible; for
non-visible objects consider using the waitForObjectExists
function instead. And if you only want
to know if an object exists, use the object.exists
function.
Additional processing can be done on waited-for objects in a
user-defined callback function. See waitUntilObjectReady
for more details.
Object waitForObjectExists(
objectOrName, timeoutMSec)
;
Waits until the objectOrName
object exists.
The given name can be a native script dictionary (resp. hash) value.
It returns a reference to the object if successful or raises a (catchable)
LookupError
exception on failure, i.e., if the function
times out.
The function waits for the time defined by the testSettings.waitForObjectTimeout property or if the
optional timeoutMSec
parameter is used, that many
milliseconds.
Object waitForObjectItem(
objectOrName, itemOrIndex, timeoutMSec)
;
Waits until the objectOrName
object is accessible
(i.e., it exists and is visible and
enabled), and contains an item that
is identified by the itemOrIndex
and that is
itself accessible.
The given name can also be a native script dictionary (resp. hash) value.
This function is typically used to access items inside containers such as lists, tables, and trees.
The itemOrIndex
for a table can be a
row/column
string like "4/21"
. In a tree, it can be a
period (.)
-separated path string such as
Mammals.Felines.Cats
. In a list where strings may appear multiple
times, a specific item can be selected by appending (_)
followed by
the item's occurrence index, to the non-unique string. For example,
"itemtext_3"
would retrieve the third item in the list which
contains the "itemtext
" string.
![]() | Delimiter signs need to be escaped! |
---|---|
When passing string literals to the |
The return value depends on the Squish edition:
Java, Qt and Windows: The return value is a reference to the item. (The reference can be used with other Squish functions.)
Web and other Squish editions: The return value is a
reference to the object identified by objectOrName
(not the item).
The function raises a (catchable) LookupError
exception on
failure, i.e., if it times out.
The function waits for the time defined by the testSettings.waitForObjectTimeout property or if the
optional timeoutMSec
parameter is used, that many
milliseconds.
Additional processing can be done on the object items before
this function returns, by providing a user-defined callback function.
See waitUntilObjectItemReady
for
details.
This function waits for an image as specified
by imageFile
to appear on the screen, by repeatedly calling
findImage
until a timeout
is
reached. In case of success, the location of the image as found on the screen will be
returned as a ScreenRectangle. Interaction functions like
mouseClick
, doubleClick
or tapObject
can be used to click or tap on the
detected location.
The behavior of the search can be customized through additional
parameters passed to the optional parameterMap
of
key-value pairs, where a key can be one of these:
interval
- Number of
milliseconds to wait in between image search retries. The default is
1000 (1 second).
timeout
- Amount of time in
milliseconds to search for an image before reporting that the image is
not found. The default is 20000 (20 seconds).
occurrence
- The occurrence
index. By default the first match (with index 1) will be returned.
Index values 2 and higher will select consecutive matches as far as
available.
tolerant
- Boolean switch
that enables tolerant image search mode. In this mode some differences
between the template image and the desktop screenshot are allowed. The
default value is the value of
testSettings.imageSearchTolerant property.
threshold
- Threshold on the
correlation between template image and a desktop screenshot,
expressed as a percentage. A correlation higher than the threshold is
considered a match against the template image. Usable values for this
parameter usually fall between 99.0
and
100.0
. The default value is the value of the
testSettings.imageSearchThreshold property.
This parameter is ignored if the tolerant
parameter is
set to false
.
multiscale
- Boolean switch
that enables scaled image search mode. In this mode the template image
is expanded into a series of images of different sizes. Those image
are subsequently used as template images for the image search. The
default value is the value of the
testSettings.imageSearchMultiscale property.
This parameter is ignored if the tolerant
parameter is
set to false
.
minScale
- Lower bound on the
template image series sizes, expressed as a percentage. The resized
template image sizes will span between minScale
and
maxScale
of the original image size. The default value
is the value of the
testSettings.imageSearchMinScale property.
This parameter is ignored if either the tolerant
or the
multiscale
parameters are set to false
.
maxScale
Upper bound on the
template image series sizes, expressed as a percentage. The resized
template image sizes will span between minScale
and
maxScale
of the original image size. The default value
is the value of the
testSettings.imageSearchMaxScale property.
This parameter is ignored if either the tolerant
or the
multiscale
parameters are set to false
.
# Click on icon.png mouseClick(waitForImage("icon.png"))
// Click on icon.png mouseClick(waitForImage("icon.png"));
# Click on icon.png mouseClick(waitForImage("icon.png"));
# Click on icon.png mouseClick(waitForImage("icon.png"))
# Click on icon.png invoke mouseClick [waitForImage "icon.png"]
By default this function will repeatedly grab the screen content
until successful or until 20 seconds have passed. Longer (or shorter)
waiting periods can be set in milliseconds via a timeout
value passed through the parameterMap
. In order
to perform a single image search, use the
findImage
function.
# Click on second icon.png, wait maximum 10 seconds mouseClick(waitForImage("icon.png", {"occurrence": 2, "timeout": 10000})
// Click on second icon.png, wait maximum 10 seconds mouseClick(waitForImage("icon.png", {occurrence: 2, timeout: 10000}));
# Click on second icon.png, wait maximum 10 seconds mouseClick(waitForImage("icon.png", {"occurrence" => 2, "timeout" => 10000}));
# Click on second icon.png, wait maximum 10 seconds mouseClick(waitForImage("icon.png", {"occurrence" => 2, "timeout" => 10000}))
# Click on second icon.png, wait maximum 10 seconds invoke mouseClick [waitForImage "icon.png" {occurrence 2 timeout 10000}]
The matching algorithm performs a pixel-by-pixel color value comparison. The screen content and sub-image content therefore have to match 100% unless the tolerant search mode is enabled.
# Click on icon.png, found with tolerance of 99.7 mouseClick(waitForImage("icon.png", {'tolerant': True, 'threshold': 99.7, 'multiscale': True, 'minScale': 100.0, 'maxScale': 150.0})
// Click on icon.png, found with tolerance of 99.7 mouseClick(waitForImage("icon.png", {tolerant: true, threshold: 99.7, multiscale: true, minScale: 100.0, maxScale: 150.0}));
# Click on icon.png, found with tolerance of 99.7 mouseClick(waitForImage("icon.png", {tolerant => true, threshold => 99.7, multiscale => true, minScale => 100.0, maxScale => 150.0}));
# Click on icon.png, found with tolerance of 99.7 mouseClick(waitForImage("icon.png", {"tolerant" => true, "threshold" => 99.7, "multiscale" => true, "minScale" => 100.0, "maxScale" => 150.0}))
# Click on icon.png, found with tolerance of 99.7 invoke mouseClick [waitForImage "icon.png" {tolerant true \ threshold 99.7 \ multiscale true \ minScale 100.0 \ maxScale 150.0}]
In case a searchRegion is specified as the last argument, the search is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the search scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section. Since the Image
object specified
as the search region cannot possibly change overtime, this function
will not perform the image search repetitively and will return the
results immediately.
# Find icon.png on the MyWidget object waitForImage("icon.png", {}, waitForObject( names.MyWidget ) ) # Find icon.png on multiple objects waitForImage("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) # Find icon.png on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 waitForImage("icon.png", {}, bounds ) # Find icon.png in the specified area waitForImage("icon.png", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) # Find icon.png on all top-level objects waitForImage("icon.png", {}, "all" )
// Find icon.png on the MyWidget object waitForImage("icon.png", {}, waitForObject( names.MyWidget ) ); // Find icon.png on multiple objects waitForImage("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); // Find icon.png on the left half of the MyWidget object var bounds = object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 waitForImage("icon.png", {}, bounds ); // Find icon.png in the specified area waitForImage("icon.png", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ); // Find icon.png on all top-level objects waitForImage("icon.png", {}, "all" );
# Find icon.png on the MyWidget object waitForImage("icon.png", {}, waitForObject( names::MyWidget ) ); # Find icon.png on multiple objects waitForImage("icon.png", {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ); # Find icon.png on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; waitForImage("icon.png", {}, bounds ); # Find icon.png in the specified area waitForImage("icon.png", {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ); # Find icon.png on all top-level objects waitForImage("icon.png", {}, "all" )
# Find icon.png on the MyWidget object waitForImage("icon.png", {}, waitForObject( names.MyWidget ) ); # Find icon.png on multiple objects waitForImage("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); # Find icon.png on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 waitForImage("icon.png", {}, bounds ); # Find icon.png in the specified area waitForImage("icon.png", {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ); # Find icon.png on all top-level objects waitForImage("icon.png", {}, "all" );
# Find icon.png on the MyWidget object waitForImage "icon.png" {} [ waitForObject $names::MyWidget ] # Find icon.png on multiple objects waitForImage "icon.png" {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } # Find icon.png on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] waitForImage "icon.png" {} $bounds # Find icon.png in the specified area waitForImage "icon.png" {} [ construct ScreenRectangle 100 100 200 300 ] # Find icon.png on all top-level objects waitForImage "icon.png" {} "all"
This function will perform optical character recognition on the display also showing the currently running application and search for the specific text within the result set. It will return a ScreenRectangle object corresponding to the location of the text.
The OCR will be performed over all available screens making up the desktop. At least on Windows and X11-based systems. For OCR on multi-screen setup on macOS please inquire with technical support.
The search behavior can be configured through entries passed
via the optional parameterMap
argument.
interval
- Minimal number of
milliseconds to wait in between OCR search retries. The default is
1000 (1 second). The actual interval between separate OCR attempts is
dependent on OCR engine performance, and may be significantly longer.
timeout
- Amount of time in
milliseconds to search for the specified text before reporting that
the text is not found. The default is 20000 (20 seconds).
occurrence
- The occurrence
index. By default the first text match (with index 1) will be
returned. Index values 2 and higher will select consecutive matches as
far as available.
language
- The language hint
for OCR engine. Use an empty string to use the OCR engine defaults.
The default value is the value of
testSettings.defaultOcrLanguage property.
profiles
- An array of OCR
engine specific profile names. This parameter is used only with
engines that support profiles.
options
- A map of
engine-specific option names and values. These options are passed to
the OCR engine after loading the specified profiles.
scaleFactor
- Image up-scale
factor. The source image is upscaled by that factor before it is
passed to the OCR engine. The default value is
3.5
. It can be set to a lower value to improve
the OCR performance in case the text is rendered with a large font.
# Click on second 'Hier klicken' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Hier klicken", {"occurrence": 2, "language": "German"})
// Click on second 'Hier klicken' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Hier klicken", {occurrence: 2, language: "German"}));
# Click on second 'Hier klicken' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Hier klicken", {"occurrence" => 2, "language" => "German"}));
# Click on second 'Hier klicken' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Hier klicken", {"occurrence" => 2, "language" => "German"}))
# Click on second 'Hier klicken' occurrence, wait maximum 10 seconds invoke mouseClick [waitForOcrText "Hier klicken" {occurrence 2 language "German"}]
By default this function will repeatedly grab the screen content
until successful or until 20 seconds have passed. Longer (or shorter)
waiting periods can be set in milliseconds via a timeout
value passed through the parameterMap
. In order
to perform a single OCR search, use the
findOcrText
function.
# Click on second 'Click me' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Click me", {"occurrence": 2, "timeout": 10000})
// Click on second 'Click me' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Click me", {occurrence: 2, timeout: 10000}));
# Click on second 'Click me' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Click me", {"occurrence" => 2, "timeout" => 10000}));
# Click on second 'Click me' occurrence, wait maximum 10 seconds mouseClick(waitForOcrText("Click me", {"occurrence" => 2, "timeout" => 10000}))
# Click on second 'Click me' occurrence, wait maximum 10 seconds invoke mouseClick [waitForOcrText "Click me" {occurrence 2 timeout 10000}]
In case a searchRegion is specified as the last argument, the OCR is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the OCR scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section. Since the Image
object specified
as the search region cannot possibly change overtime, this function
will not perform the OCR repetitively and will return the results
immediately.
# Click on text on the MyWidget object mouseClick( waitForOcrText( "Click me", {}, waitForObject( names.MyWidget ) ) # Click on text on multiple objects mouseClick( waitForOcrText( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ) # Click on text on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 mouseClick( waitForOcrText( "Click me", {}, bounds ) ) # Click on text in the specified area mouseClick( waitForOcrText( "Click me", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) ) # Click on text on all top-level objects mouseClick( waitForOcrText( "Click me", {}, "all" ) )
# Click on text on the MyWidget object mouseClick( waitForOcrText( "Click me", {}, waitForObject( names.MyWidget ) ) ); // Click on text on multiple objects mouseClick( waitForOcrText( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ); // Click on text on the left half of the MyWidget object var bounds = object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 mouseClick( waitForOcrText( "Click me", {}, bounds ) ); // Click on text in the specified area mouseClick( waitForOcrText( "Click me", {}, new UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) ); // Click on text on all top-level objects mouseClick( waitForOcrText( "Click me", {}, "all" ) );
# Click on text on the MyWidget object mouseClick( waitForOcrText( "Click me", {}, waitForObject( names::MyWidget ) ) ); # Click on text on multiple objects mouseClick( waitForOcrText( "Click me", {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ) ); # Click on text on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; mouseClick( waitForOcrText( "Click me", {}, bounds ) ); # Click on text in the specified area mouseClick( waitForOcrText( "Click me", {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ) ); # Click on text on all top-level objects mouseClick( waitForOcrText( "Click me", {}, "all" ) )
# Click on text on the MyWidget object mouseClick( waitForOcrText( "Click me", {}, waitForObject( names.MyWidget ) ) ); # Click on text on multiple objects mouseClick( waitForOcrText( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) ); # Click on text on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 mouseClick( waitForOcrText( "Click me", {}, bounds ) ); # Click on text in the specified area mouseClick( waitForOcrText( "Click me", {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ) ); # Click on text on all top-level objects mouseClick( waitForOcrText( "Click me", {}, "all" ) );
# Click on text on the MyWidget object invoke mouseClick [ waitForOcrText "Click me" {} [ waitForObject $names::MyWidget ] ] # Click on text on multiple objects invoke mouseClick [ waitForOcrText "Click me" {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } ] # Click on text on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] invoke mouseClick [ waitForOcrText "Click me" {} $bounds ] # Click on text in the specified area invoke mouseClick [ waitForOcrText "Click me" {} [ construct ScreenRectangle 100 100 200 300 ] ] # Click on text on all top-level objects invoke mouseClick [ waitForOcrText "Click me" {} "all" ]
doubleClick(
screenRectangle, modifierState, button)
;
This function performs a mouse double click at the position specified by
screenPoint
or at the center of the rectangle specified
by screenRectangle
. Both positions are in screen global
coordinates. The optional modifierState
and
button
arguments specify keyboard modifiers and the
mouse button that are held down during the click. See Squish API Function Parameters for a list of valid modifierState
and button values.
This function performs a key press of the specified key
keyboard key. This key
argument is either a single
character or a special key which is written between angle brackets (<>).
E.g. "<Ctrl>"
for the control key,
"<Alt>"
for the alt key, "<Shift>"
,
"<Return>"
for the enter key and "<Tab>"
for the tab key.
This function performs a key release of the specified key
keyboard key. This key
argument is either a single
character or a special key which is written between angle brackets (<>),
see keyPress
.
mouseClick(
screenRectangle, modifierState, button)
;
This function performs a mouse click at the position specified by
screenPoint
or at the center of the rectangle specified
by screenRectangle
. Both positions are in screen global
coordinates. The optional modifierState
and
button
arguments specify keyboard modifiers and the
mouse button that are held down during the click. See Squish API Function Parameters for a list of valid modifierState
and button values.
mouseMove(
objectOrName)
;
mouseMove(
objectOrName, x, y)
;
This function moves the mouse to position x
and
y
relative to the top-left of the
objectOrName
widget if one is specified, or
relative to the current screen otherwise.
If no coordinates are specified, the mouse is moved to the middle of the
objectOrName
widget.
This function is useful if you want to trigger events that need the mouse to be at a particular position. For example, tooltips normally only appear when the mouse is over a certain area.
mousePress(
mouseButton)
;
mousePress(
mouseButton, modifierState)
;
mousePress(
x, y, mouseButton)
;
mousePress(
x, y, mouseButton, modifierState)
;
mousePress(
objectOrName)
;
mousePress(
objectOrName, mouseButton)
;
mousePress(
objectOrName, mouseButton, modifierState)
;
mousePress(
objectOrName, x, y, mouseButton)
;
mousePress(
objectOrName, x, y, mouseButton, modifierState)
;
This function performs a mouse press. All the parameters are optional, but either both or neither of the coordinates (x,y) must be present.
If x
and y
coordinates are
given, the press takes place at those coordinates, either relative to the
objectOrName
object if one is specified, or
relative to the current screen otherwise. If no coordinates are given
the press takes place on the middle of the
objectOrName
object if one is specified, or
wherever the mouse happens to be otherwise.
By default MouseButton.LeftButton
is used, but this can be
changed by specifying the optional mouseButton
argument. Similarly a default modifier state of no modifiers is used,
but this can be changed by specifying the
modifierState
argument. See Squish API Function Parameters for which values are valid for
the mouseButton
argument and for the
modifierState
argument.
![]() | Note |
---|---|
When executing tests on Windows systems, |
There is a toolkit-specific version of this function that may have
different arguments:
mousePress
(Windows).
mouseRelease(
mouseButton)
;
mouseRelease(
mouseButton, modifierState)
;
mouseRelease(
x, y, mouseButton)
;
mouseRelease(
x, y, mouseButton, modifierState)
;
mouseRelease(
objectOrName)
;
mouseRelease(
objectOrName, mouseButton)
;
mouseRelease(
objectOrName, mouseButton, modifierState)
;
mouseRelease(
objectOrName, x, y, mouseButton)
;
mouseRelease(
objectOrName, x, y, mouseButton, modifierState)
;
This function performs a mouse release. All the parameters are optional excepting that either both or neither of the coordinates must be present.
If x
and y
coordinates are
given, the release takes place at those coordinates, either relative to the
objectOrName
object if one is specified, or
relative to the current screen otherwise. If no coordinates are given
the release takes place on the middle of the
objectOrName
object if one is specified, or
wherever the mouse happens to be otherwise.
By default MouseButton.LeftButton
is used, but this can be
changed by specifying the optional mouseButton
argument. Similarly a default modifier state of no modifiers is used,
but this can be changed by specifying the
modifierState
argument. See Squish API Function Parameters for which values are valid for
the mouseButton
argument and for the
modifierState
argument.
![]() | Note |
---|---|
When executing tests on Windows systems, |
There is a toolkit-specific version of this function that may have
different arguments:
mouseRelease
(Windows).
tapObject(
screenRectangle, modifierState, button)
;
This function performs a touch tap at the position specified by
screenPoint
or at the center of the rectangle specified
by screenRectangle
. Both positions are in screen global
coordinates. The optional modifierState
and
button
arguments specify keyboard modifiers and the
mouse button that are held down during the click. See Squish API Function Parameters for a list of valid modifierState
and button values.
This function returns the object
's class name as
a string.
(A suitable object can be obtained using the waitForObject
function or the
findObject
function.)
![]() | Python-specific |
---|---|
This function is only available to Python test scripts; for other script
languages use the |
This function highlights the screen position of the object specified
by objectOrName
through a red rectangle. Such a
visual confirmation can be useful if there is doubt about whether
an object found via waitForObject
,
waitForImage
and related functions is the
correct object.
The red overlay will remain on the screen for 3 seconds unless
overridden by the optional timeout
parameter.
This function returns a true value if the object
is null (e.g., a null-pointer in C++); otherwise it returns a false
value.
(A suitable object can be obtained using the waitForObject
function or the
findObject
function.)
This function returns the object
's class name as
a string.
(A suitable object can be obtained using the waitForObject
function or the
findObject
function.)
For objects that are created in test scripts, this is their
actual type name. For widgets and other application objects, Squish
tries to return the correct type name, and if that isn't possible,
returns "Object", the name of Squish's generic object type, instead.
JavaScript, Perl, Ruby, and Tcl scripts should always return the correct
type name. Python scripts usually return "Object" for application
objects, but Squish's API for Python includes the className
function, which returns the correct class
name of the object it is given, whether that object is created in a test
script or is an application object.
This function will cause the debugger to stop at this position.
This function will copy the file referenced by pathToFile
into the
test report directory specified when starting Squish and create an entry
in the test report pointing to the file copy if the report generator supports
this. The optional message
allows to specify a short
description of the attachment and will be included in the report as well.
The pathToFile
can specify the file to attach using an
absolute or a relative path. In the case that a relative is being used it'll be
appended to the current working directory of the script interpreter running the
test.
Currently only the XML3, the HTML and the JSON report generators have dedicated
support for attachments. Other generators can be used with test.attachFile, but
will only generate a normal log message including the path to the attached file
and the provided message
.
The copied file will appear in an attachments subdirectory that is going to be inside a directory named after the testcase. In turn the testcase directory will be inside a directory named after the suite, which is placed in the test report directory. The name of the copied file will match the file name of the originally specified file. If a file of that name already exists in the report directory a number will be added to make the file name unique.
For report generators that do not require specifying a test report directory
but rather take a file (like xml2, xml or xmljunit) you can either specify
--resultdir
when invoking squishrunner to
specify the test report directory or Squish will fall back to generate the
attachments directory inside the testcase that is currently being executed when
test.attachFile is being invoked.
This function will create a screenshot of the desktop from the system where the
currently active AUT is running and store that in the test report directory. In
addition an entry is being logged in the test report indicating the path of the
screenshot file as well as including the specified message
.
The screenshot will be stored in the lossless PNG format under the
same attachments subdirectory as files attached using the test.attachFile
function and thus the same
restrictions and comments regarding the used report generator apply for this
function too.
This API is a shorthand for test.attachImage(grabDesktopScreenshot(),
message)
.
This function will store the specified image in the test report directory. In
addition an entry is being logged in the test report indicating the path of the
image file as well as including the specified message
.
The image will be stored in the lossless PNG format under the
same attachments subdirectory as files attached using the test.attachFile
function and thus the same
restrictions and comments regarding the used report generator apply for this
function too.
This function will start the desktop video capture on the system where the application under test
is running. The video file will be stored as part of the test report and logged in the test report
using the specified message
. The message
is optional:
if it is not specified, a default message containing the application name will be added to the report.
At any point in the script, there can be only one video capture for a given application context. Attempting to start another video capture on the same application context will result in an error.
The video capture will be stopped when the application under test terminates or is disconnected from, either through the test script commands or as part of the ending of the test case. In case of sudden, unexpected terminations of the application under test, the video file may be incomplete.
The video capture can be explicitly terminated at any point after starting it using the
test.stopVideoCapture
.
If video capture is enabled for all applications through --enable-video-capture
commandline option, then this function will only add a log message to the test report (see also
Playback option --enable-video-capture
(Section 7.4.3.8)).
![]() | Note |
---|---|
The video capture feature has some technical limitations. Please refer to the page Known Video Capture Limitations in our Knowledge Base for more information. |
This function will stop the desktop video capture on the system where the application under test
is running. The end of the video capture will be logged in the test report using the specified
message
.The message
is optional: if it is not
specified, a default message containing the application name will be added to the report.
Attempting to stop video capture where no capture is currently active will result in an exception
being thrown. Starting the video capture is done through test.startVideoCapture
,
or by enabling it on the commandline using --enable-video-capture"
option
(see also Playback option --enable-video-capture
(Section 7.4.3.8)).
If video capture is enabled for all applications through --enable-video-capture
commandline option, then this function will only add a log message to the test report. The video
capture will be terminated automatically when the application has been terminated.
Casts the object
to the given
type
and returns a reference to that object, or
to a new copy of the object if the object
is of
an immutable type. (A suitable object can be obtained using the waitForObject
function or the findObject
function.) The desired
type
can be specified either by name (as a
string) or by using a type object.
For mutable objects the object
itself is
modified.
If the cast fails the object reference is returned unchanged.
This function makes it possible to downcast (e.g., from
QWidget
to QTextEdit
).
See Event Handlers for Specific Objects (Section 5.10.3) for an example of use.
See also the object.convertTo
function.
Table of Contents
The compare, verify, and exception functions are used to record the results of tests applied to a running AUT in Squish's test log as passes or fails. The other functions can be used to programmatically record any kind of test results in the test log. (See also, the Verification Point Creator view (Section 8.2.22) and How to Create and Use Verification Points (Section 5.22).)
This function grabs an image of the screen the AUT is running on and returns it as a Image Object (Section 6.3.14).
var img = grabDesktopScreenshot(); test.attachImage(img);
my $img = grabDesktopScreenshot(); test::attachImage($img);
img = grabDesktopScreenshot() test.attachImage(img)
img = grabDesktopScreenshot() Test.attachImage(img)
set img [grabDesktopScreenshot] test attachImage $img
This function grabs an image of the screen the AUT is running on and stores it on the computer where the Squish IDE (or squishrunner) is executing.
If no path is specified the file gets stored in the working directory of the squishrunner process. (The default working directory of squishrunner is the path of the test case that it is currently executing.)
If a relative path is specified it is relative to the working directory of the squishrunner process. (The default working directory of squishrunner is the path of the test case that it is currently executing.)
If an absolute path is specified that path is used as is.
The filename should have a suffix denoting the image format to be used. Here's an example of use that is legal in JavaScript, Python, Ruby, and Perl:
saveDesktopScreenshot("screen.png");
And for Tcl:
saveDesktopScreenshot "screen.png"
The available formats vary, but will always include at least the following:
.bmp
— Windows Bitmap
.png
— Portable Network Graphics
.ppm
— Portable Pixmap
.xbm
— X11 Bitmap (monochrome)
.xpm
— X11 Pixmap
This API is a shorthand for calling
grabDesktopScreenshot
followed by a call
to Image.save
on the resulting image.
This function grabs a snapshot of an object and saves it to the specified file in the xml format. The object snapshot is a state of an object, including all of its properties and its children with children's properties.
If a relative path of the snapshot is specified, it is relative to the working directory of the squishrunner process. (The default working directory of squishrunner is the path of the test case that it is currently executing.)
If an absolute path is specified that path is used as is.
What is actually saved in the snapshot can be customized by making changes to
another .xml file located in
SQUISHDIR/etc/<edition>_snapshot_filter.xml
,
where <edition> is the Squish edition you are using,
such as java
, qt
, web
,
windows
, mac
, ios
, or
android
. With this, you can exclude certain classes or
properties of classes, and decide if the real name or the symbolic name should
be included in the output.
Here's an example of use that is legal in JavaScript, Python, Ruby, and Perl:
saveObjectSnapshot( objectNameOrReference, "objectSnapshot.xml" );
And for Tcl:
saveObjectSnapshot objectNameOrReference "objectSnapshot.xml"
Boolean test.compare(
value1, value2, message)
;
This function compares value1
and
value2
, and if they are equal, a test result of
type PASS is added to the test log and this function returns a true
value. Otherwise a test result of type FAIL is added to the test log and
a false value is returned.
If the optional message
parameter (of type
string—e.g., a comment, bug number, or test plan reference)
is present, it will be added to the test result no matter whether the
test passed or failed.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the verification fails.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the verification fails.
Boolean test.exception(
code, message)
;
This function
executes the code passed as a string in code
,
expecting it to raise an exception. If an exception is raised a test
result of type PASS is added to the test log and
this function returns a true value. Otherwise a test result of
type FAIL is added to the test log and a false value is returned.
If the optional message
parameter (of type
string—e.g., a comment, bug number, or test plan reference)
is present, it will be added to the test result no matter whether the
test passed or failed.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the given code did not raise an exception.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the given code did not raise an exception.
test.fail(
message, detail)
;
This function unconditionally adds a FAIL entry to Squish's test log
with the given message
string, and with the
detail
string, if one is given.
The testSettings.breakOnFailure property can be used to make the debugger stop at this function.
The testSettings.throwOnFailure property can be used to make this function additionally raise a script exception.
test.fatal(
message, detail)
;
This function unconditionally adds a FATAL entry to Squish's test log
with the given message
string, and with the
detail
string, if one is given.
The testSettings.breakOnFailure property can be used to make the debugger stop at this function.
The testSettings.throwOnFailure property can be used to make this function additionally raise a script exception.
test.log(
message, detail)
;
This function unconditionally adds a LOG entry to Squish's test log
with the given message
string, and with the
detail
string, if one is given.
test.pass(
message, detail)
;
This function unconditionally adds a PASS entry to Squish's test log
with the given message
string, and with the
detail
string, if one is given.
![]() | Python-specific |
---|---|
Since |
This function returns the number of results of the given
resultCategory
of the current test case. The
resultCategory
must be one of the strings:
"errors"
,
"fails"
,
"fatals"
,
"passes"
,
"testcases"
,
"tests"
,
"warnings"
,
"xfails"
, or
"xpasses"
.
The result counts are only gathered for the currently running test case.
Boolean test.verify(
condition, message)
;
This function evaluates the condition
and if it
evaluates to a true value (e.g., true
or 1), a test result
of type PASS is added to the test log. Otherwise a result of type FAIL
is added to the test log. In either case the function returns the result
of evaluating the condition
, (i.e., a true value
on PASS and a false value on FAIL).
If the optional message
parameter (of type
string—e.g., a comment, bug number, or test plan reference)
is present, it will be added to the test result whether the test passed
or failed.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the verification fails.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the verification fails.
Boolean test.vp(
name, message)
;
This function executes the verification point called
name
.
If the verification point's comparison succeeds, a test result
of type PASS is added to the test
log and this function returns a true
value. Otherwise a result of type FAIL is added to the test
log and a false value is returned.
If the verification point refers to an object that is not found, the function will return a false value, and possibly pop up an object not found dialog, if Squish is configured that way.
If the optional message
parameter (of type
string—e.g., a comment, bug number, or test plan reference)
is present, it will be added to the test result whether the test passed
or failed.
In the event of a FAIL, the testcase proceeds to
the next test statement unless squishrunner is configured to
--abortOnFail
.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the verification fails.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the verification fails.
This function executes the verification point called
name
where comparison will be performed with the
objectNameOrReference
instead of an object present in the
VP file. If the verification point's comparison succeeds, a test result of type
PASS is added to the test log and this function returns a
true value. Otherwise a result of type FAIL is added to the
test log and a false value is returned. If the VP contains/verifies
more than a single object, test.vpWithObject()
will log an ERROR.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the verification fails.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the verification fails.
test.warning(
message, detail)
;
This function unconditionally adds a WARNING entry to Squish's test
log with the given message
string, and with the
detail
string, if one is given.
test.skip(
message)
;
This function skips further execution of the current script test case, or
the current BDD scenario (or BDD scenario outline iteration), by
throwing an exception and adding a SKIPPED entry to Squish's test
log with the given message
string.
If the test case logged verification failures before the skip, it is still
considered failed.
Boolean test.xcompare(
value1, value2, message)
;
This function is used to handle expected failures in test scripts. To test for bugs that should be fixed one day.
The function compares value1
and
value2
, and if they are not
equal, a test result of type XFAIL (eXpected FAILure) is added to the
test log and this function returns a false value. Otherwise a test result
of type XPASS (uneXpected PASS) is added to the test log and a true
value is returned.
The 'expected fail' result is intended for cases where you know a comparison or verification will go wrong right now due to a bug in the AUT
In test cases where you want to ensure that a property never has a certain
value, we suggest using test.verify()
, or to use
test.fail()
directly with an if-construct.
If the optional message
parameter (of type
string—e.g., a comment, bug number, or test plan reference)
is present, it will be added to the test result whether the test passed
or failed.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the verification passes unexpectedly.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the verification passes unexpectedly.
test.xfail(
message, detail)
;
This function unconditionally adds an XFAIL (eXpected FAILure) entry
to Squish's test log with the given message
string, and with the detail
string, if one is given.
The 'expected fail' result is intended for cases where you know
a comparison or verification will go wrong right now due to a bug in the AUT.
test.xpass(
message, detail)
;
This function unconditionally adds an XPASS (uneXpected PASS) entry
to Squish's test log with the given message
string, and with the detail
string, if one is given.
![]() | Python-specific |
---|---|
The Python version of this function is called |
Boolean test.xverify(
condition, message)
;
This function is used to test for expected failures in test scripts. For handling of bugs that should be fixed one day.
The function evaluates the condition
and if it
evaluates to a false value (e.g., anything that isn't true
or that's non-zero), a test result of type XFAIL (eXpected FAILure) is
added to the test log. Otherwise a test result of type XPASS (uneXpected
PASS) is added. In either case the function returns the result of
evaluating the condition
, (i.e., a false value on
XFAIL and a true value on XPASS).
If the optional message
parameter (of type
string—e.g., a comment, bug number, or test plan reference)
is present, it will be added to the test result whether the test passed
or failed.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the verification passes unexpectedly.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the verification passes unexpectedly.
Boolean test.xvp(
name, message)
;
This function is used to test expected verification point failures. For handling of bugs that should be fixed one day.
This function executes the verification point called
name
.
If the verification point's comparison fails, a test result
of type XFAIL (eXpected FAILure) is added to the test
log and this function returns a true value.
Otherwise a result of type XPASS (uneXpected PASS)
is added to the test log and a false value is returned.
If the verification point refers to an object that is not found, the function will return a false value, and possibly pop up an object not found dialog, if Squish is configured that way.
If the optional message
parameter (of type
string—e.g., a comment, bug number, or test plan reference)
is present, it will be added to the test result whether the test passed
or failed.
In the event of a XPASS, the testcase proceeds to
the next test statement unless squishrunner is configured to
--abortOnFail
.
The testSettings.breakOnFailure property can be used to make the debugger stop in case the verification passes unexpectedly.
The testSettings.throwOnFailure property can be used to make this function raise a script exception in case the verification passes unexpectedly.
StackTrace test.stackTrace(
startFrame)
;
StackTrace test.stackTrace(
startFrameIndex, maxFrameCount)
;
This function returns a list of stack frames representing the currently
active function calls. The first element in the list contains information
about the location of the test.stackTrace
call
itself, the second element contains information about its caller and so
on. The last element in the list is usually the main
function call.
Each stack frame value in the returned list features two fields:
fileName
The name of the source file in which the function call was done.
line
The line number in the script file in which the function call was done.
If the optional startFrameIndex
parameter (a number) is
given, the given number of most recent frames will be skipped. This is useful
for retrieving stack traces from framework functions, in which case the stack
trace should possibly not include the code internal to the framework itself. If
this parameter is not given it defaults to zero, i.e. no frames are skipped.
If both startFrameIndex
as well as
maxFrameCount
are given, the stack trace will be limited
to maxFrameCount
frames, i.e. it will not be computed
all the way back to the initial call to the main
function. This
can improve performance for deeply nested script frameworks.
test.fixateResultContext(
ancestorFrameIndex)
;
These functions temporarily enforce that test results created by other Squish
functions such as test.xcompare
or test.verify
will have their report entry rewritten such
that the location of the result entry is no longer the place where
text.xcompare
was called but rather any of the ancestors frames of
the current function.
The test.fixateResultContext
function adjusts the call stack frame
which is used when generating test result entries; by default, it will rewrite
the location of all result entries such that they seem to stem from the parent
stack frame. The same effect can be achieved by passing an optional argument
1
. You can pass other values to reference other ancestor stack
frames, e.g. 2
would reference the grand-parent stack framer (the
caller of the caller).
Use the test.restoreResultContext
to revert the effect of a
previous test.fixateResultContext
call. Note that the calls can be
nested, i.e. multiple subsequent calls to fixateResultContext
requires that restoreResultContext
gets called multiple times as
well.
Here are some examples; note how the test result entry triggered by the call to
test.compare
will be logged with a location pointing into the
main
function, not into the libraryFunction
function:
def libraryFunction(): test.fixateResultContext(1) test.compare("Apples", "Oranges")test.restoreResultContext() def main(): libraryFunction()
![]()
function libraryFunction() { test.fixateResultContext(1); test.compare("Apples", "Oranges");test.restoreResultContext(); } function main() { libraryFunction();
}
sub libraryFunction { test::fixateResultContext(1); test::compare("Apples", "Oranges");test::restoreResultContext(); } sub main { libraryFunction();
}
require 'squish' include Squish def libraryFunction Test.fixateResultContext(1) Test.compare("Apples", "Oranges")Test.restoreResultContext() end def main libraryFunction()
end
proc libraryFunction {} { test fixateResultContext 1 test compare "Apples" "Oranges"test restoreResultContext } proc main {} { libraryFunction
}
The script file location which is associated with the comparison in case
| |
The script file location which is associated with the comparison with
|
![]() | Warning |
---|---|
Omitting a call to |
This function will perform a search of the template image as stored
in imageFile
on the display also showing the
currently running application. On success a test result of type PASS
is added to the test log and the function returns true
.
Otherwise a test result of type FAIL is added to the test log and the
function returns false
.
The imageNotPresent()
variant of the function works
exactly the same as imagePresent()
, except it waits for
the image NOT to be found. It can be used to verify the image absence.
The search for the sub-image is performed left to right, top to
bottom. The first successful match is selected. For selection of other
matches use the occurrence
parameter as described below.
All available screens making up the desktop will be searched. At least on Windows and X11-based systems. For searches on multi-screen setup on macOS please inquire with technical support.
The search behavior can be configured through entries passed
via the optional parameterMap
argument.
occurrence
- The occurrence
index. By default the first match (with index 1) will be selected.
Index values 2 and higher will select consecutive matches.
interval
- Number of
milliseconds to wait in between image search retries. The default is
1000 (1 second).
timeout
- Amount of time in
milliseconds to search for an image before reporting that the image is
not found. The default is 20000 (20 seconds).
tolerant
- Boolean switch
that enables tolerant image search mode. In this mode some differences
between the template image and the desktop screenshot are allowed. The
default value is the value of
testSettings.imageSearchTolerant property.
threshold
- Threshold on the
correlation between template image and a desktop screenshot,
expressed as a percentage. A correlation higher than the threshold is
considered a match against the template image. Usable values for this
parameter usually fall between 99.0
and
100.0
. The default value is the value of the
testSettings.imageSearchThreshold property.
This parameter is ignored if the tolerant
parameter is
set to false
.
multiscale
- Boolean switch
that enables scaled image search mode. In this mode the template image
is expanded into a series of images of different sizes. Those image
are subsequently used as template images for the image search. The
default value is the value of the
testSettings.imageSearchMultiscale property.
This parameter is ignored if the tolerant
parameter is
set to false
.
minScale
- Lower bound on the
template image series sizes, expressed as a percentage. The resized
template image sizes will span between minScale
and
maxScale
of the original image size. The default value
is the value of the
testSettings.imageSearchMinScale property.
This parameter is ignored if either the tolerant
or the
multiscale
parameters are set to false
.
maxScale
Upper bound on the
template image series sizes, expressed as a percentage. The resized
template image sizes will span between minScale
and
maxScale
of the original image size. The default value
is the value of the
testSettings.imageSearchMaxScale property.
This parameter is ignored if either the tolerant
or the
multiscale
parameters are set to false
.
message
- An optional detailed
description (of type string) added to the test result no matter whether
the test passed or failed, much like message
argument of
test.compare
.
# Verify the icon.png is displayed test.imagePresent("icon.png") # Verify the icon.png is displayed at least twice test.imagePresent("icon.png", {"occurrence": 2})
// Verify the icon.png is displayed test.imagePresent("icon.png"); // Verify the icon.png is displayed at least twice test.imagePresent("icon.png", {"occurrence": 2});
# Verify the icon.png is displayed test::imagePresent("icon.png") # Verify the icon.png is displayed at least twice test::imagePresent("icon.png", {"occurrence" => 2})
# Verify the icon.png is displayed Test.imagePresent("icon.png") # Verify the icon.png is displayed at least twice Test.imagePresent("icon.png", {"occurrence" => 2})
# Verify the icon.png is displayed test imagePresent "icon.png" # Verify the icon.png is displayed at least twice test imagePresent "icon.png" {"occurrence": 2}
By default this function will repeatedly grab the screen content
until an image is found or until 20 seconds have passed. Longer (or
shorter) waiting periods can be set in milliseconds via a
timeout
value passed through the
parameterMap
.
The matching algorithm performs a pixel-by-pixel color value comparison. The screen content and sub-image content therefore have to match 100% unless the tolerant search mode is enabled.
# Verify the icon.png is displayed test.imagePresent( "icon.png", {'tolerant': True, 'threshold': 99.7, 'multiscale': True, 'minScale': 100.0, 'maxScale': 150.0})
// Verify the icon.png is displayed test.imagePresent("icon.png", {tolerant: true, threshold: 99.7, multiscale: true, minScale: 100.0, maxScale: 150.0});
# Verify the icon.png is displayed test::imagePresent("icon.png", {tolerant => true, threshold => 99.7, multiscale => true, minScale => 100.0, maxScale => 150.0}) );
# Verify the icon.png is displayed Test.imagePresent("icon.png", {"tolerant" => true, "threshold" => 99.7, "multiscale" => true, "minScale" => 100.0, "maxScale" => 150.0}) )
# Verify the icon.png is displayed test imagePresent "icon.png" {tolerant true \ threshold 99.7 \ multiscale true \ minScale 100.0 \ maxScale 150.0}
In case a searchRegion is specified as the last argument, the search is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the search scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section. Since the Image
object specified
as the search region cannot possibly change overtime, this function
will not perform the image search repetitively and will return the
result immediately.
# Verify the icon.png is displayed on the MyWidget object test.imagePresent("icon.png", {}, waitForObject( names.MyWidget ) ) # Verify the icon.png is displayed on multiple objects test.imagePresent("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) # Verify the icon.png is displayed on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 test.imagePresent("icon.png", {}, bounds ) # Verify the icon.png is displayed in the specified area test.imagePresent("icon.png", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) # Verify the icon.png is displayed on all top-level objects test.imagePresent("icon.png", {}, "all" )
// Verify the icon.png is displayed on the MyWidget object test.imagePresent("icon.png", {}, waitForObject( names.MyWidget ) ); // Verify the icon.png is displayed on multiple objects test.imagePresent("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); // Verify the icon.png is displayed on the left half of the MyWidget object var bounds = object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 test.imagePresent("icon.png", {}, bounds ); // Verify the icon.png is displayed in the specified area test.imagePresent("icon.png", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ); // Verify the icon.png is displayed on all top-level objects test.imagePresent("icon.png", {}, "all" );
# Verify the icon.png is displayed on the MyWidget object test::imagePresent("icon.png", {}, waitForObject( names::MyWidget ) ); # Verify the icon.png is displayed on multiple objects test::imagePresent("icon.png", {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ); # Verify the icon.png is displayed on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; test::imagePresent("icon.png", {}, bounds ); # Verify the icon.png is displayed in the specified area test::imagePresent("icon.png", {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ); # Verify the icon.png is displayed on all top-level objects test::imagePresent("icon.png", {}, "all" )
# Verify the icon.png is displayed on the MyWidget object Test.imagePresent("icon.png", {}, waitForObject( names.MyWidget ) ); # Verify the icon.png is displayed on multiple objects Test.imagePresent("icon.png", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); # Verify the icon.png is displayed on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 Test.imagePresent("icon.png", {}, bounds ); # Verify the icon.png is displayed in the specified area Test.imagePresent("icon.png", {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ); # Verify the icon.png is displayed on all top-level objects Test.imagePresent("icon.png", {}, "all" );
# Verify the icon.png is displayed on the MyWidget object test imagePresent "icon.png" {} [ waitForObject $names::MyWidget ] # Verify the icon.png is displayed on multiple objects test imagePresent "icon.png" {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } # Verify the icon.png is displayed on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] test imagePresent "icon.png" {} $bounds # Verify the icon.png is displayed in the specified area test imagePresent "icon.png" {} [ construct ScreenRectangle 100 100 200 300 ] # Verify the icon.png is displayed on all top-level objects test imagePresent "icon.png" {} "all"
This function will perform optical character recognition on the
display also showing the currently running application and search for
the specific text within the result set. If the specified text is present,
a test result of type PASS is added to the test log and the function
returns true
. Otherwise a test result of type FAIL is added
to the test log and the function returns false
.
The ocrTextNotPresent()
variant of the function works
exactly the same as ocrTextPresent()
, except it waits for
the text NOT to be found. It can be used to verify the text absence.
The OCR will be performed over all available screens making up the desktop. At least on Windows and X11-based systems. For OCR on multi-screen setup on macOS please inquire with technical support.
The search behavior can be configured through entries passed
via the optional parameterMap
argument.
interval
- Minimal number of
milliseconds to wait in between OCR search retries. The default is
1000 (1 second). The actual interval between separate OCR attempts is
dependent on OCR engine performance, and may be significantly longer.
timeout
- Amount of time in
milliseconds to search for the specified text before reporting that
the text is not found. The default is 20000 (20 seconds).
occurrence
- The occurrence
index. By default the first text match (with index 1) will be
returned. Index values 2 and higher will select consecutive matches as
far as available.
language
- The language hint
for OCR engine. Use an empty string to use the OCR engine defaults.
The default value is the value of
testSettings.defaultOcrLanguage property.
profiles
- An array of OCR
engine specific profile names. This parameter is used only with
engines that support profiles.
options
- A map of
engine-specific option names and values. These options are passed to
the OCR engine after loading the specified profiles.
scaleFactor
- Image up-scale
factor. The source image is upscaled by that factor before it is
passed to the OCR engine. The default value is
3.5
. It can be set to a lower value to improve
the OCR performance in case the text is rendered with a large font.
message
- An optional detailed
description (of type string) added to the test result no matter whether
the test passed or failed, much like message
argument of
test.compare
.
# Verify the 'Hier klicken' German text is displayed at least twice test.ocrTextPresent("Hier klicken", {"occurrence": 2, "language": "German"})
// Verify the 'Hier klicken' German text is displayed at least twice test.ocrTextPresent("Hier klicken", {occurrence: 2, language: "German"});
# Verify the 'Hier klicken' German text is displayed at least twice test::ocrTextPresent("Hier klicken", {"occurrence" => 2, "language" => "German"});
# Verify the 'Hier klicken' German text is displayed at least twice Test.ocrTextPresent("Hier klicken", {"occurrence" => 2, "language" => "German"})
# Verify the 'Hier klicken' German text is displayed at least twice test ocrTextPresent "Hier klicken" {occurrence 2 language "German"}
By default this function will repeatedly grab the screen content
until the specified text is found or until 20 seconds have passed. Longer
(or shorter) waiting periods can be set in milliseconds via a
timeout
value passed through the
parameterMap
.
In case a searchRegion is specified as the last argument, the OCR is performed only within the area corresponding to it. The search region can be an AUT object, a ScreenRectangle object or an array of such objects. It can also be a special string value "all", in which case all top-level objects are used.
The searchRegion can also be an Image object. In such case no new screenshots
are taken and the specified image is used instead. Currently it is not
possible to limit the OCR scope to a portion of an Image
object; please use the Image.copy
to cut
the relevant section. Since the Image
object specified
as the search region cannot possibly change overtime, this function
will not perform the OCR repetitively and will return the results
immediately.
# Verify the 'Click me' text is displayed on the MyWidget object test.ocrTextPresent( "Click me", {}, waitForObject( names.MyWidget ) # Verify the 'Click me' text is displayed on multiple objects test.ocrTextPresent( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ) # Verify the 'Click me' text is displayed on the left half of the MyWidget object bounds = object.globalBounds( waitForObject( names.MyWidget ) ) bounds.width = bounds.width / 2 test.ocrTextPresent( "Click me", {}, bounds ) # Verify the 'Click me' text is displayed in the specified area test.ocrTextPresent( "Click me", {}, UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ) # Verify the 'Click me' text is displayed on all top-level objects test.ocrTextPresent( "Click me", {}, "all" )
# Verify the 'Click me' text is displayed on the MyWidget object test.ocrTextPresent( "Click me", {}, waitForObject( names.MyWidget ) ); // Verify the 'Click me' text is displayed on multiple objects test.ocrTextPresent( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); // Verify the 'Click me' text is displayed on the left half of the MyWidget object var bounds = object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 test.ocrTextPresent( "Click me", {}, bounds ); // Verify the 'Click me' text is displayed in the specified area test.ocrTextPresent( "Click me", {}, new UiTypes.ScreenRectangle( 100, 100, 200, 300 ) ); // Verify the 'Click me' text is displayed on all top-level objects test.ocrTextPresent( "Click me", {}, "all" );
# Verify the 'Click me' text is displayed on the MyWidget object test::ocrTextPresent( "Click me", {}, waitForObject( names::MyWidget ) ); # Verify the 'Click me' text is displayed on multiple objects test::ocrTextPresent( "Click me", {}, ( waitForObject( names::MyWidget ), waitForObject( names::MyOtherWidget ) ) ); # Verify the 'Click me' text is displayed on the left half of the MyWidget object my $bounds = object::globalBounds( waitForObject( names::MyWidget ) ); $bounds->width = $bounds->width / 2; test::ocrTextPresent( "Click me", {}, bounds ); # Verify the 'Click me' text is displayed in the specified area test::ocrTextPresent( "Click me", {}, new UiTypes::ScreenRectangle( 100, 100, 200, 300 ) ); # Verify the 'Click me' text is displayed on all top-level objects test::ocrTextPresent( "Click me", {}, "all" );
# Verify the 'Click me' text is displayed on the MyWidget object Test.ocrTextPresent( "Click me", {}, waitForObject( names.MyWidget ) ); # Verify the 'Click me' text is displayed on multiple objects Test.ocrTextPresent( "Click me", {}, [ waitForObject( names.MyWidget ), waitForObject( names.MyOtherWidget ) ] ); # Verify the 'Click me' text is displayed on the left half of the MyWidget object bounds = Squish::Object.globalBounds( waitForObject( names.MyWidget ) ); bounds.width = bounds.width / 2 Test.ocrTextPresent( "Click me", {}, bounds ); # Verify the 'Click me' text is displayed in the specified area Test.ocrTextPresent( "Click me", {}, UiTypes::ScreenRectangle.new( 100, 100, 200, 300 ) ); # Verify the 'Click me' text is displayed on all top-level objects Test.ocrTextPresent( "Click me", {}, "all" );
# Verify the 'Click me' text is displayed on the MyWidget object test ocrTextPresent "Click me" {} [ waitForObject $names::MyWidget ] # Verify the 'Click me' text is displayed on multiple objects test ocrTextPresent "Click me" {} { [ waitForObject $names::MyWidget ], [ waitForObject $names::MyOtherWidget ] } # Verify the 'Click me' text is displayed on the left half of the MyWidget object set bounds [object globalBounds [ waitForObject $names::MyWidget ] ] property set $bounds width [ expr [ property get $bounds width ] / 2 ] test ocrTextPresent "Click me" {} $bounds # Verify the 'Click me' text is displayed in the specified area test ocrTextPresent "Click me" {} [ construct ScreenRectangle 100 100 200 300 ] # Verify the 'Click me' text is displayed on all top-level objects test ocrTextPresent "Click me" {} "all"
Some functions need to be called in pairs to work correctly. For instance,
fixateResultContext
& restoreResultContext
should go together, just like startsection
& endSection
.
In order to ensure that this is the case even when script exceptions are raised
(or the control flow could bypass one of the statements by other means, e.g. a
return;
statement), it is advisable to wrap the calls to the function
pairs into helper functions which ensure that they always go together.
Here are some examples for how to ensure that fixateResultContext
and
restoreResultContext
always go together. The same approach is applicable
to startSection
& endSection
:
# # Python 2.5 or newer # def resultsReportedAtCallsite(ancestorLevel = 1): class Ctx: def __enter__(self): test.fixateResultContext(ancestorLevel + 1) def __exit__(self, exc_type, exc_value, traceback): test.restoreResultContext() return Ctx() def libraryFunction(): with resultsReportedAtCallsite(): test.compare("Apples", "Oranges")
# # Python 2.4 or earlier; these versions don't have the 'with' statement yet. # def withResultsReportedAtCallsite(callable, ancestorLevel = 1): test.fixateResultContext(ancestorLevel + 1) try: return callable() finally: test.restoreResultContext() def libraryFunction(): def go(): test.compare("Apples", "Oranges") withResultsReportedAtCallsite(go)
function withResultsReportedAtCallsite(f) { test.fixateResultContext(2); try { return f(); } finally { test.restoreResultContext(); } } function libraryFunction() { withResultsReportedAtCallsite(function() { test.compare("Apples", "Oranges"); }); }
sub withResultsReportedAtCallsite { my $code = shift; test::fixateResultContext(2); $code->(); test::restoreResultContext(); } sub libraryFunction { withResultsReportedAtCallsite sub { test::compare("Apples", "Oranges"); }; }
require 'squish' include Squish def withResultsReportedAtCallsite Test.fixateResultContext( 2 ) begin yield ensure Test.restoreResultContext() end end def libraryFunction withResultsReportedAtCallsite do Test.compare("Apples", "Oranges") end end
proc withResultsReportedAtCallsite {body} { test fixateResultContext 2 uplevel 1 $body test restoreResultContext } proc libraryFunction {} { withResultsReportedAtCallsite { test compare "Apples" "Oranges" } }
test.startSection(
title, description)
;
These functions can be used to group test results into logical units. A set of
comparison or log/warning statements can be enclosed in
startSection
/endSection
to have it logged as a
distinct result section. The Squish IDE will display result sections as a nested set
of test results. Executing tests on the commandline will, except when the XML3
report generator is used, get log messages added to the test report whenever a
section starts or ends.
![]() | Warning |
---|---|
Omitting a call to |
Boolean test.compareTextFiles(
expectedFilePath, actualFilePath, options)
;
This function compares the expected file specified by expectedFilePath
and compares it to the actual file specified by actualFilePath
. If they
are equal a test result of type PASS is added to the test log and the function returns a true
value. Otherwise a test result of type FAIL is added to the test log and a false value is returned.
If the files are different a diff that shows which lines have changed is created which can be found
in the test result message details.
The optional parameter options
can be specified as a map or dictionary.
So far the following options can be set:
strictLineEndings : If this is set to true
the function will pick up
if two files use different line endings (e.g. CR+LF on windows or LF on unix). The default is
false
.
//example 1: no options test.compareTextFiles("expected.txt", "actual.txt"); //example 2: with options test.compareTextFiles("expected.txt", "actual.txt", {'strictLineEndings': true});
#example 1: no options test::compareTextFiles("expected.txt", "actual.txt"); #example 2: with options test::compareTextFiles("expected.txt", "actual.txt", {"strictLineEndings" => 1});
#example 1: no options test.compareTextFiles("expected.txt", "actual.txt") #example 2: with options test.compareTextFiles("expected.txt", "actual.txt", {'strictLineEndings': True})
#example 1: no options Test.compareTextFiles("expected.txt", "actual.txt") #example 2: with options Test.compareTextFiles("expected.txt", "actual.txt", {'strictLineEndings' => True})
#example 1: no options test compareTextFiles "expected.txt" "actual.txt" #example 2: with options test compareTextFiles "expected.txt" "actual.txt" [dict create strictLineEndings 1]
Boolean test.compareXMLFiles(
expectedFilePath, actualFilePath, options)
;
This function compares the expected XML file specified by expectedFilePath
with the actual XML file specified by actualFilePath
.
If they are equal, a test result of type PASS is added to the test log and this function returns
a true value. Otherwise a test result of type FAIL is added to the test log and a false value is
returned. If the files are different the result message details will show in which line and for
what reason the comparison failed.
The optional parameter options
can be specified as a map or dictionary.
So far the following options can be set:
ignoreNodeOrder : If this is set to true
the function will ignore
the order of elements on the same level, i.e. with the same parent element. The default is
false
.
ignoreAttributeOrder : If this is set to true
the function will ignore
the order of attributes inside an element. The default is true
.
ignoreComments : If this is set to true
the function will ignore
all comments. If it is set to false
all comments are compared. The default is
true
.
whitespaceInTextHandling : This option can be used to control how whitespaces
inside of text elements are processed. This can be set to either preserve
,
normalize
or trim
. If this is set to preserve
all whitespaces
are kept, if this is set to normalize
all whitespaces will be normalized and if this
is set to trim
whitespaces at the start and end of the text elements are removed.
The default is normalize
.
whitespaceInValuesHandling : This option can be used to control how whitespaces
inside of attribute values are processed. This can be set to either preserve
,
normalize
or trim
. If this is set to preserve
all whitespaces
are kept, if this is set to normalize
all whitespaces will be normalized and if this
is set to trim
whitespaces at the start and end of the attribute values are removed.
The default is preserve
.
ignoreCDATA : If this is set to true
only the text inside the
CDATA tags will be compared. The tags itself will be ignored. If this is set to false
the tags will also be compared. The default is true
.
matchSpecialTags : If this is set to true
special tags like the
declaration, processing instructions and doctype tags will also be compared by value.
The default is false
.
filteredElements : This option accepts a list/array of strings representing tag names. Tags that have a name contained inside the filtered elements list will be ignored when comparing the two documents.
filteredAttributes : This option accepts a list/array of strings representing attribute names. Attributes that have a name contained inside the filtered attributes list will be ignored when comparing the two documents.
You can also compare XML files with the test.compareTextFiles
function but this function has the advantage that it does not consider the file formatting.
Instead it looks directly at the structure of the files and compares nodes and attributes.
//example 1: no options test.compareXMLFiles("expected.xml", "actual.xml"); //example 2: you only need to specify the options you need test.compareXMLFiles("expected.xml", "actual.xml", {'ignoreNodeOrder': false}); //example 3: with filtered attributes and elements filteredAttributes = ["version", "xmlns"]; filteredElements = ["uri"]; options = {'ignoreNodeOrder': false, 'ignoreAttributeOrder': true, 'filteredAttributes': filteredAttributes, 'filteredElements': filteredElements, 'whitespaceInTextHandling':'trim'}; test.compareXMLFiles("expected.xml", "actual.xml", options);
#example 1: no options test::compareXMLFiles("expected.xml", "actual.xml"); #example 2: you only need to specify the options you need test::compareXMLFiles("expected.xml", "actual.xml", {"ignoreNodeOrder" => 0}); #example 3: with filtered attributes and elements my $filteredAttributes = ["version", "xmlns"]; my $filteredElements = ["uri"]; my $options = {"ignoreNodeOrder" => 0, "ignoreAttributeOrder" => 1, "filteredAttributes" => $filteredAttributes, "filteredElements" => $filteredElements, "whitespaceInTextHandling" => "trim"}; test::compareXMLFiles("expected.xml", "actual.xml", $options);
#example 1: no options test.compareXMLFiles("expected.xml", "actual.xml") #example 2: you only need to specify the options you need test.compareXMLFiles("expected.xml", "actual.xml", {'ignoreNodeOrder': False}) #example 3: with filtered attributes and elements filteredAttributes = ["version", "xmlns"] filteredElements = ["uri"] options = {'ignoreNodeOrder': False, 'ignoreAttributeOrder': True, 'filteredAttributes': filteredAttributes, 'filteredElements': filteredElements, 'whitespaceInTextHandling':'trim'} test.compareXMLFiles("expected.xml", "actual.xml", options)
#example 1: no options Test.compareXMLFiles("expected.xml", "actual.xml") #example 2: you only need to specify the options you need Test.compareXMLFiles("expected.xml", "actual.xml", {'ignoreNodeOrder' => false}) #example 3: with filtered attributes and elements filteredAttributes = ["version", "xmlns"] filteredElements = ["uri"] options = {'ignoreNodeOrder' => false, 'ignoreAttributeOrder' => true, 'filteredAttributes' => filteredAttributes, 'filteredElements' => filteredElements, 'whitespaceInTextHandling' => 'trim'} Test.compareXMLFiles("expected.xml", "actual.xml", options)
#example 1: no options test compareXMLFiles "expected.xml" "actual.xml" #example 2: you only need to specify the options you need test compareXMLFiles "expected.xml" "actual.xml" [dict create ignoreNodeOrder 0] #example 3: with filtered attributes and elements set filteredAttributes [list version xmlns] set filteredElements [list uri] set options [dict create ignoreNodeOrder 0 \ ignoreAttributeOrder 1 \ filteredAttributes $filteredAttributes \ filteredElements $filteredElements \ whitespaceInTextHandling trim] test compareXMLFiles "expected.xml" "actual.xml" $options
This function compares the expected JSON file specified by expectedFilePath
with the actual JSON file specified by actualFilePath
.
If they are equal, a test result of type PASS is added to the test log and this function returns
a true value. Otherwise a test result of type FAIL is added to the test log and a false value is
returned. If the files are different the result message details will show for what reason the
comparison failed as well as a textual diff.
![]() | Warning |
---|---|
Due to features and constraints of the used JSON library, non-standard and possibly unwanted JSON might pass the test.
Please validate the JSON files and make sure there are no duplicate names before calling them with |
This function creates a Visual Verification Point named vpFile
to be
used with test.vp
and test.xvp
in a later test run.
Whereas this action is typically performed via point & click in the Squish IDE.
The expected visual state is determined through an internal call
to saveObjectSnapshot
for the object
denoted by objectNameOrReference
.
The newly created verification point will have all of content, geometry and screenshot checks enabled. The Visual Verification Point Editor can later be used to modify these checks.
In case vpFile
already exists the function will
throw a catchable script exception.
Squish can handle tabular data (rows and columns—or in database terminology, records and fields). With respect to Squish's data handling functions, we use the terms “row” and “record” as synonyms, and similarly, “column” and “field”.
Squish can read in test data from .tsv
(tab-separated values format), .csv
(comma-separated values format),
.xls
or .xlsx
(Microsoft®
Excel™ spreadsheet format) files. In
the case of .csv
and .tsv
files, Squish assumes that they use the Unicode UTF-8
encoding—the same encoding used for all test scripts.
![]() | Data Row Indexing |
---|---|
In the Squish IDE, the first row of data is used for the headers, with row indexes shown counting from 1. However, the functions listed in this subsection use 0-based indexing, so the first record is at row 0, the second record at row 1, and so on. (And in fact the headers are accessible at row index -1.) |
The test data functions are used for data-driven and keyword-driven testing. For examples of data-driven testing see the Tutorials, and for examples of keyword-driven testing see How to Do Keyword-Driven Testing (Section 5.16).
This function returns the name of a file you can write to. If the
where
parameter is "shared"
, the
filename will have a path that locates the file in the test suite's
shared test data directory
(test_suite/shared/testdata/filename
),
and if the where
is "local"
the
filename will have a path that locates the file in the test suite's,
test case's test data directory
(test_suite/tst_case/testdata/filename
).
This function is designed to be used when you are running a script in a “learning” mode and want to create test data dynamically.
This function (along with the testData.fieldNames
, testData.field
and testData.datasetExcel
functions), is used for data-driven and
keyword-driven testing.
The testData.dataset
function returns a
dataset object that refers to an array or tuple of
records. The data is retrieved from the file specified by the
filename
—providing the data is in one of
the file formats that Squish recognizes.
The normal practice is for the filename
to be
given without a path (e.g., mydata.csv
). In this
case, Squish first tries to find the file in the test case's data
(i.e., in the test case's testdata
folder if it has
one). If that fails, Squish next tries looking in the test suite's
shared data folder (i.e., in the test suite's
shared/testdata
folder). If the file isn't found
(or is found but cannot be read or understood), Squish throws a
catchable exception. If the filename
is specified
with a path (e.g., C:\mydata\mydata.csv
), then
Squish tries to read that specific file and throws a catchable
exception if the file doesn't exist or isn't in a format that Squish
can understand.
The field names and field values can be retrieved using the functions described below.
This function (along with the testData.fieldNames
,
testData.field
and testData.dataset
functions), is used for data-driven and
keyword-driven testing.
The testData.datasetExcel
function returns a
dataset object that refers to an array or tuple of
records. The data is retrieved from the file specified by the
filename
and sheetname
— providing the data is in one of
the Excel formats i.e. having extension .xls or .xlsx. This function is a specification of the function testData.dataset
.
For a detailed description of the function's behavior please see info
to testData.dataset
above.
The only specific is the second parameter of the function, namely
sheetname
. This is the name of the particular sheet within the Excel document.
This parameter is optional. By default the first sheet will be used.
This is an old API and it is generally better to use
RemoteSystem.exists
instead.
This function returns a true value if a file called
filename
exists in the AUT's current working
directory; otherwise it returns a false value.
String testData.field(
record, fieldIndex)
;
This function returns the value of the field specified by the given
fieldName
string or the given
fieldIndex
integer, taken from the specified
record
(i.e., from a particular row from
the dataset returned by the
testData.dataset
function).
See How to Do Data-Driven Testing (Section 5.23.2) for usage examples.
This function returns an array or tuple of field names for the specified
record
(i.e., from a particular row from
the dataset returned by the
testData.dataset
function).
This function copies the file called filename
from the AUT's current working directory to squishrunner's current working
directory. Generally, for copying remote files to a local machine, it is better
to use RemoteSystem.download
instead.
This function removes the file called filename
from the AUT's current working directory.
If the filename
is specified without a path, this
function copies the test data file called
filename
from the test case's directory into the
AUT's current working directory. If the filename
is specified with a path, this function copies the specified file into
the AUT's current working directory. When the AUT is terminated the
copied test data file is automatically deleted.
This function returns the full path of the file copied or, in case of error, throws an exception that can be caught in the test script.
Note that if multiple AUTs are involved—for example, if one AUT
starts another program—the deletion occurs when the program in
whose context the call to the testData.put
function was
made is terminated.
For information about manipulating the Object Map using the Squish IDE see the Object Map view (Section 8.2.10). For more about Object Maps in use see Object Map (Section 7.11).
![]() | Note |
---|---|
These functions are only relevant for Text-Based Object Map (Section 7.11.5); when using Script-Based Object Map (Section 7.11.4), object names are plain script variables and hence no dedicated API is required to handle them. |
This function adds the given object
to the object
map. (A suitable object can be obtained using the waitForObject
function or the findObject
function.)
This function loads an object map from the given
filename
and uses it to
replace the current object map. If the file does
not exist, an exception is raised and the current object map is left
unchanged.
String objectMap.realName(
symbolicName)
;
This function returns the real (multi-property) name for the given
object
, or for the object with the given
symbolicName
.
String objectMap.symbolicName(
objectOrRealName)
;
This function tries to return the symbolic name for the specified object or real name from the object map.
If the objectOrRealName
is a real name,
and it does not match any existing object, it will simply be
returned; no error will be thrown.
If the objectOrRealName
is an invalid
real name it will simply be returned; no error will be thrown.
If the objectOrRealName
is a reference
to an object and the object map does not contain an object
name that matches this object, then a real name for this
object will be returned.
This function returns an array (a tuple in Python) containing all the mapped symbolic names. The returned names are in an arbitrary order.
Every AUT that is started by Squish has a corresponding
ApplicationContext
object. These objects provide the
following properties and functions. (For examples of use see How to Use ApplicationContext Objects (Section 5.12.3).)
Here are some quick links to the Application Context-related functions, methods and properties:
This function returns a handle to the application context object with the given name.
![]() | Tcl-specific |
---|---|
When using the Tcl scripting language, this function is called
|
This read-only property holds the command line that the application was started with.
String applicationContext.cwdThis read-only property holds the application's current working directory.
This function returns the value of the AUT process environment variable
called name
or an empty string if no such
environment variable exists.
Every application context is connected to a squishserver process. This read-only property holds the computer/host name or TCP/IP address of the computer where the squishserver process is running and which this application context is connected to.
If this application context has been created by
startApplication
then this property also
denotes the computer/host name or TCP/IP address of the computer
where the AUT is running.
This function returns a false value if the application responds before
the timeout
(in seconds) expired; otherwise it
returns a true value.
This read-only property is true
if the communication
between squishserver and Squish Hook in the AUT is still active,
otherwise false
.
The communication between squishserver and Squish Hook is shutting down when the Squish Hook is shutting down. The Squish Hook in turn is shutting down when the AUT is shutting down. (For example in case of Qt, when the main Qt event loop exits.)
However, the AUT shut down is not necessarily immediate: An AUT
can perform lengthy operations shortly before finally exiting, and so
for some amount of time isRunning
can be false
even though the AUT process is still alive.
This function detaches from a previously started (or attached) application.
If the respective application has been started with
startApplication
Squish will attempt to close
it, and eventually (if still running) forcefully close it.
If the respective application has been attached to with
attachToApplication
Squish will leave it
running but detach from it, thus leaving the application running. The
application can then be attached to with
attachToApplication
again.
After detaching from an application one should not access any of its objects anymore. (This would typically be done by using object references which had been retrieved before detaching.)
If the application context of
applicationContext.detach
is the current
application context, then the current application context will be
changed to another (random) application context. So one must make
sure to make the desired application context the current one before
proceeding. (See applicationContextList
,
currentApplicationContext
and
setApplicationContext
.)
This read-only property holds the application's name.
int applicationContext.pidThis read-only property holds the application's process identifier.
int applicationContext.portEvery application context is connected to a squishserver process. This read-only property holds the TCP port number of the squishserver process which this application context is connected to.
This function reads and returns everything which the application has
written to the stderr
stream since the last call to
readStderr
, or since the application started if there has
been no previous call.
This function reads and returns everything which the application has
written to the stdout
stream since the last call to
readStdout
, or since the application started if there has
been no previous call.
This read-only property holds the time when the application was started. (The property's data type varies depending on the scripting language used.)
int applicationContext.totalTimeThis read-only property holds the amount of time that the AUT process has been scheduled in user and kernel modes measured in milliseconds.
int applicationContext.usedMemoryThis read-only property holds the amount of memory used by the AUT process. For Windows operating systems, the value corresponds to the working set size in bytes. For Linux operating systems, the value corresponds to the resident set size (RSS), in bytes. For macOS, it is also the RSS, but in Kbytes.
This function returns an array (a tuple in Python) of handles to all the existing application contexts.
ApplicationContext attachToApplication(
autName, squishserver_host)
;
ApplicationContext attachToApplication(
autName, squishserver_host, squishserver_port)
;
ApplicationContext attachToApplication(
autName, squishserver_host, squishserver_port, timeoutSecs)
;
This function causes Squish to attach to the application called
autName
and returns a handle to its application
context. The autName
must be the name of an
application that has been registered with the squishserver as an
attachable AUT. (See Configuring squishserver (Section 7.4.4.3).) No command line options can be
given since the application should already be running.
squishserver_host
and
squishserver_port
refer to the computer where the desired squishserver is running,
and its TCP port. (This is not the host and
port of the attachable Attachable AUT. The
Attachable AUT's host and port are specified
when the Attachable AUT is registered with the
squishserver (see Register the Attachable AUT (Section 7.8.3)).)
The parameter timeoutSecs
is being used
after the socket connection to the attachable AUT has been
established. If the attachable AUT requires more seconds than
specified to respond to the attaching attempt an error will be
thrown. If no timeoutSecs
is specified the
squishserver's (Maximum Startup Time) default is used—this
is 20 seconds, unless it has been changed; see
Squish Server Settings dialog (Section 8.3.22).
If you want to specify a timeout, but don't want to change the host or
port, you can do so by passing an empty string as the host (which will
make Squish use the configured host—localhost
by
default), and by passing -1 as the port.
If attaching fails (e.g,. because the AUT is not running), this function throws an exception that can be caught in the test script. If the exception is not caught an error will be logged as an error in the test script's execution.
See Attaching to Running Applications (Section 7.8) for more information.
This function returns a handle to the current application context.
This function returns a handle to the default application context. It is
more reliable to use the currentApplicationContext
function instead.
This function can be used to change the current application context. The
contextHandle
object is a handle to an
application context that has been returned by the any of the functions
that return one—applicationContextList
,
attachToApplication
,
defaultApplicationContext
,
currentApplicationContext
, and
startApplication
.
If the argument is omitted the default context is activated.
If the contextHandle
object is invalid—for
example, if it refers to an application that has crashed—a catchable
exception (TypeError
in Python), will be thrown.
![]() | Note |
---|---|
Changing application contexts determines which AUT the test script is interacting with at a given time, but it does not change the currently active GUI window to be displayed. For that, we use the ToplevelWindow.setForeground function. |
These functions can be used for getting and setting the clipboard text content on a machine where the AUT is running.
When working with clipboard contents containing line breaks, be aware that
their representations (\n
and \r\n
) are OS-specific.
Note to Linux users: For non-Qt X11 applications this feature does require the xsel tool to be installed. For non-Qt applications with alternative windowing system, this feature is not yet available.
ApplicationContext startApplication(
autName, host)
;
ApplicationContext startApplication(
autName, host, port)
;
ApplicationContext startApplication(
autName, host, port, timeoutSecs)
;
This function starts the specified application and returns a handle
to its application context. The autName
parameter
should be the name of an application whose path is already registered with
the squishserver. (See Configuring squishserver (Section 7.4.4.3))
It is also possible to use the absolute
path of an executable or a .jar file for autName
. In
addition, command line options can be supplied here.
Optionally, as second and third parameters a host
and port
can be specified. If these parameters
are used, instead of connecting to the default host and port (as
specified in the Squish IDE's settings or on squishrunner's command line), a
connection to the squishserver on the specified host and listening to
the specified port will be established. This makes it possible to
control multiple applications on multiple computers from a single test
script.
The fourth parameter, timeoutSecs
(an integer
number of seconds) can also be specified. This tells Squish how long it
should be prepared to wait for the application to start before throwing
an error. If not specified, the squishserver's default is used—this
is 20 seconds, and can be changed from - -
Maximum Startup Time, or by executing
squishserver --config AUTTimeout numSeconds
.
If you want to specify a timeout, but don't want to specify the host or
port, you can do so by passing an empty string as the host (which will
make Squish use the configured host—localhost
by
default), and by passing -1 as the port.
For more about how application context objects can be used, see How to Use ApplicationContext Objects (Section 5.12.3). (See also, the waitForApplicationLaunch
function.)
This read-only property holds the name of the OS the AUT is running on. Possible names include:
"Android"
— Android
"Darwin"
— macOS and iOS
"Linux"
— Linux
"QNX"
— QNX
"SunOS"
— Solaris
"Windows"
— Windows
ApplicationContext connectTo(
target, host)
;
ApplicationContext connectTo(
target, host, port)
;
This function starts a connection to a remote desktop (eg. VNC) server and
returns a handle to its application context. The target
specifies the connection parameters.
The connection target can be either a URL or a map. In order to connect to a VNC server, the parameters of both URL and parameter map need to conform to RFC 7869, ie. it may specify the following fields:
scheme
- the connection scheme
"vnc"
;
host
- the hostname of the VNC server;
port
- the TCP port of the VNC server.
If no port is specified, the default value of 5900 is used;
VncUsername
- the user name used for
VNC authentication. Used only if required by the server;
VncPassword
- the password used for
VNC authentication. Used only if required by the server.
Squish also offers a "Native" connection protocol which
allows the squishserver to connect directly to a user session it is running
in, without any need for an additional remote desktop server/authentication.
In order to use it, the "os"
scheme needs to be specified as a part
of the target
parameter. The "os"
scheme
accepts the following fields:
scheme
- the connection scheme
"os"
;
display
- the X11 display string to
connect to. If not specified, the default display string will be used. This
parameter is only relevant on UNIX-like systems and ignored on Windows and OSX
systems.
Remote desktop connections are always routed through a squishserver instance.
If the host
and port
parameters
are specified, Squish will use the server listening at the specified address.
By default the server parameters specified in the Squish IDE's settings or on
squishrunner's command line will be used.
For example:
connectTo("vnc://example.com") connectTo("vnc://example.com:5901") connectTo("vnc://example.com?VncPassword=secret") connectTo("vnc://example.com:5901?VncUsername=user&VncPassword=secret") connectTo("os://") connectTo({"scheme": "vnc", "host": "example.com"}) connectTo({"scheme": "vnc", "host": "example.com", "port": 5901}) connectTo({"scheme": "vnc", "host": "example.com", "VncPassword": "secret"}) connectTo({"scheme": "vnc", "host": "example.com", "port": 5901, "VncUsername": "user", "VncPassword": "secret"}) connectTo({"scheme": "os"})
connectTo("vnc://example.com"); connectTo("vnc://example.com:5901"); connectTo("vnc://example.com?VncPassword=secret"); connectTo("vnc://example.com:5901?VncUsername=user&VncPassword=secret"); connectTo("os://"); connectTo({scheme: "vnc", host: "example.com"}); connectTo({scheme: "vnc", host: "example.com", port: 5901}); connectTo({scheme: "vnc", host: "example.com", VncPassword: "secret"}); connectTo({scheme: "vnc", host: "example.com", port: 5901, VncUsername: "user", VncPassword: "secret"}); connectTo({scheme: "os"});
connectTo("vnc://example.com"); connectTo("vnc://example.com:5901"); connectTo("vnc://example.com?VncPassword=secret"); connectTo("vnc://example.com:5901?VncUsername=user&VncPassword=secret"); connectTo("os://"); connectTo({"scheme" => "vnc", "host" => "example.com"}); connectTo({"scheme" => "vnc", "host" => "example.com", "port" => 5901}); connectTo({"scheme" => "vnc", "host" => "example.com", "VncPassword" => "secret"}); connectTo({"scheme" => "vnc", "host" => "example.com", "port" => 5901, "VncUsername" => "user", "VncPassword" => "secret"}); connectTo({"scheme" => "os"});
connectTo("vnc://example.com"); connectTo("vnc://example.com:5901"); connectTo("vnc://example.com?VncPassword=secret"); connectTo("vnc://example.com:5901?VncUsername=user&VncPassword=secret"); connectTo("os://"); connectTo({"scheme" => "vnc", "host" => "example.com"}); connectTo({"scheme" => "vnc", "host" => "example.com", "port" => 5901}); connectTo({"scheme" => "vnc", "host" => "example.com", "VncPassword" => "secret"}); connectTo({"scheme" => "vnc", "host" => "example.com", "port" => 5901, "VncUsername" => "user", "VncPassword" => "secret"}); connectTo({"scheme" => "os"});
connectTo "vnc://example.com" connectTo "vnc://example.com:5901" connectTo "vnc://example.com?VncPassword=secret" connectTo "vnc://example.com:5901?VncUsername=user&VncPassword=secret" connectTo "os://" connectTo [ dict create "scheme" "vnc" "host" "example.com" ] connectTo [ dict create "scheme" "vnc" "host" "example.com" "port" 5901 ] connectTo [ dict create "scheme" "vnc" "host" "example.com" "VncPassword" "secret" ] connectTo [ dict create "scheme" "vnc" "host" "example.com" "port" 5901 "VncUsername" "user" "VncPassword" "secret" ] connectTo [ dict create "scheme" "os" ]
Most toolkits' grabWidget
function returns a
QImage object. This object resides in the AUT process.
The class provides a single method, save
.
QImage.save(
filename, imageFormat)
;
This method saves the image to a file with the given
filename
on the computer where the AUT is running.
In case of remote execution, the function RemoteSystem.download
can be used to transfer the
image file to the computer where the test script is being executed.
The image file format is deduced from the filename for toolkits
where this is supported and using the specified
imageFormat
otherwise.
For example:
widget = waitForObject(objectName) image = grabWidget(widget) image.save("C:\\screenshot1.png", "PNG")
var widget = waitForObject(objectName); var image = grabWidget(widget); image.save("C:\\screenshot1.png", "PNG");
my $widget = waitForObject($objectName); my $image = grabWidget($widget); $image->save("C:\\screenshot1.png", "PNG");
widget = waitForObject(objectName) image = grabWidget(widget) image.save("C:\\screenshot1.png", "PNG")
set widget [waitForObject $objectName] set image [invoke grabWidget $widget] invoke $image save "C:\\screenshot1.png" "PNG"
This example takes a screenshot of the given object and saves it to the
file screenshot1.png
in the root directory on
Windows, using the PNG (Portable Network Graphics) file format.
The available formats depend on which platform/edition you are using, but will usually include the following:
"BMP"
— Windows Bitmap
"JPG"
or "JPEG"
— Joint
Photographic Experts Group
"PNG"
— Portable Network
Graphics
"PPM"
— Portable Pixmap
"TIF"
or "TIFF"
— Tagged
Image File Format
"XBM"
— X11
Bitmap (monochrome)
"XPM"
— X11 Pixmap
For iOS testing, only the "JPEG"
and "PNG"
formats are supported.
See also:
grabWidget
[Qt]
, grabWidget
[Java]
, grabWidget
[Mac]
, grabWidget
[iOS]
, grabWidget
[Tk]
, grabWidget
[Web]
, grabWidget
[Win]
, grabWidget
[Android]
.
The global Image
object provides functions for reading,
saving and manipulation of image files. Instances of the Image
class can be obtained by loading an image from a file using
the Image.load
or by taking
screenshots using either object.grabScreenshot
or grabDesktopScreenshot
test API. It can
be used as the search region argument to image search and OCR APIs like
findImage
,
waitForImage
,
getOcrText
,
findOcrText
,
waitForOcrText
,
findAllOcrText
,
test.imagePresent
and
test.ocrTextPresent
Image Image(
QPixmap)
;
The constructor for the Image
type. It creates an image
object out of the AUT-specific QImage and QPixmap objects.
Image Image(
width, height, [color])
;
The constructor for the Image
type. It creates an image
with the specified size. The initial color of the image pixels can be
specified using the color
argument. The color may be
specified as a 32-bit ARGB value or as a set of values for each of the
color channels.
var img = new Image(100, 100, [255, 0, 0]); img.save("C:\\red.png");
my $img = Image->new(100, 100, [255, 0, 0]); $img->save("C:\\red.png");
img = Image(100, 100,[255, 0, 0]) img.save("C:\\red.png")
img = Image.new(100, 100, [255, 0, 0]); img.save("C:\\red.png");
set img [image new 100 100 {255 0 0}] invoke $img save "C:\\red.png"
This static function of the Image
object reads an image
from the specified file and returns a reference to the instance. In
case the file cannot be found or read an exception is thrown.
img = Image.load("indicator.png") test.compare(img.width, 32) test.compare(img.height, 32)
var img = Image.load("indicator.png"); test.compare(img.width, 32); test.compare(img.height, 32);
my $img = Image::load("indicator.png"); test->compare($img->width, 32); test->compare($img->height, 32);
img = Image::load("indicator.png"); Test::compare(img.width, 32) Test::compare(img.height, 32)
set img [image load "indicator.png"] test compare [property get $img width] 32 test compare [property get $img height] 32
The properties and functions available in the prototype of image instances can be found below.
Number widthThis property denotes the width of the image instance in pixels. The value is read-only. When attempting to set a new value an exception is thrown.
Number heightThis property denotes the height of the image instance in pixels. The value is read-only. When attempting to set a new value an exception is thrown.
Image.copy(
x, y, width, height)
;
This function returns a copy of a part of the image. In case the specified geometry does not fit into the image's boundary [(0, 0)...(width-1, height-1)], an exception is thrown. If the coordinate parameters are not specified, the copy of the entire image is returned.
This function saves the image instance on disk under the specified file name. In case the path is invalid or not writable, an exception is thrown. If the specified path is relative, the file is saved relative to the interpreter's current working directory, which by default, is the location of the currently executing test case.
The format of the saved file will be based on the file extension. The supported formats vary depending on which platform/edition is used, but will usually include BMP, JPG, PNG, PPM, TIF, XBM and XPM.
var img = grabDesktopScreenshot(); img.save("C:\\screenshot1.png");
my $img = grabDesktopScreenshot(); $img->save("C:\\screenshot1.png");
img = grabDesktopScreenshot() img.save("C:\\screenshot1.png")
img = grabDesktopScreenshot() img.save("C:\\screenshot1.png")
set img [grabDesktopScreenshot] invoke $img save "C:\\screenshot1.png"
This function returns an array that contains colors of the pixel at the specified position on the red, green, blue and alpha color channel (in that order). In case the pixel does not lie within the boundary of the image (from (0, 0) to (width-1, height-1)) an exception is thrown.
pixel = img.getPixelRGBA(0, 0) red = pixel[0]; green = pixel[1]; blue = pixel[2]; alpha = pixel[3];
var pixel = img.getPixelRGBA(0, 0); var red = pixel[0]; var green = pixel[1]; var blue = pixel[2]; var alpha = pixel[3];
my @pixel = $img->getPixelRGBA(0, 0); my red = $pixel[0]; my green = $pixel[1]; my blue = $pixel[2]; my alpha = $pixel[3];
pixel = img.getPixelRGBA(0, 0); red = pixel[0]; green = pixel[1]; blue = pixel[2]; alpha = pixel[3];
set pix [invoke $img getPixelRGBA 0 0] set red [lindex $pix 0] set green [lindex $pix 1] set blue [lindex $pix 2] set alpha [lindex $pix 3]
The alpha value for fully opaque pixels is 255. Fully transparent pixels have an alpha value 0.
This function returns the 32-bit ARGB color value of the pixel at the specified position. In case the pixel does not lie within the boundary of the image (from (0, 0) to (width-1, height-1)) an exception is thrown. The value can directly be compared against expected values (e.g. 0xff00ff00 for pure green).
pixel = img.getPixel(0, 0) test.compare(pixel, 0xff102030)
var pixel = img.getPixel(0, 0); test.compare(pixel, 0xff102030 );
my $pixel = $img->getPixel(0, 0); test::compare($pixel, 0xff102030);
pixel = img.getPixel(0, 0); Test::compare(pixel, 0xff102030);
set pixel [invoke $img getPixel 0 0] test compare $pixel [expr 0xff102030]
Number Image.setPixel(
x, y, Array)
;
Number Image.setPixel(
x, y, red, green, blue)
;
Number Image.setPixel(
x, y, red, green, blue, alpha)
;
This function changes the color of the pixel at the specified position. The color may be specified as a 32-bit ARGB value, as a set of values for each of the color channels: reg, green, blue and optionally alpha, or an array of such values; for example:
img.setPixel(0, 0, 0xffff0000) img.setPixel(0, 0, 255, 0, 0) img.setPixel(0, 0, 255, 0, 0, 255) img.setPixel(0, 0, [255, 0, 0]) img.setPixel(0, 0, [255, 0, 0, 255])
img.setPixel(0, 0, 0xffff0000); img.setPixel(0, 0, 255, 0, 0); img.setPixel(0, 0, 255, 0, 0, 255); img.setPixel(0, 0, [255, 0, 0]); img.setPixel(0, 0, [255, 0, 0, 255]);
$img->setPixel( 0, 0, 0xffff0000); $img->setPixel( 0, 0, 255, 0, 0); $img->setPixel( 0, 0, 255, 0, 0, 255 ); $img->setPixel( 0, 0, [255, 0, 0]); $img->setPixel( 0, 0, [255, 0, 0, 255]);
img.setPixel(0, 0, 0xffff0000) img.setPixel(0, 0, 255, 0, 0) img.setPixel(0, 0, 255, 0, 0, 255) img.setPixel(0, 0, [255, 0, 0]) img.setPixel(0, 0, [255, 0, 0, 255])
invoke $img setPixel 0 0 [expr 0xffff0000] invoke $img setPixel 0 0 255 0 0 invoke $img setPixel 0 0 255 0 0 255 invoke $img setPixel 0 0 {255 0 0} invoke $img setPixel 0 0 {255 0 0 255}
This function returns true if this image is equal to the other image. In case the argument does not reference an image instance an exception is thrown.
Information about screens. In order to use this Screen
object,
the Squish screen
library has to be included in the
script file, and Squish must be hooked into/attached to an AUT.
source(findFile("scripts", "javascript/screen.js")); function main() { startApplication("myaut"); // ... var scr = Screen.byIndex(0); var geom = scr.geometry; test.log("Screen is " + geom.width + " by " + geom.height); }
use strict; use utf8; use warnings; use Squish::Screen; sub main { startApplication("myaut"); # ... my $scr = Squish::Screen->byIndex(0); my $geom = $scr->geometry; test::log("Screen is " . $geom->width . " by " . $geom->height); }
# -*- coding: utf-8 -*- from screen import Screen def main(): startApplication("myaut") # ... scr = Screen.byIndex(0) geom = scr.geometry test.log("Screen is " + str(geom.width) + " by " + str(geom.height))
# encoding: UTF-8 require 'squish' require 'squish/screen' def main startApplication("myaut") # ... scr = Screen::byIndex(0) geom = scr.geometry Test.log("Screen is " + geom.width.to_s + " by " + geom.height.to_s)
package require squish::screen # ... set scr [Squish::Screen byIndex 0] set geom [$scr geometry] test log [concat "Screen is " [property get $geom width] " by " [property get $geom height]]
This method returns the number of Screen
objects available.
This method returns a Screen
object. The specified
index
must be in the range of 0
till
Screen.count() - 1
.
Read-only property of a Screen
object which is the index of this
Screen
object in the list of all available Screen
objects.
Read-only property of a Screen
object that returns a
ScreenRectangle containing the dimensions of this
Screen
object.
Read-Write property of a Screen
object specifying the orientation
of this Screen
using one of the following 4 properties.
Instead of the following properties it's also possible to use numbers to
specify the orientation, 1 for LandscapeOrientation, 2 for PortraitOrientation,
4 for ReverseLandscapeOrientation and 8 for ReversePortraitOrientation.
![]() | Tcl users |
---|---|
Due to language constraints, these orientation properties start with a lowercase. |
Information about and manipulation of toplevel windows. In order to use this
ToplevelWindow
object, the Squish toplevelwindow
library has to be included in the script file.
source(findFile("scripts", "javascript/toplevelwindow.js")); // ... var win = ToplevelWindow.focused(); var geom = win.geometry; test.log("Focused window is " + geom.width + " by " + geom.height);
use strict; use utf8; use warnings; use Squish::ToplevelWindow; # ... my $win = Squish::ToplevelWindow->focused(); my $geom = $win->geometry; test::log("Focused window is " . $geom->width . " by " . $geom->height);
# -*- coding: utf-8 -*- from toplevelwindow import * # ... win = ToplevelWindow.focused() geom = win.geometry test.log("Focused window is " + str(geom.width) + " by " + str(geom.height))
# encoding: UTF-8 require 'squish' require 'squish/toplevelwindow' # ... win = ToplevelWindow::focused() geom = win.geometry test.log("Focused window is " + geom.width + " by " + geom.height)
package require squish::toplevelwindow # ... set win [Squish::ToplevelWindow focused] set geom [$win geometry] test log "Focused window is [property get $geom width] by [property get $geom height]"
These methods return a ToplevelWindow
object for the given
objectname
or object
. The first
is a convenience method for calling the second, with the result
of waitForObject
. These methods accept different
argument types depending on the toolkit, and should work with most top-level
windows such as Dialogs, Main Windows, and Browser Tabs.
tlw = ToplevelWindow.byName({'type': 'BrowserTab'}) # ... is equivalent to ... tlw = ToplevelWindow.byObject(activeBrowserTab())
This method returns a ToplevelWindow
object for the window
having the keyboard focus. When no window found having the keyboard focus,
an exception is raised.
![]() | Squish for Web specific |
---|---|
To obtain an instance of |
Read-only property of a ToplevelWindow
object that returns a
ScreenRectangle containing the dimensions of
the referenced window.
Read-only property of a ToplevelWindow
object that returns the
object for which this ToplevelWindow
object was created.
This method closes the window referenced by this ToplevelWindow
object.
This method maximizes the window referenced by this ToplevelWindow
object.
This method minimizes the window referenced by this ToplevelWindow
object.
This method moves the client-area (excluding window borders) upper left corner
of the window referenced by this ToplevelWindow
object, to the
given global position.
This method resizes the client-area (excluding window borders) of the window
referenced by this ToplevelWindow
object, to the given
width
and height
.
This method restores the window referenced by this ToplevelWindow
object from fullscreen.
This method sets the keyboard input focus to the window referenced by this
ToplevelWindow
object.
![]() | Windows specific |
---|---|
On Windows, there is a feature called "focus theft protection"
that prevents certain APIs from being able to change the focus from the
active window.
Therefore, |
![]() | Squish for Web specific |
---|---|
This function is not supported for Squish for Web, it will generate an error when being used |
This raises the window referenced by this ToplevelWindow
object.
![]() | Windows specific |
---|---|
On Windows, there is a feature called "foreground lock protection"
that prevents certain APIs from being able to change the foreground window.
Therefore, |
![]() | Squish for Web specific |
---|---|
This function is not supported for Squish for Web, it will generate an error when being used |
This changes the window referenced by this ToplevelWindow
object
to fullscreen, i.e. covering the whole screen without window borders. Use
restore
to undo this operation.
The global squishinfo object provides the following properties.
int squishinfo.majorThis read-only property holds Squish's major version number as a single integer (e.g., 4).
int squishinfo.minorThis read-only property holds Squish's minor version number as a single integer (e.g., 0).
int squishinfo.patchThis read-only property holds Squish's patch level version number as a single integer (e.g., 1).
String squishinfo.resultDirThis read-only property holds the path to the results directory.
—deprecated—String squishinfo.settingsGroupThis read-only property holds the current test's currently active settings group.
String squishinfo.testCaseThis read-only property holds the current test case's path.
String squishinfo.testCaseNameThis read-only property holds the current test case's name.
String squishinfo.testSuiteNameThis read-only property holds the current test suite's name.
int squishinfo.versionThis read-only property holds Squish's complete version number (major/minor/patch/release) as a single integer (see explanation further on).
The squishinfo.version
number is a unique number that
represents the complete Squish version number
(major/minor/patch/release). The number is composed of four bytes by
representing each part as a one-byte hexadecimal number. So
Squish 4.0.1-final would be represented by the number
0x040001FF
where the 0x04
is the major version
(4), the 0x00
the minor version (0), the 0x01
the patch version (1), and the 0xFF
the release (final).
The release is encoded using one of three hexadecimal numbers:
0xAA
is used for “alpha”, 0xBB
for “beta”, and 0xFF
for “final”.
Using a hexadecimal format version number makes it easy to write version-specific code in test scripts. Here's an example where we want some code executed only for Squish 4.0.0-final or later (for example, to take advantage of some Squish 4-specific functionality):
if squishinfo.version >= 0x040000FF: # code meant for Squish version 4.0.0-final or higher
if (squishinfo.version >= 0x040000FF) { // code meant for Squish version 4.0.0-final or higher }
if (squishinfo->version >= 0x040000FF) { # code meant for Squish version 4.0.0-final or higher }
if Squishinfo.version >= 0x040000FF # code meant for Squish version 4.0.0-final or higher end
if {[squishinfo version] >= 0x040000FF} { # code meant for Squish version 4.0.0-final or higher }
This read-only property holds Squish's version number as a human-readable string (e.g., "4.0.1-final").
Squish provides several functions for tests which need interaction with a real user during replay. Such interaction includes simple questions for manual verification as well as providing user-input, i.e. for manually driven testing or for taking notes while observing test execution.
testInteraction
functions that display a message box return one of
the following constant values depending on the button that was pressed by the
user:
testInteraction.Ok
testInteraction.Yes
testInteraction.No
Any testInteraction
function that displays a dialog shows
the current testscript filename and line number in its title bar.
Calling any of these functions only works if squishrunner was started with
the --interactive
option (See also squishrunner --testsuite: Running tests in batch mode (Section 7.4.3.3)). Tests executed from the Squish IDE are
always run in interactive mode. Calling any of the testInteraction
functions (except for testInteraction.isAvailable()
) in
non-interactive mode will result in a script error causing script execution to
abort.
Shows a dialog with message
as message text and a list
of items
to choose from. The returned string contains
the selected item text or an empty string if the user canceled the dialog.
var name = testInteraction.choice("Choose something", ["First", "Second", "Third"]) if (name == "") { test.warning("No item was chosen") } else { test.log(item + " it is!") }
my $item = testInteraction::choice("Choose something", ["First", "Second", "Third"]); if ($item eq "") { test::warning("No item was chosen"); } else { test::log($item." it is!"); }
item = testInteraction.choice("Choose something", ["First", "Second", "Third"]) if not item: test.warning("No item was chosen") else: test.log("{} it is!".format(item))
item = TestInteraction.choice("Choose something", ["First", "Second", "Third"]) if item == "" Test.warning("No item was chosen") else Test.log("#{item} it is!") end
set item [testInteraction choice "Choose something" [list "First" "Second" "Third"]] if {$item == ""} { test warning "No item was chosen" } { test log "$item it is!" }
Shows a message box with message
as message text, an
information icon and an OK button.
testInteraction.information("This is the 'information' function.\nPress 'OK' to continue.")
testInteraction::information("This is the 'information' function.\nPress 'OK' to continue.");
testInteraction.information("This is the 'information' function.\nPress 'OK' to continue.")
TestInteraction.information("This is the 'information' function.\nPress 'OK' to continue.")
testInteraction information "This is the 'information' function.\nPress 'OK' to continue."
Shows a dialog with message
as message text and a line
edit for user input. The optional initialText
sets the
initial text of the line edit. The returned string contains the contents of the
line edit or an empty string if the user canceled the dialog.
name = testInteraction.input("Type in your name and press one of buttons below.") if (name == "") { testInteraction.warning("It's sad you don't want to share your name.") } else { testInteraction.information("Hello " + name + "!") }
$name = testInteraction::input("Type in your name and press one of buttons below."); if ($name eq "") { testInteraction::warning("It's sad you don't want to share your name."); } else { testInteraction::information("Hello $name!"); }
name = testInteraction.input("Type in your name and press one of buttons below.") if name == "": testInteraction.warning("It's sad you don't want to share your name.") else: testInteraction.information("Hello %s!" %name)
name = TestInteraction.input("Type in your name and press one of buttons below.") if name == "" TestInteraction.warning("It's sad you don't want to share your name.") else TestInteraction.information("Hello " + name + "!") end
set name [testInteraction input "Type in your name and press one of buttons below."] if {$name == ""} { testInteraction warning "It's sad you don't want to share your name." } { testInteraction information "Hello $name!" }
This function returns whether the test script is executed by a squishrunner
that was started including the --interactive
option. This
allows creating tests that only show interactive dialogs on request but also
run in a non-interactive way.
Shows a timed non-blocking message box with message
as message text for timeoutSecs
seconds.
If timeoutSecs
is not provided, the message box will be shown for 5 seconds.
timeOut = 2 testInteraction.notification("This is the 'notification' function.\nWait " + timeOut +" seconds for message box to close.", timeOut) //or testInteraction.notification("This is the 'notification' function.\nWait 5 seconds for message box to close.")
$timeOut = 2; testInteraction::notification("This is the 'notification' function.\nWait $timeOut seconds for message box to close.", $timeOut); #or testInteraction::notification("This is the 'notification' function.\nWait 5 seconds for message box to close.");
timeOut = 2 testInteraction.notification("This is the 'notification' function.\nWait %s seconds for message box to close." %timeOut, timeOut) #or testInteraction.notification("This is the 'notification' function.\nWait 5 seconds for message box to close.")
timeOut = "2" TestInteraction.notification("This is the 'notification' function.\nWait "+ timeOut + " seconds for message box to close.", timeOut) #or TestInteraction.notification("This is the 'notification' function.\nWait 5 seconds for message box to close.")
set timeOut 2 testInteraction notification "This is the 'notification' function.\nWait $timeOut seconds for message box to close." $timeOut #or testInteraction notification "This is the 'notification' function.\nWait 5 seconds for message box to close."
Shows a dialog with message
as message text and a line
edit with asterisks instead of the characters actually entered for user input.
The returned string contains the contents of the line edit or an empty string if the user canceled the dialog.
passwd = testInteraction.password("Type 'P@ssw0rd' without quotes to reveal secret information.") if (passwd == "P@ssw0rd") { testInteraction.information("The secret information is: The Cake is a Lie!") } else { testInteraction.warning("Wrong password. It seems the secret will remain hidden.") }
$passwd = testInteraction::password("Type 'Passw0rd' without quotes to reveal secret information."); if ($passwd eq "Passw0rd") { testInteraction::information("The secret information is: The Cake is a Lie!"); } else { testInteraction::warning("Wrong password. It seems the secret will remain hidden."); }
passwd = testInteraction.password("Type 'P@ssw0rd' without quotes to reveal secret information.") if passwd == "P@ssw0rd": testInteraction.information("The secret information is: The Cake is a Lie!") else: testInteraction.warning("Wrong password. It seems the secret will remain hidden.")
passwd = TestInteraction.password("Type 'P@ssw0rd' without quotes to reveal secret information.") if passwd == "P@ssw0rd" TestInteraction.information("The secret information is: The Cake is a Lie!") else TestInteraction.warning("Wrong password. It seems the secret will remain hidden.") end
set passwd [testInteraction password "Type 'P@ssw0rd' without quotes to reveal secret information."] if {$passwd == "P@ssw0rd"} { testInteraction information "The secret information is: The Cake is a Lie!" } { testInteraction warning "Wrong password. It seems the secret will remain hidden." }
Shows a message box with message
as message text, a
questionmark-icon, a Yes button and a
No button.
questionResult = testInteraction.question("Do you wish to continue?") if (questionResult == testInteraction.Yes) { testInteraction.information("Button 'Yes' was pressed.") } else { testInteraction.information("Button 'No' was pressed.") }
$questionResult = testInteraction::question("Do you wish to continue?"); if ($questionResult == testInteraction::Yes) { testInteraction::information("Button 'Yes' was pressed."); } else { testInteraction::information("Button 'No' was pressed."); }
questionResult = testInteraction.question("Do you wish to continue?") if questionResult == testInteraction.Yes: testInteraction.information("Button 'Yes' was pressed.") else: testInteraction.information("Button 'No' was pressed.")
questionResult = TestInteraction.question("Do you wish to continue?") if questionResult == TestInteraction::YES TestInteraction.information("Button 'Yes' was pressed.") else TestInteraction.information("Button 'No' was pressed.") end
set questionResult [testInteraction question "Do you wish to continue?"] if {$questionResult == [testInteraction Yes] } { testInteraction information "Button 'Yes' was pressed." } { testInteraction information "Button 'No' was pressed." }
Shows a timed non-blocking dialog that contains the image
, a message
message text, and a OK
button. If timeoutSecs
is not provided, the dialog will
be shown for 5 seconds.
var img = grabDesktopScreenshot(); testInteraction.showImage(img, "Current desktop", 2);
my $img = grabDesktopScreenshot(); testInteraction::showImage($img, "Current desktop", 2);
img = grabDesktopScreenshot() testInteraction.showImage(img, "Current desktop", 2)
img = grabDesktopScreenshot(); TestInteraction.showImage(img, "Current desktop", 2)
set img [grabDesktopScreenshot] testInteraction showImage $img, "Current desktop", 2
Shows a message box with message
as message text, a
warning-icon and an OK button.
testInteraction.warning("This is the 'warning' function.\nPress 'OK' to continue.")
testInteraction::warning("This is the 'warning' function.\nPress 'OK' to continue.");
testInteraction.warning("This is the 'warning' function.\nPress 'OK' to continue.")
TestInteraction.warning("This is the 'warning' function.\nPress 'OK' to continue.")
testInteraction warning "This is the 'warning' function.\nPress 'OK' to continue."
Table of Contents
Squish provides a global testSettings
object whose
properties and methods can be set to control certain aspects of test
execution.
This function returns the list of wrappers associated with the specified
application
. (See also testSettings.setWrappersForApplication
.)
If this property is true every test failure will cause Squish to take a screenshot of the desktop when the failure occurred; by default this property is false and screenshots of failures are not automatically taken
For example, let's assume that we occasionally experience test failures when verifying the state of a specific widget in our nightly tests. We cannot explain the cause of the problem but suspect that the overall state of our application's GUI is broken due to as yet unknown external factors. To provide the developers with useful information via a visual inspection we enable automatic screenshot capturing—but for only for the test that is causing concern:
testSettings.logScreenshotOnFail = True # ... perform test ... testSettings.logScreenshotOnFail = False
testSettings.logScreenshotOnFail = true; // ... perform test ... testSettings.logScreenshotOnFail = false;
testSettings->logScreenshotOnFail(1); # ... perform test ... testSettings->logScreenshotOnFail(0);
TestSettings.logScreenshotOnFail = true # ... perform test ... TestSettings.logScreenshotOnFail = false
testSettings set logScreenshotOnFail 1 # ... perform test ... testSettings set logScreenshotOnFail 0
If this property is true every test error will cause Squish to take a screenshot of the desktop when the error occurred; by default this property is false and screenshots of errors are not automatically taken
bool testSettings.logScreenshotOnPassIf this property is true every test pass will cause Squish to take a screenshot of the desktop. By default this property is false and this screenshots are not automatically taken for test passes.
bool testSettings.logStacktraceOnLogIf this property is true every test log will have a stacktrace attached in test reports that support stacktrace information. By default this property is false.
bool testSettings.logStacktraceOnPassIf this property is true every test pass will have a stacktrace attached in test reports that support stacktrace information. By default this property is false.
bool testSettings.objectNotFoundDebuggingIf this property is false the object not found debug dialog will not open if an object can not be located or is not ready. By default this property is true and the object not found dialog will open, whenever an object can not be located or is not ready in time.
Some algorithms require to determine if an object is ready or not, without triggering the object not found dialog. In script sections that would normally trigger unwanted object not found dialogs, you can use the objectNotFoundDebugging property to temporarily deactivate the dialog:
testSettings.objectNotFoundDebugging = False # ... wait for object that might not exist or get ready in time ... testSettings.objectNotFoundDebugging = True
testSettings.objectNotFoundDebugging = false; // ... wait for object that might not exist or get ready in time ... testSettings.objectNotFoundDebugging = true;
testSettings->objectNotFoundDebugging(0); # ... wait for object that might not exist or get ready in time ... testSettings->objectNotFoundDebugging(1);
TestSettings.objectNotFoundDebugging = false # ... wait for object that might not exist or get ready in time ... TestSettings.objectNotFoundDebugging = true
testSettings set objectNotFoundDebugging 0 # ... wait for object that might not exist or get ready in time ... testSettings set objectNotFoundDebugging 1
![]() | Object Not Found debugging |
---|---|
The Object Not Found dialog (Section 8.3.14) will not be shown if the Halt Test Execution in case of 'Object not found' issues is disabled on the Playback Squish pane (Section 8.3.17.7) in the IDE preferences. |
If this property is false the image not found debug dialog will not open if an template image can not be located. By default this property is true and the image not found dialog will open, whenever a template image can not be located in time.
Some algorithms require image search without triggering the image not found dialog. In script sections that would normally trigger unwanted image not found dialogs, you can use the imageNotFoundDebugging property to temporarily deactivate the dialog:
testSettings.imageNotFoundDebugging = False # ... wait for image that might not exist in time ... testSettings.imageNotFoundDebugging = True
testSettings.imageNotFoundDebugging = false; // ... wait for image that might not exist in time ... testSettings.imageNotFoundDebugging = true;
testSettings->imageNotFoundDebugging(0); # ... wait for image that might not exist in time ... testSettings->imageNotFoundDebugging(1);
TestSettings.imageNotFoundDebugging = false # ... wait for image that might not exist in time ... TestSettings.imageNotFoundDebugging = true
testSettings set imageNotFoundDebugging 0 # ... wait for image that might not exist in time ... testSettings set imageNotFoundDebugging 1
![]() | Image Not Found debugging |
---|---|
The Image Not Found dialog (Section 8.3.4) will not be shown if the Halt Test Execution in case of 'Image not found' issues is disabled on the Playback Squish pane (Section 8.3.17.7) in the IDE preferences. |
If this property is false the text not found debug dialog will not open if a search text can not be located. By default this property is true and the text not found dialog will open, whenever a search text can not be located in time.
Some algorithms require text search without triggering the text not found dialog. In script sections that would normally trigger unwanted text not found dialogs, you can use the textNotFoundDebugging property to temporarily deactivate the dialog:
testSettings.textNotFoundDebugging = False # ... wait for text that might not exist in time ... testSettings.textNotFoundDebugging = True
testSettings.textNotFoundDebugging = false; // ... wait for text that might not exist in time ... testSettings.textNotFoundDebugging = true;
testSettings->textNotFoundDebugging(0); # ... wait for text that might not exist in time ... testSettings->textNotFoundDebugging(1);
TestSettings.textNotFoundDebugging = false # ... wait for text that might not exist in time ... TestSettings.textNotFoundDebugging = true
testSettings set textNotFoundDebugging 0 # ... wait for text that might not exist in time ... testSettings set textNotFoundDebugging 1
![]() | Text Not Found debugging |
---|---|
The Text Not Found dialog (Section 8.3.5) will not be shown if the Halt Test Execution in case of 'Text not found' issues is disabled on the Playback Squish pane (Section 8.3.17.7) in the IDE preferences. |
This function associates a list of wrappers with the specified
application
. The list must include
at least one of the main toolkit wrappers. Optionally, it may include
application-specific wrappers (for those Squish editions that support them). The
main toolkit wrappers are:
|
|
|
These main toolkit wrapper names correspond directly to the Toolkit: field in the Test Suite Configuration view of the Squish IDE.
Note that Squish 4's dynamic wrapper support greatly reduces the need to create and maintain application-specific wrappers.
Here is an example that sets the Qt toolkit wrapper as well as a custom application wrapper, and then starts the AUT:
testSettings.setWrappersForApplication("MyApp", ("Qt", "CanvasWrapper")) startApplication("MyApp")
testSettings.setWrappersForApplication("MyApp", ["Qt", "CanvasWrapper"]); startApplication("MyApp");
testSettings->setWrappersForApplication("MyApp", ("Qt", "CanvasWrapper")); startApplication("MyApp");
TestSettings.setWrappersForApplication("MyApp", ["Qt", "CanvasWrapper"]) startApplication("MyApp")
testSettings setWrappersForApplication MyApp { Qt CanvasWrapper } startApplication "MyApp"
(See also testSettings.getWrappersForApplication
.)
If this property is true Squish will not produce Test Result entries
for passing or failing test.vp
, test.xvp
and test.vpWithObject
calls. In combination with
using the (boolean) return value of test.vp() and test.vpWithObject(),
this can come in handy for custom defined verifications on top of a
series of Verification Points.
Here is an example that checks that one of three Screenshot Verification Points passes.
testSettings.silentVerifications = True for current in ['VP-winxp', 'VP-win2k', 'VP-win7']: if test.vp(current): test.passes("%s matched" % (current, )) break else: test.fail("none of the provided VPs matched")
If this property is true
, the debugger stops on every failed verification performed by
test.compare
, test.xcompare
,
test.verify
, test.xverify
,
test.vp
, test.xvp
,
test.vpWithObject
and test.exception
as well as every invocation of test.fail
and
test.fatal
.
By default, this property is false
.
If this property is true every failing verification performed by
test.compare
, test.xcompare
,
test.verify
, test.xverify
,
test.vp
, test.xvp
,
test.vpWithObject
and test.exception
as well as every invocation of test.fail
and
test.fatal
will raise a script error.
By default, this property is false and the aforementioned functions do not raise script errors.
This property affects the test.vp
,
test.xvp
and the test.vpWithObject
functions.
It can be used to specify for how long a verification should be retried after it fails.
The default value is 0, which means the verification is only tried once.
If you set it to 5000 the verification will be retried for at least 5000ms
if it keeps on failing (i.e. it will be retried until it passes or
5 seconds have passed). This can be useful if the AUT needs to reach a certain
stage before a property or screenshot verification can pass. This can help
to reduce timing issues.
![]() | Result logging |
---|---|
Please note that intermediate failures are not logged. Only the last result in the series is logged. This can either be a fail when the retry duration is reached and the verification is still failing or a pass. |
The following example shows how you can set this property for each verification individually, but you could also set it once for every verification that follows.
testSettings.retryDuration = 5000 test.vp("VP1") testSettings.retryDuration = 0
testSettings.retryDuration = 5000; test.vp("VP1") testSettings.retryDuration = 0;
testSettings->retryDuration(5000); test::vp("VP1") testSettings->retryDuration(0);
TestSettings.retryDuration = 5000 Test.vp("VP1") TestSettings.retryDuration = 0
testSettings set retryDuration 5000 test vp "VP1" testSettings set retryDuration 0
This property affects the findImage
,
waitForImage
and
test.imagePresent
functions. In case the
option map passed to the above functions does not contain the
tolerant
key, the value of this property is
used in its place. The default value is false
.
This property affects the findImage
,
waitForImage
and
test.imagePresent
functions. In case the
option map passed to the above functions does not contain the
threshold
key, the value of this property is
used in its place. The default value is 99.5
.
This property affects the findImage
,
waitForImage
and
test.imagePresent
functions. In case the
option map passed to the above functions does not contain the
multiscale
key, the value of this property is
used in its place. The default value is false
.
This property affects the findImage
,
waitForImage
and
test.imagePresent
functions. In case the
option map passed to the above functions does not contain the
minScale
key, the value of this property is
used in its place. The default value is 50.0
.
This property affects the findImage
,
waitForImage
and
test.imagePresent
functions. In case the
option map passed to the above functions does not contain the
maxScale
key, the value of this property is
used in its place. The default value is 200.0
.
This property affects the OCR functions like
getOcrText
,
findOcrText
,
waitForOcrText
and
test.ocrTextPresent
. In case the option
map passed to the above functions does not contain the
language
key, the value of this property is
used in its place. The default value is empty which means the engine's
default language.
This property defines the default timeout in milliseconds waitForObject
,
waitForObjectItem
and waitForObjectExists
will wait for an object lookup to succeed. This timeout also applies to
test.vp
, test.xvp
,
test.vpWithObject
and highlightObject
.
The timeout value of 0 means Squish will try to find the object exactly once. Negative timeout values are not supported.
This method retrieves the password associated with the specified
key
. The passwords are stored with the test suite and can
be edited using the Password Information (Section 8.2.16.6).
![]() | Note |
---|---|
The passwords stored in a Squish test suite have to be retrievable in plaintext form. Therefore, they are not stored in a "secure" way - they are just stored separately, so that it is not necessary to hard-code passwords in your test scripts. |
The initial values of the testSettings
Object properties can be set by editing the
config.xml
in the test suite folder. This way you can
easily set the same values for multiple test cases. The test settings
in the config.xml
can be edited using the
Test Settings (Section 8.2.16.4) and
Image Search (Section 8.2.16.5) pages of the test
suite settings editor in the Squish IDE.
The following example shows how to extend the config.xml
manually. Every property can be set in the same way.
<testconfig version="1.0"> ... <testsettings> <objectNotFoundDebugging>false</objectNotFoundDebugging> <testCaseName>some name</testCaseName> </testsettings> ... </testconfig>
The test suite's config.xml
file is not always
created automatically. You can either create it manually with a text
editor, or in the Squish IDE by opening the
Test Suite Settings view (Section 8.2.16) editor and editing either the
test suite summary and description or the default test settings.
![]() | Usability notes |
---|---|
The |
Squish provides a RemoteSystem
object whose
methods can be used for file system operations and process execution on the
system the squishserver is running on.
In order to use the object, the RemoteSystem
library has to be
included and an object instance must be created.
When the object instance is created by the default constructor, a connection to the default squishserver is automatically established. If an error occurs and the connection cannot be established, an exception is raised and no object instance is created.
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remotesys = new RemoteSystem(); } catch (e) { test.fail("Connect to squishserver", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; eval { my $con = Squish::RemoteSystem->new(); 1; } or do { my $e = $@; test::fail("Connect to squishserver", $e); };
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remotesys = RemoteSystem() except Exception as e: test.fail("Connect to squishserver", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remotecon = RemoteSystem.new() rescue Exception => e Test.fail("Connect to squishserver", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remotesys [::Squish::RemoteSystem new]} result]} { test fail "Connect to squishserver" $result } }
RemoteSystem RemoteSystem(
host, port)
;
The constructor of the RemoteSystem
object takes two optional arguments
that can be used to establish a connection to an arbitrary squishserver. The first
parameter is the hostname or IP address, the second parameter is the port number.
The following example creates a RemoteSystem
object that is connected
to a manually started squishserver on the local system.
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remotesys = new RemoteSystem("localhost", 4322); } catch (e) { test.fail("Connect to squishserver", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; eval { my $con = Squish::RemoteSystem->new("localhost", 4322); 1; } or do { my $e = $@; test::fail("Connect to squishserver", $e); };
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remotesys = RemoteSystem("localhost", 4322) except Exception as e: test.fail("Connect to squishserver", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remotecon = RemoteSystem.new("localhost", 4322) rescue Exception => e Test.fail("Connect to squishserver", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remotesys [::Squish::RemoteSystem new localhost 4322]} result]} { test fail "Connect to squishserver" $result } }
The following exceptions can occur when the constructor of the object is called.
Exception | Description |
---|---|
Runtime Error | When a connection cannot be established. |
Type/Value/Argument Error (JavaScript/Python/Ruby) | When a parameter is missing. |
![]() | Perl/Tcl-specific |
---|---|
The exceptions for this languages don`t have a specific exception type. Only a message, describing the error, is given. |
Once the RemoteSystem
object is created the following methods
are available.
|
list RemoteSystem.execute(
cmd, cwd)
;
list RemoteSystem.execute(
cmd, cwd, env)
;
list RemoteSystem.execute(
cmd, cwd, env, options)
;
The execute method can be used to run an application or shell command. As the first parameter a list/array of the command and all parameters must be given. The three following parameters are optional.
The cwd
parameter specifies the working directory for executing the provided command.
The env
parameter allows to set or remove environment variables. To remove an environment variable use an empty string as value.
The options
parameter offers additional, sometimes less often used options. Please find the supported options for this below.
![]() | RemoteSystem.execute is a synchronous operation |
---|---|
RemoteSystem.execute returns only when the executed command is finished or the process is started as a background task. When the process is started as a background task there no longer is an association to the RemoteSystem object. |
The following table lists all possible options.
Parameter | Type | Default | Description |
---|---|---|---|
cmd | List/Array | Mandatory | Array with command to execute and parameters. |
cwd | String | Empty | Working directory for the started process. |
env | Dictionary | Empty | Key/Value pairs of environment variables. |
options | Dictionary | Empty | Dictionary of all options. |
options.keepLineEnding | Boolean | True | If provided and set to false, line endings in stdout/stderr output of the started process will be converted to '\n' (Unix) newlines. |
options.clearenv | Boolean | False | If provided and set to true, the process will be started with a minimal environment. However, on most OS it is not possible to remove all environment variables because then some functionality or tools provided by the operating system would not work any more. |
options.timeout | Integer | 30 | Value is a timeout in seconds. It is used to limit the execution time of the started process. |
options.encoding | String | UTF-8 | Name of the encoding of the stdout/stderr output of the started process. See below for a list of supported encodings. |
The following table lists the return values. The returned value is a simple list/array with three elements. The order is always the same.
Name | Type | Description |
---|---|---|
exitcode | String/Unicode | Exit code of the process. |
stdout | String/Unicode | Stdout output of the process. |
stderr | String/Unicode | Stderr output of the process. |
![]() | JavaScript |
---|---|
The return value in JavaScript is an object with properties. |
Example for each language. The example adds one environment variable, deletes one and then gets the environment variable list from windows. The maximum run time for the command is 10 seconds, for the encoding the Windows IBM850 codepage is used. Also the line endings are transformed to "\n" line endings.
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remotesys = new RemoteSystem(); cmd = ["cmd", "/c", "set"]; cwd = ""; env = {}; env["MYTESTENV"] = "test string"; env["COMPUTERNAME"] = ""; options = {}; options.keepLineEnding = false; options.clearenv = false; options.timeout = 10; options.encoding = "IBM850" execresult = remotesys.execute(cmd, cwd, env, options); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; my $cmd = ["cmd", "/c", "set"]; my $cwd = ""; my $env = { "MYTESTENV" => "test string", "COMPUTERNAME" => "" }; my $options = { "keepLineEnding" => 0, "clearenv" => 0, "timeout" => 10, "encoding" => "IBM850" }; eval { my $remotecon = Squish::RemoteSystem->new(); my ($exitcode,$stdout,$stderr) = $remotecon->execute($cmd, $cwd, $env, $options); 1; } or do { test::fail("RemoteSystem error", $@); };
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remotesys = RemoteSystem() cmd = [ "cmd", "/c", "set" ] cwd = "" env = { "MYTESTENV": "test string", "COMPUTERNAME": "" } options = { "keepLineEnding": False, "clearenv": False, "timeout": 10, "encoding": "IBM850" } (exitcode, stdout, stderr) = remotesys.execute(cmd, cwd, env, options) test.verify(exitcode == "0", "Command not executed") except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remotesys = RemoteSystem.new() cmd = ["cmd", "/c", "set"] cwd = "" env = { "MYTESTENV" => "test string", "COMPUTERNAME" => "" } options = { "keepLineEnding" => false, "clearenv" => false, "timeout" => 10, "encoding" => "IBM850" } exitcode, stdout, stderr = remotesys.execute(cmd, cwd, env, options) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { set cmd [list cmd /c set] set cwd "" set env [dict create] set options [dict create keepNewLine 0 clearenv 0 timeout 10 encoding IBM850] if {[catch {set remotesys [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch {foreach {exitcode stdout stderr} [$remotesys execute $cmd $cwd $env $options] {break}} result] } { test fail "RemoteSystem error" $result } }
![]() | Encoding and Windows codepages |
---|---|
When the command is executed on windows and runs in a console window, the encoding must match the codepage of the console that is used. See https://msdn.microsoft.com/de-de/library/windows/desktop/dd317756(v=vs.85).aspx for windows codepage numbers and there names. The name of the codepage is the name for the encoding option. |
![]() | Encoding under Linux |
---|---|
Linux encoding is mostly UTF-8. |
The following list is a sub set of possible encodings.
UTF-8 | UTF-16 | ISO 8859-1 to 10 |
ISO 8859-13 to 16 | ISO 2022-JP | Shift-JIS |
IBM 874 | IBM 866 | IBM 850 |
Windows-1250 to 1258 | Big5 | KOI8-R |
![]() | More encodings |
---|---|
Complete list of supported encodings. https://doc.qt.io/qt-4.8/qtextcodec.html#details |
The following exception can occur when a command is executed.
Exception | Description |
---|---|
Runtime Error | Encoding not supported. The exception is raised when the wanted encoding is not supported. |
Runtime Error | Working directory not found. The exception is raised when the working directory is not found. |
Runtime Error | Program not started after timeout. The exception is raised when the program to execute does not start within 10 seconds. |
The getEnvironmentVariable
method can be used to retrieve the content of environment variables from the remote system.
The variableName
parameter is used to specify the name of the environment variable on the remote system.
![]() | RemoteSystem.getEnvironmentVariable error handling |
---|---|
If the retrieved environment variable is not set on the remote system the function will return an empty string. There is no way to differentiate if the variable is set to an empty string or not set at all. |
The following example retrieves the environment variable HOMEDRIVE and logs the result.
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.log(remoteOS.getEnvironmentVariable("HOMEDRIVE")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::log($remoteOS->getEnvironmentVariable("HOMEDRIVE")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.log(remoteOS.getEnvironmentVariable("HOMEDRIVE")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.log(remoteOS.getEnvironmentVariable("HOMEDRIVE")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test log [$remoteOS getEnvironmentVariable "HOMEDRIVE"] } result] } { test fail "RemoteSystem error" $result } }
The getOSName
method can be used to retrieve the name of the operating system of the remote system.
When the OS can not be determined the function returns "Unknown".
Possible names include:
"Android"
— Android
"Darwin"
— macOS and iOS
"Linux"
— Linux
"QNX"
— QNX
"SunOS"
— Solaris
"Windows"
— Windows
The following example retrieves the name of the operating system and logs the result.
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.log(remoteOS.getOSName()); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::log($remoteOS->getOSName()); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.log(remoteOS.getOSName()) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.log(remoteOS.getOSName()) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } else { test log [$remoteOS getOSName] } }
The listFiles
method can be used to retrieve a directory listing of a certain path from the remote system.
The path
parameter is used to specify the path on the remote system that is retrieved. This method returns
a list of file and folder names (it does not return the full paths). It does not work recursively and therefore doesn't show the
content of subfolders. If the path does not exist or is not a directory an exception is raised.
The following example retrieves all directory and file names of the "/"-Directory (which under Windows should be the homedrive).
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); dirList = remoteOS.listFiles("/"); for (var i = 0; i < dirList.length; i++) { test.log(dirList[i]); } } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); my @dirList = $remoteOS->listFiles("/"); my $dirListLength = @dirList; for (my $i = 0; $i < $dirListLength; $i++) { test::log($dirList[$i]); } 1; } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() dirList = remoteOS.listFiles("/") for remoteFile in dirList: test.log(remoteFile) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() dirList = remoteOS.listFiles("/") dirList.each do |remoteFile| Test.log remoteFile end rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { set dirList [$remoteOS listFiles "/"]] } result] } { test fail "RemoteSystem error" $result } if { [catch { foreach remoteFile $dirList { test log $remoteFile } } result ] } { test fail "RemoteSystem error" $result } }
The stat
method can be used to retrieve different properties of a certain path from the remote system.
The path
parameter is used to specify the path on the remote system and the propertyName
is used to specify which property should be retrieved. The property name must be chosen from a predefined list
of property names (property names are case-sensitive). Depending on the property this method returns different result types.
If the path does not exist or the property is unknown an exception is raised.
The following list shows the supported properties and the returned types.
Property Name | Return Type |
---|---|
exists | Boolean |
isDir | Boolean |
isFile | Boolean |
isSymLink | Boolean |
isReadable | Boolean |
isWritable | Boolean |
isExecutable | Boolean |
isHidden | Boolean |
lastModified | Timestamp |
lastRead | Timestamp |
size | Integer |
The following example prints if the given path is a directory or file. And prints the timestamp when the directory was last read.
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.log(remoteOS.stat("/", "isDir")); test.log(remoteOS.stat("/", "isFile")); test.log(remoteOS.stat("/", "lastRead")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::log($remoteOS->stat("/", "isDir")); test::log($remoteOS->stat("/", "isFile")); test::log($remoteOS->stat("/", "lastRead")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.log(str(remoteOS.stat("/", "isDir"))) test.log(str(remoteOS.stat("/", "isFile"))) test.log(remoteOS.stat("/", "lastRead")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.log(remoteOS.stat("/", "isDir")? "true" : "false") Test.log(remoteOS.stat("/", "isFile")? "true" : "false" ) Test.log(remoteOS.stat("/", "lastRead")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test log [$remoteOS stat "/" "isDir" ] } result] } { test fail "RemoteSystem error" $result } if { [catch { test log [$remoteOS stat "/" "isFile" ] } result] } { test fail "RemoteSystem error" $result } if { [catch { test log [$remoteOS stat "/" "lastRead" ] } result] } { test fail "RemoteSystem error" $result } }
The exists
method can be used to check if a certain path on the remote system exists.
The path
parameter is used to specify the path on the remote system that will be checked.
The following example prints if the two given paths exists.
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.log(remoteOS.exists("/")); test.log(remoteOS.exists("/some/nonexisting/path")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::log($remoteOS->exists("/")); test::log($remoteOS->exists("/some/nonexisting/path")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.log(str(remoteOS.exists("/"))) test.log(str(remoteOS.exists("/some/nonexisting/path"))) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.log(remoteOS.exists("/")? "true" : "false") Test.log(remoteOS.exists("/some/nonexisting/path")? "true" : "false") rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test log [$remoteOS exists "/"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test log [expr ![$remoteOS exists "/some/nonexisting/path"]] } result] } { test fail "RemoteSystem error" $result } }
The deleteFile
method can be used to delete a file on the remote system.
The path
parameter is used to specify the path of the file on the remote system.
If the provided file cannot be deleted or the path doesn't lead to a file an exception is raised.
The following example shows how to use the deleteFile method. You will have to replace the path if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.deleteFile("/some/nonexisting/filepath")); test.verify(!remoteOS.exists("/some/nonexisting/filepath")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->deleteFile("/some/nonexisting/filepath")); test::verify(!$remoteOS->exists("/some/nonexisting/filepath")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.deleteFile("/some/nonexisting/filepath")) test.verify(!remoteOS.exists("/some/nonexisting/filepath")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.deleteFile("/some/nonexisting/filepath")) Test.verify(!remoteOS.exists("/some/nonexisting/filepath")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS deleteFile "/some/nonexisting/filepath"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [expr ![$remoteOS exists "/some/nonexisting/filepath"]] } result] } { test fail "RemoteSystem error" $result } }
Boolean RemoteSystem.deleteDirectory(
path, recursive)
;
The deleteDirectory
method can be used to delete a directory on the remote system.
The path
parameter is used to specify the path of the folder on the remote system.
The optional boolean parameter recursive
can be used to specify whether subdirectories
and files inside the directories should be deleted too. If the recursive
flag is not set and the
specified directory contains files or folders the deletion operation will fail and an exception will be raised.
Additionally if some of the specified files and folders cannot be deleted an exception will be raised.
The following example shows how to use the deleteDirectory method. You will have to replace the path if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.deleteDirectory("/some/nonexisting/path")); test.verify(!remoteOS.exists("/some/nonexisting/path")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->deleteDirectory("/some/nonexisting/path")); test::verify(!$remoteOS->exists("/some/nonexisting/path")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.deleteDirectory("/some/nonexisting/path")) test.verify(!remoteOS.exists("/some/nonexisting/path")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.deleteDirectory("/some/nonexisting/path")) Test.verify(!remoteOS.exists("/some/nonexisting/path")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS deleteDirectory "/some/nonexisting/path"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [expr ![$remoteOS exists "/some/nonexisting/path"]] } result] } { test fail "RemoteSystem error" $result } }
The createDirectory
method can be used to create a directory on the remote system.
The path
parameter is used to specify the path of the folder on the remote system.
This method will only create the new folder if the parent directory already exists. If you want
to create multiple directories in one go you can use createPath RemoteSystem.createPath
.
If the folder cannot be created an exception will be raised.
The following example shows how to use the createDirectory method. You will have to replace the path if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.createDirectory("/some/nonexisting/path")); test.verify(remoteOS.exists("/some/nonexisting/path")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->createDirectory("/some/nonexisting/path")); test::verify($remoteOS->exists("/some/nonexisting/path")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.createDirectory("/some/nonexisting/path")) test.verify(remoteOS.exists("/some/nonexisting/path")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.createDirectory("/some/nonexisting/path")) Test.verify(remoteOS.exists("/some/nonexisting/path")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS createDirectory "/some/nonexisting/path"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS exists "/some/nonexisting/path"] } result] } { test fail "RemoteSystem error" $result } }
The createPath
method can be used to create directories on the remote system.
The path
parameter is used to specify the path of the directories on the remote system.
This method will create all folders that are missing on the remote system from the specified path.
If the path cannot be created an exception will be raised.
The following example shows how to use the createPath method. You will have to replace the path if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.createPath("/some/nonexisting/path")); test.verify(remoteOS.exists("/some/nonexisting/path")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->createPath("/some/nonexisting/path")); test::verify($remoteOS->exists("/some/nonexisting/path")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.createPath("/some/nonexisting/path")) test.verify(remoteOS.exists("/some/nonexisting/path")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.createPath("/some/nonexisting/path")) Test.verify(remoteOS.exists("/some/nonexisting/path")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS createPath "/some/nonexisting/path"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS exists "/some/nonexisting/path"] } result] } { test fail "RemoteSystem error" $result } }
The rename
method can be used to rename and move files and directories on the remote system.
The oldPath
parameter is used to specify the old or current path of the directory or file on the remote system.
The newPath
parameter is used to specify the new or desired path of the directory or file on the remote system.
The operation will fail if the new path is already existing. If the old path doesn't exist or the file
or folder cannot be renamed an exception will be raised.
The following example shows how to use the rename method. You will have to replace the paths if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.rename("/some/old/path", "/some/new/path")); test.verify(remoteOS.exists("/some/new/path")); test.verify(!remoteOS.exists("/some/old/path")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->rename("/some/old/path", "/some/new/path")); test::verify($remoteOS->exists("/some/new/path")); test::verify(!$remoteOS->exists("/some/old/path")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.rename("/some/old/path", "/some/new/path")) test.verify(remoteOS.exists("/some/new/path")) test.verify(!remoteOS.exists("/some/old/path")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.rename("/some/old/path", "/some/new/path")) Test.verify(remoteOS.exists("/some/new/path")) Test.verify(!remoteOS.exists("/some/old/path")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS rename "/some/old/path" "/some/new/path"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS exists "/some/new/path"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [expr ![$remoteOS exists "/some/old/path"]] } result] } { test fail "RemoteSystem error" $result } }
Boolean RemoteSystem.createTextFile(
path, content, encoding)
;
The createTextFile
method can be used to create a text file on the remote system.
The path
parameter is used to specify the path and name of the file that is to be created on the remote system.
The content
parameter is used to specify the content of the file that is created as a string.
The optional parameter encoding
can be used to specify the encoding of the text file. The default
encoding is UTF-8, see above for a list of possible encodings.
This operation will fail if the supplied path already exists (so this function will not overwrite existing files).
If the file already exists, the encoding is not supported or the file cannot be created an exception will be raised.
The following example shows how to use the createTextFile method. You will have to replace the path if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.createTextFile("/some/path/to/a/textfile", "Content...")); test.verify(remoteOS.exists("/some/path/to/a/textfile")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->createTextFile("/some/path/to/a/textfile", "Content...")); test::verify($remoteOS->exists("/some/path/to/a/textfile")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.createTextFile("/some/path/to/a/textfile", "Content...")) test.verify(remoteOS.exists("/some/path/to/a/textfile")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.createTextFile("/some/path/to/a/textfile", "Content...")) Test.verify(remoteOS.exists("/some/path/to/a/textfile")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS createTextFile "/some/path/to/a/textfile" "Content..."] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS exists "/some/path/to/a/textfile"] } result] } { test fail "RemoteSystem error" $result } }
The upload
method can be used to upload a file from the local system (i.e. the system the runner is running on)
to the remote system (i.e. the system the server is running on).
The localPath
parameter is used to specify the path of the source file on the local system, while the
remotePath
parameter is used to specify the path of the target location for the file on the remote system.
This operation will fail if the supplied remote path already exists (so this function will not overwrite existing files).
Additionally if the local path does not exist or the file is not transferred correctly an exception will be raised.
The following example shows how to use the upload method. You will have to replace the paths if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.upload("/some/local/path", "/some/remote/path")); test.verify(remoteOS.exists("/some/remote/path")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->upload("/some/local/path", "/some/remote/path")); test::verify($remoteOS->exists("/some/remote/path")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.upload("/some/local/path", "/some/remote/path")) test.verify(remoteOS.exists("/some/remote/path")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.upload("/some/local/path", "/some/remote/path")) Test.verify(remoteOS.exists("/some/remote/path")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS upload "/some/local/path" "/some/remote/path"] } result] } { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS exists "/some/remote/path"] } result] } { test fail "RemoteSystem error" $result } }
The download
method can be used to download a file from the remote system (i.e. the system the server is running on)
to the local system (i.e. the system the runner is running on).
The remotePath
parameter is used to specify the path of the source file on the remote system, while the
localPath
parameter is used to specify the path of the target location for the file on the local system.
This operation will fail if the supplied local path already exists (so this function will not overwrite existing files).
Additionally if the remote path does not exist, the local file cannot be created or the file is not transferred correctly
an exception will be raised.
The following example shows how to use the download method. You will have to replace the paths if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.download("/some/remote/path", "/some/local/path")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->download("/some/remote/path", "/some/local/path")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.download("/some/remote/path", "/some/local/path")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.download("/some/remote/path", "/some/local/path")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS download "/some/remote/path" "/some/local/path"] } result] } { test fail "RemoteSystem error" $result } }
The copy
method can be used to copy files or folders inside the remote system.
The sourcePath
parameter is used to specify the path of the source file or folder on the remote system, while the
destinationPath
parameter is used to specify the path of the destination location for the file or folder on the remote system.
If you copy a single file the destination path can either be a file or folder. If you copy a folder the destination path has to be a folder,
otherwise an exception will be raised. This operation will fail if one of the files involved in a copy operation already exists in the
destination location (it will not overwrite existing files). Additionally if any of the files involved cannot be copied correctly
an exception will be raised.
The following example shows how to use the copy method. You will have to replace the paths if you want to try the example.
![]() | Important |
---|---|
Depending on your setup this test might alter files or folders on your local or remote system. |
source(findFile('scripts', 'javascript/remotesystem.js')); function main() { try { remoteOS = new RemoteSystem(); test.verify(remoteOS.copy("/some/remote/path/a", "/some/remote/path/b")); } catch (e) { test.fail("RemoteSystem error", e.toString()); }; }
use warnings; use strict; use Squish::RemoteSystem; sub main { eval { my $remoteOS = Squish::RemoteSystem->new(); test::verify($remoteOS->copy("/some/remote/path/a", "/some/remote/path/b")); } or do { test::fail("RemoteSystem error", $@); }; }
# -*- coding: utf-8 -*- from remotesystem import RemoteSystem def main(): try: remoteOS = RemoteSystem() test.verify(remoteOS.copy("/some/remote/path/a", "/some/remote/path/b")) except Exception as e: test.fail("RemoteSystem error", str(e))
# encoding: UTF-8 require 'squish' require "squish/remotesystem" include Squish def main begin remoteOS = RemoteSystem.new() Test.verify(remoteOS.copy("/some/remote/path/a", "/some/remote/path/b")) rescue Exception => e Test.fail("RemoteSystem error", e.to_s) end end
package require squish::remotesystem proc main {} { if {[catch {set remoteOS [::Squish::RemoteSystem new]} result]} { test fail "RemoteSystem error" $result } if { [catch { test verify [$remoteOS copy "/some/remote/path/a" "/some/remote/path/b"] } result] } { test fail "RemoteSystem error" $result } }
The close
method can be used to close the connection
from an instance of RemoteSystem
to the squishserver.
Use this if you wish to stop using an instance and explicitly clean up its
resources.
Table of Contents
Squish provides the UiTypes
namespace (in languages where
namespaces make sense) through which items of generic types can be
created.
The UiTypes.DateTime
type (plain DateTime
in
Tcl) is capable of holding a date and time value.
DateTime UiTypes.DateTime(
year, month, dayOfMonth)
;
DateTime UiTypes.DateTime(
year, month, dayOfMonth, hour, minute, second)
;
This construction function creates a DateTime
object. If no
arguments are given all the values are set to -1 (i.e., the
DateTime
is invalid). Here is how to create a valid
DateTime
:
moonLanding = UiTypes.DateTime(1969, 7, 20)
var moonLanding = new UiTypes.DateTime(1969, 7, 20);
my $moonLanding = UiTypes::DateTime->new(1969, 7, 20);
moonLanding = UiTypes::DateTime.new(1969, 7, 20)
set moonLanding [construct DateTime 1969 7 20]
The Squish UiTypes
namespace is inside the
Squish
namespace that is automatically imported into test
scripts—except for Ruby where the script file should begin with a
require 'squish'
statement.
DateTime
objects have the following properties:
This read/write property holds the date/time's year.
int UiTypes.DateTime.monthThis read/write property holds the date/time's month (1-12).
int UiTypes.DateTime.dayThis read/write property holds the date/time's day of the month (1-31).
int UiTypes.DateTime.hourThis read/write property holds the date/time's hour (0-23).
int UiTypes.DateTime.minuteThis read/write property holds the date/time's minutes (0-59).
int UiTypes.DateTime.secondThis read/write property holds the date/time's seconds (0-59).
This function returns the path of the given
filename
or raises a LookupError
exception if the file cannot be found.
If the where
parameter is "scripts"
,
findFile
looks for the filename
in
the test case's scripts
directory. If that doesn't
contain the file the function next tries the test suite's
shared/scripts
directory. If that doesn't contain
the file the function tries the paths in the
paths.ini
file (see Squish Initialization Files (Section 7.6)), and if it still isn't found, the function
tries all of the directories listed in the
SQUISH_SCRIPT_DIR
environment variable (if it is
defined—see Environment Variables (Section 7.5)). As soon as the file is
found, the filename's path is returned; otherwise a catchable
LookupError
exception is raised.
If the where
parameter is "testdata"
,
findFile
looks for the filename
in
the test case's testdata
directory. If that doesn't
contain the file the function next tries the test suite's
shared/testdata
directory, and failing that the
function tries the test case's directory. As soon as the file
is found the filename with full path is returned; otherwise a catchable
LookupError
exception is raised.
(See also, the source
function and the Test Data Functions (Section 6.3.10).)
This function tells Squish to sleep for the specified nominal number
of seconds. The seconds
argument can be a whole
number or a floating-point number. The actual sleep time will depend on
the current snoozeFactor
. Unless you really do need to
force Squish to sleep, it is usually more robust to use the waitForObject
function than to use
snooze
.
The snoozeFactor
can be set using the Squish IDE. Click
| to invoke the Preferences dialog (Section 8.3.17), then click the
Squish item, and then the
Playback item and then set the Snooze
Factor value. The snoozeFactor
can also be set
by using squishrunner's command line options; see squishrunner --record
: Recording a Test Case (Section 7.4.3.21) and Executing a Test Case (Advanced) (Section 7.4.3.25).
Reads and evaluates the contents of filename
,
line-by-line. Unlike the scripting language's normal “import” mechanism,
(such as Python's import
or Perl's use
), this is more
like the C++ #include
directive in that the statements are inserted
into your script at that location. This is one way to parse your own shared script files
rather than using the scripting language's import mechanism, which may require customization
to your environment for it to locate your own modules.
A common use case is to write something like
source(findFile("scripts", "common.js"))
. This uses the
findFile
function to produce a filename
including a path and then evaluates that file's contents as a script.
This typically results in additional functions (and even new classes and
variables) becoming available to the test script that performs this
call.
For Ruby, use the built-in require
method
instead—inside a function or method. For example,
require findFile("scripts", "common.rb"))
.
(See also, How to Create and Use Shared Data and Shared Scripts (Section 5.23), and the Import Squish Resource dialog (Section 8.3.7) and the New Squish Test Script dialog (Section 8.3.12).)
This function simulates a native mouse click on the currently active
window. The x
and y
parameters are the coordinates where the mouse click must take place in
screen coordinates. The button
parameter is the
mouse button that should be used, and must be one of
MouseButton.LeftButton
,
MouseButton.MiddleButton
or
MouseButton.RightButton
.
![]() | Small caveat |
---|---|
In theory it is possible for a call to the |
This function simulates user keyboard input using the operating system's
facilities, sending keypresses to the currently active window, i.e., to
the window with keyboard focus. On Windows, this can be used to interact
with native Windows message boxes, for example. The keyboard input will
be sent to whatever widget has the keyboard focus. The input is
case-sensitive, so nativeType("R")
is different from
nativeType("r")
.
This function can also simulate the input of special keys by using their
names and enclosing them in angle brackets (<>), and can simulate
combinations of keys by separating each key name with a +
.
Here are some examples:
nativeType("Hello"); nativeType("<Return>"); nativeType("<Alt+F4>"); nativeType("<Alt+Tab>"); nativeType("<Ctrl+c>");
This is valid in JavaScript, Perl, Python, and Ruby.
invoke nativeType "Hello" invoke nativeType "<Return>" invoke nativeType "<Alt+F4>" invoke nativeType "<Alt+Tab>" invoke nativeType "<Ctrl+c>"
The
nativeType
function can accept all the normal
alphanumeric characters (which are written literally), as well as the
following special keys (which must be enclosed in angle brackets):
<Alt>
,
<Ctrl>
,
<Shift>
,
<Escape>
,
<Return>
,
<Space>
,
<Backspace>
,
<Tab>
,
<Pause>
,
<PageUp>
,
<PageDown>
,
<Home>
,
<End>
,
<Left>
,
<Right>
,
<Up>
,
<Down>
,
<Insert>
,
<Delete>
,
<Print>
,
<NumPad0>
,
<NumPad1>
,
<NumPad2>
,
<NumPad3>
,
<NumPad4>
,
<NumPad5>
,
<NumPad6>
,
<NumPad7>
,
<NumPad8>
,
<NumPad9>
,
<NumPadMultiply>
,
<NumPadAdd>
,
<NumPadSubtract>
,
<NumPadDivide>
,
<NumPadDecimal>
,
<MenuLeft>
,
<MenuRight>
,
<Win>
,
<WinLeft>
,
<WinRight>
,
<F1>
,
<F2>
,
<F3>
,
<F4>
,
<F5>
,
<F6>
,
<F7>
,
<F8>
,
<F9>
,
<F10>
,
<F11>
,
<F12>
,
<F13>
,
<F14>
,
<F15>
,
<F16>
,
<F17>
,
<F18>
,
<F19>
,
<F20>
,
<F21>
,
<F22>
,
<F23>
,
<F24>
,
<NumLock>
,
<ScrollLock>
,
<CapsLock>
and
<Command>
(macOS only)
.
It is usually better to use one of the toolkit-specific type
functions.
![]() | Small caveat |
---|---|
In theory it is possible for keypresses entered with the
|
This function sends a sequence
of low-level
native events to the window called windowName
.
This function may be useful when interacting with windows from another
application or with widgets implemented with a foreign toolkit. For
interaction with standard application widgets it is best to use
the functions in Squish's API such as the type
function.
Here's an example of use that is legal in JavaScript, Python, Perl, and Ruby:
sendNativeEvent("Login", "username");
At present, the only supported types of event are simple keystrokes. Support for complex keystrokes and for mouse events might be added in a future version. Please contact technical support if this is an important requirement for you.