Here is an example that shows how to read an optional script argument:
var filename = "defaultfile.txt";
if (OS.argv.length > 1) {
filename = OS.argv[1];
String OS.capture(command)
This function executes the given command
in a shell (console) just like the int OS.system(command) function. The command
string must hold the name of the command to be executed, and may optionally include command line arguments and shell redirection characters. What makes this function different from the int OS.system(command) function is that it captures the command's output, that is, any text that would normally go to the console (the stdout
stream), and returns it as a string.
Here is an example that shows the execution of a command on Windows, and the capturing of its output:
var files = OS.capture("dir C:\\temp\\*.dat").split('\n');
for (var i in files) {
var file = files[i];
Note that in this particular case it is easier and better to use the cross-platform Array OS.listDir(path) function to get a list of files in a directory.
OS.chdir(path)
This function changes the test script's current working directory to the specified path
.
Example:
var path = OS.cwd() + "/results";
OS.chdir(path);
This function returns the current working directory as a string.
Example:
var path = OS.cwd();
test.log("Current working directory: " + path);
This function returns the value of the environment variable with the given name
, or an empty string if no such environment variable exists. (See also, OS.setenv(name, value).)
Example:
var homeDir = OS.getenv("HOME");
test.log("Current user's home directory: " + homeDir);
Array OS.listDir(path)
This function returns a list of all the files and directories in the directory specified by path
, but excluding the special directories .
(current) and ..
(parent). This function does not recurse into subdirectories.
Here is an example that logs all the files that were generated in an output directory on Windows:
var files = OS.listDir("C:\\temp\\output");
for (var i in files)
test.log("Found generated file: " + files[i]);
The OS
object's read-only machine
property holds the name of the machine's hardware that squishrunner is running on. On Microsoft Windows systems the value is either "x86", "amd64", "arm64" or "ia64". On Unix-like systems the value is the same as the output of uname -m
, e.g. "i686", "x86_64", etc.
The OS
object's read-only name
property holds the name of the operating system that squishrunner is running on. On Microsoft Windows systems the value is "Windows". On Unix-like systems the value is the same as the output of uname -s
, e.g. "Linux", "Solaris", "Darwin", etc.
This function pauses the script for the specified number of milliseconds. Unlike the snooze(seconds) function, the delay is fixed and not influenced by the current snooze factor setting.
Boolean OS.removeRecursively(path)
This function deletes the directory found at path
including all of its contents. The function returns true
on success and in case the directory did not exist in the first place. (The desired result was still achieved.)
Example:
OS.system("mkdir exampleDir");
var file = File.open("exampleDir/data", "w");
file.write("some data");
file.close();
var result = OS.removeRecursively("exampleDir");
test.log("Deletion result: " + result);
This function deletes the directory found at path
. It must be empty at the time of deletion. On success, the function returns true
.
Example:
var oldDir = "C:\\build_old";
var result = OS.rmdir(oldDir);
test.log("Deletion result: " + result);
This function creates the directory with the path path
, if the path is absolute and with the path current_directory/path
, if the path is relative. IMPORTANT: all necessary directories mentioned in path
will be created, if they don't already exist. The function throws an error in case:
(a) call arguments are wrong; or
(b) directory already exists; or
(c) creating directory failed for any other reason like I/O error.
If successful, function returns true
.
Example:
var Dir = "C:\\some_new_directory";
var result = OS.mkpath(Dir);
test.log("Directory created: " + result);
This function sets the environment variable called name
to have the given value
. The name
environment variable is created (and then set to the given value
) if it doesn't already exist. (See also, String OS.getenv(name).)
Example:
var preferredEditor = "vim";
OS.setenv("EDITOR", preferredEditor);
int OS.system(command)
This function executes the given command
in a shell (console). If the execution is successful the return status is returned; otherwise -1 is returned to signify that an error occurred. The command
string must hold the name of the command to be executed, and may optionally include command line arguments and shell redirection characters.
Here is an example that executes a custom application on Windows and redirects its stdout
stream to a file:
var result = OS.system("C:\\testprograms\\readresult.exe > output.txt");
if (result == -1)
test.fatal("readresult error occurred");
else if (result != 0)
test.warning("readresult failed");
Here is another example: this sends an email on a Unix system:
var msg = "This is a mail from Squish";
OS.system("echo '" + msg + "' | mail -s Subject [email protected]");
See also the String OS.capture(command) function.
Array OS.version
The OS
object's read-only version
property holds an array with information about the operating system that squishrunner is running on. The array's elements are named "major", "minor" and "name" and denote the version number and human-readable representation.
Here is an example making use of this information to ensure test execution on supported operating systems:
var major = OS.version.major;
if (major < 7)
test.warning("Unsupported OS version " + OS.version.name);
The XML
object provides a parsing function that operates on a string of XML-marked-up text, and that returns an XMLNode
object that provides methods which allow the XML to be traversed and queried.
This function parses the given string of XML markup and returns a document node object that represents the root of the document tree. If the parse fails a catchable exception is thrown.
Note that the XML is assumed to use the UTF-8 encoding (which is the default for XML files that don't specify an encoding), even if an encoding is specified that isn't UTF-8.
This read-only node property holds this node's first child—or a null node if this node has no children.
This node method returns a string containing the value of the node's attributeName
attribute. If the node doesn't have an attribute called attributeName
, the method's behavior is undefined. If the attributeName
is an empty string, a catchable exception is thrown. All of a node's attribute names can be retrieved using the ListOfString xmlNode.getAttributeNames() function.
Note: This function must only be called on element nodes—those nodes whose nodeType
attribute's value is XML.ElementNode
. Calling the function on non-element nodes will cause a catchable exception to be thrown.
ListOfString xmlNode.getAttributeNames()
This node method returns a list of strings containing the names of all the node's attributes. Any of these names can be used as the argument to the String xmlNode.getAttribute(attributeName) function to get the corresponding attribute's value.
Note: This function must only be called on element nodes—those nodes whose nodeType
attribute's value is XML.ElementNode
. Calling the function on non-element nodes will cause a catchable exception to be thrown.
Boolean xmlNode.hasAttribute(attributeName)
This function returns true
if the node has an attribute called attributeName
; otherwise it returns false
.
Note: This function must only be called on element nodes—those nodes whose nodeType
attribute's value is XML.ElementNode
. Calling the function on non-element nodes will cause a catchable exception to be thrown.
This function returns a list of XMLNode
objects for the given tagName
.
Note: This function must only be called on document or element nodes—a node whose nodeType
property's value is XML.DocumentNode
or XML.ElementNode
respectively. Calling the function on other nodes will cause a catchable exception to be thrown.
This function evaluates a given XPath.Expression
on an XMLNode
object's parent document and retrieves the first XMLNode
object the evaluation returns, or (if given XPath exptession doesn't evaluate anything) null
will be beturned.
This function evaluates an XPath.Expression
on an XMLNode
object's parent document and returns a list of XMLNode
objects.
This function evaluates a given XPath.Expression
on an XMLNode
object's parent document and retrieves the content of the first XMLNode
object the evaluation returns. So return type varies, depending on the type of content the returned XMLNode
object contains. If the evaluation won't return any nodes, it will return null.
This function evaluates an XPath.Expression
on an XMLNode
object's parent document and returns a JavaScript tuple, which elements are either: directly that contents which are contained in the returned XMLNode
objects, or, if evaluation may return XMLNode
objects which contain just a subtree of even more XMLNode
objects as children, these nodes then are contained in the tuple 'as are'.
This read-only node property is true
if the node is a null node; otherwise it is false
.
This read-only node property holds this node's next sibling node (which will be a null node if this node has no next sibling).
This node property holds the node's name, which is the tag name for element nodes. For the document node the node name is always "<anonymous xml document>".
This node property holds the node's type as enum value. The possible type values are:
0 : XML.DocumentNode
1 : XML.ElementNode
2 : XML.CommentNode
3 : XML.UnknownType
4 : XML.TextNode
5 : XML.DeclarationNode
This node property holds the node's value. The meaning depends on the type of the node as follows:
XML.CommentNode
provides the comment text
XML.DeclarationNode
provides an empty text
XML.DocumentNode
provides the fixed text "<anonymous xml document>"
XML.TextNode
provides the text string
XML.UnknownType
provides the content of the tag
This node property holds the node's parent node or a null node if this node has no parent. (For example, the document node has no parent.)
This node property holds the text contained within this node (which could be an empty string).
Note that this node property does not traverse its child nodes to produce a concatenation of all their texts. For example:
var documentNode = XML.parse("<a>Hello</a>");
var anchorNode = documentNode.firstChild;
test.verify(anchorNode.textContent == "Hello");
documentNode = XML.parse("<a><b>Hello</b></a>");
anchorNode = documentNode.firstChild;
test.verify(anchorNode.textContent == "");
var boldNode = anchorNode.firstChild;
test.verify(boldNode.textContent == "Hello");
Note: This function must only be called on element nodes—those nodes whose nodeType
attribute's value is XML.ElementNode
. Calling the function on non-element nodes will cause a catchable exception to be thrown.
This function returns an XML-formatted string representation of the XMLNode
object including tags, attributes and child elements.
Squish provides its own APIs for accessing SQL databases since the JavaScript specification does not include them. To see the SQL APIs in action, see the JavaScript examples in How to Access Databases from Squish Test Scripts.
SQL Object
The SQL
object provides a means of connecting to a database, executing queries on the database, and traversing and inspecting results. This functionality might be useful for retrieving test data or for providing data to the AUT.
This function tries to connect to a SQL database. If it succeeds a SQLConnection Object is returned—this can be used to execute SQL statements on the database. If the connection fails a catchable exception is thrown. The information required to establish the connection must be passed as an object whose properties are then interpreted.
Here is an example invocation showing how to connect to a MySQL server on a host called "dulsberg", with the given username and password:
var conn = SQL.connect( { Driver: "MySQL",
Host: "dulsberg",
Port: 1342,
Database: "mydatabase",
UserName: "test",
Password: "secretPhrase" } );
The object's attributes have the following meanings:
Driver: The driver is used to specify what kind of database we are connecting to. Possible values are:
- DB2*: IBM DB2, v7.1 and higher
- IBase*: Borland Interbase Driver
- MySQL: MySQL Driver
- ODBC: ODBC Driver (includes Microsoft SQL Server)
- Oracle*: Oracle Call Interface Driver
- PostgreSQL: PostgreSQL v8.x Driver
- SQLite: SQLite 3 Driver
- Sybase*: Sybase Adaptive Server
Note: The drivers marked with an asterisk (*) are not supported in Squish binary packages. This is usually because the database vendor's license does not permit redistributing their client libraries without owning a license for their product. The solution is to either try the ODBC driver, or to build Squish yourself against a Qt library which includes support for your particular SQL database.
- Host: This is used to specify the host name (or the IP address) of the computer on which the SQL database is installed.
- Port: This is used to specify the port on the remote computer to which the connection should be established. If this is omitted, the default port for the specified driver is used.
- Database: This is used to specify the name of the database to which the connection should be made.
- DataSource: This is used to specify the Data Source Name (DSN) to use. Note that specifying this attribute is only necessary when using the ODBC driver.
- UserName: This is used to specify the user name to use when logging into the database.
- Password: This is used to specify the password to use when logging into the database. If omitted, an empty password is assumed.
SQLConnection Object
SQLConnection
objects are returned by the SQLConnection SQL.connect(informationObject) function described above; the object provides the methods listed below.
sqlConnection.close()
This method closes the SQL connection.
This method executes the given sql
statement (such as DELETE
, INSERT
, or UPDATE
) on the SQLConnection
object. If the statement succeeds the number of rows affected is returned; or -1 if the number cannot be determined. If an error occurs, a catchable exception is thrown.
If the result returned by the statement needs to be read (e.g. for CALL
) use SQLResult sqlConnection.query(sql).
SQLResult sqlConnection.query(sql)
This method executes the given sql
statement (e.g., a SELECT
statement) on the SQLConnection
object. If the statement succeeds a SQLResult Object is returned. If an error occurs, a catchable exception is thrown.
Here is an example that shows how to execute a SQL query on a connection object:
var result = connection.query("SELECT last_name, first_name " +
"FROM people WHERE country LIKE 'A%';");
SQLResult Object
SQLResult
objects are returned by the Number sqlConnection.execute(sql) and SQLResult sqlConnection.query(sql) methods. A SQLResult
object provides the functions and properties listed below. Note that in the case of SELECT
statements, the SQLResult
object is automatically set to the first row (if any were retrieved).
Boolean sqlResult.isValid
This property is true
if the SQLResult
object is in a valid state; otherwise it is false
. Some functions return invalid result objects to indicate errors or other special conditions (see below).
This property holds the number of rows affected by the query (for example, the number of rows deleted, inserted, or updated)—or -1 if the number could not be determined. And for SELECT
queries this property holds the number of rows which this result contains.
This function navigates to the first row in this result. This is useful if you want to iterate over the rows multiple times: after processing the rows using the sqlResult.toNext() function, call this function to return to the first row so that you can use the sqlResult.toNext() function once again.
sqlResult.toNext()
This function navigates to the next row in this SQL result. If there is no next row (because there are no rows at all or because we have already navigated to the last row), this SQLResult
object is marked as invalid. This function and the isValid
property make it easy to iterate over the results of a SELECT
query. For example:
var result = connection.query("SELECT last_name, first_name " +
"FROM people WHERE country LIKE 'A%';");
while (result.isValid) {
result.toNext();
This function can be used to get the data in the given column (field) for the current row (record). The column can be identified by its position (counting from zero), or by using the (case-insensitive) field name. The data in the given column is implicitly converted into a string. Note that you can also use the bracket-syntax (shown in the example below) as a shortcut.
var result = connection.query("SELECT first_name, last_name " +
"FROM people WHERE country LIKE 'A%';");
while (result.isValid) {
var name1 = result.value(0) + " " + result.value(1);
var name2 = result.value("first_name") + " " + result.value("last_name");
var name3 = result["first_name"] + " " + result["last_name"];
test.verify(name1 == name2 && name2 == name3);
result.toNext();
This example shows three different ways of indexing fields, all of which are equivalent.
The Socket
object can be used as TCP client socket to connect to a server socket to read and write strings.
Example:
var socket = Socket.connect("192.168.1.42", 4711);
socket.encoding = "latin1";
socket.writeString("hello");
var line = socket.readLine();
socket.close();
Here are some quick links to the Socket
object's properties and methods.
- socket.close()
- socket Socket.connect(host, port)
- socket.encoding
- socket.localAddress
- socket.localPort
- Number socket.readInt8()
- Number socket.readInt32()
- String socket.readLine()
- socket.remoteAddress
- socket.remotePort
- socket.timeout
- Socket.writeString(string)
socket.close()
This method closes the socket connection. Once closed a socket object cannot be read from or written to.
This function tries to connect to the specified host name (or the IP address) and port and returns a socket object on success. If the connection failed a catchable exception is thrown.
The socket
object's encoding
property holds the encoding to read and write strings. The default encoding is "utf-8"
. Other possible values are "ucs-2"
(2 byte Unicode) and "latin1"
(also known as ISO 8859-1) which includes the US-ASCII range.
This property should be set before doing any reading or writing of strings.
The socket
object's localAddress
property holds the address used on the local machine for the socket.
The socket
object's localPort
property holds the port used on the local machine for the socket.
This method reads a signed 8-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.
This method reads a signed 32-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.
This method reads until one of the line endings "\n"
or "\r\n"
are read from the socket returned by the socket Socket.connect(host, port) function. The content is assumed to be text using the UTF-8 encoding (unless the socket.encoding property is changed). On success the string is returned without line ending. If no line ending is received a catchable exception is thrown.
String socket.remoteAddress
The socket
object's remoteAddress
property holds the address used on the remote machine for the socket.
The socket
object's remotePort
property holds the port used on the remote machine for the socket.
The socket
object's timeout
property holds the timeout used for read and write operations on the socket. It's an integer number of seconds which defaults to 20 seconds.
This property should be set before doing any reading or writing.
This method writes the given string
to the socket object returned by the socket Socket.connect(host, port) function. The string
is written using the UTF-8 encoding (unless the socket.encoding property is changed). If the writing fails a catchable exception is thrown.
WebSocket Object
The WebSocket
object implements text-based communication with a server via the WebSocket protocol. Its functions block until completion for convenient use within a test script.
var socket;
try {
socket = WebSocket.connect("websocket-server", 80);
} catch (e) {
test.log("Could not connect: " + e);
return;
socket.timeout = 500;
socket.sendTextMessage( "'Quack!' said the frog." );
test.log("received: " + socket.receiveTextMessage());
socket.close();
Connects to hostname:port
and returns a WebSocket object on success. On failure, an exception is thrown.
Closes a WebSocket connection.
Sends a text message through the WebSocket. Throws an exception on failure.
Receives a message from the WebSocket. Throws an exception if there is nothing to receive.
A readonly property that holds the host this socket is connected to.
A readonly property that tells if this socket is currently open.
A readonly property that holds the port this socket is connected to.
Holds the timeout (default: 3000 ms) used when sending and receiving data through the WebSocket. This property can be changed at any time and expects a millisecond value.
The XMLHttpRequest
object can be used as a HTTP client that can make GET
, HEAD
, POST
, PUT
, PATCH
or DELETE
requests. Possible usage ranges from querying the content of Web pages up to so called REST calls with data transmitted as plain text, XML or JSON.
The constructor for the XMLHttpRequest
type.
This function will reset the client object and change the readyState property back to UNSENT
.
This function returns the header field value from the response of which the field name matches header. A call like
var client = new XMLHttpRequest();
client.open("GET", "http://www.example.com/result.txt", false);
client.send();
test.log(client.getResponseHeader("Content-Type"));
might log a result like "text/plain".
This function returns all headers from the response. Whereas each name/value pair is separated by a CR/LF sequence.
This function opens the client for a method
request to the specified url
. The method
can be any of GET
, HEAD
, POST
, PUT
, PATCH
or DELETE
. The async
parameter has to be false
.
The optional username
and password
parameters can be used for authentication against the server.
Unlike in a Web browser the requests initiated through the XMLHttpRequest object will run in the foreground only. Installation of a handler receiving the data asynchronously is not required. With async
set to false
calls to send() will wait for the response to fully have arrived before returning.
This property holds the current state of the client. Possible values are XMLHttpRequest.UNSENT
, OPENED
, HEADERS_RECEIVED
, LOADING
and DONE
. Given the synchronous send() mode the intermediate states HEADERS_RECEIVED
and LOADING
will not be visible to the test script.
In case of a successful request this property holds the server's response. The response text is expected to have been UTF-8 encoded. Here is an example that makes use of this property to check the content of a Web page:
var client = new XMLHttpRequest();
client.open('GET', 'https://www.froglogic.com', false);
client.send();
test.compare(client.status, 200);
test.verify(client.response.indexOf("Testing") >= 0);
This function initiates the request as specified by XMLHttpRequest.open(method, url, async, [username], [password]). The data
argument is ignored if the request method is GET
or HEAD
. The optional boundary
is only used when sending form data and sets the dividing boundary between key-value pairs.
An fictional example demonstrating the addition of a customer to a database via a REST API call:
var client = new XMLHttpRequest();
client.open("POST", "http://www.example.com/rest/CUSTOMER/", false);
client.send("<CUSTOMER><ID>60</ID><FIRSTNAME>Laura</FIRSTNAME><LASTNAME>Miller</LASTNAME><STREET>443 Seventh Av.</STREET><CITY>Lyon</CITY></CUSTOMER>");
test.compare(client.statusText, "Created");
Furthermore, this function can send FormData according to the FormData Web API using an HTTP POST
or PUT
request. The following example shows how another customer can be added to the same database as above using FormData.
var client = new XMLHttpRequest();
client.open("POST", "http://www.example.com/rest/CUSTOMER/", false);
client.setRequestHeader( "Content-type", "multipart/form-data" );
var data = new FormData();
data.append("id", "61");
data.append("firstname", "John");
data.append("lastname", "Smith");
data.append("street", "1301 Ferguson Rd");
data.append("city", "Sebastopol");
client.send(data);
test.compare(client.statusText, "Created");
When sending form data this way it is important to use XMLHttpRequest.setRequestHeader(header, value) and to set the media type with Content-type
to multipart/form-data
. Setting the Content-type
header is imperative for data to be interpreted correctly by the server.
It is possible to set a custom boundary used in the HTTP request body to separate the keys from the values and avoid any random boundaries. This boundary is provided as a second optional argument for the send method. The boundary should not exceed 70 characters and should contain only characters from the US-ASCII character set. When using UTF-8 characters please set the charset inside Content-Type header accordingly.
client.send(data, "CUSTOMBOUNDARY");
For further details how to handle such data please refer to the section FormData Object.