JavaScript Notes and Extension APIs

Squish assumes that all test.js files use the UTF-8 encoding. If you expect to edit such files outside of the Squish IDE, make sure that the editor loads and saves the files using UTF-8.

JavaScript Language Documentation

In theory, any JavaScript book or online resource is suitable for learning about the language or for looking up functions. Unfortunately most authors don't make a clear distinction between features that are part of the JavaScript language itself and browser-specific extensions. When reading such texts beware of any example code that makes use of the window or document objects since these are provided by browsers and are not part of the language.

By keeping in mind the distinction between the pure language (which is what Squish supports) and browser-specific extensions, you'll be able to find the information you need from a variety of books and online resources while avoiding confusion. Here are some useful online JavaScript language resources:

If you prefer books, a good JavaScript book is JavaScript: The Definitive Guide by David Flanagan.

Language Core

The JavaScript engine shipped with Squish is based on the ECMAScript language specification (ECMA 262 Edition 3, plus parts of later editions). The language core that is defined in this standard encompasses operators, control structures, objects, and other features commonly found in a scripting language. The subset of supported built-in classes and members can be found in Squish ECMAScript Support.

The pure JavaScript (i.e., ECMAScript) language has no built-in support for file handling or networking, unlike other scripting languages such as Python and Tcl. This is because JavaScript has been designed to be a small language that can be safely embedded into applications. However, JavaScript is also designed to be extened by custom APIs specific to the embedding application. In the case of web browsers there are hundreds of functions and properties that allow for the manipulation of HTML documents via the DOM API, for example. In the case of Squish we have added numerous functions specific to testing. And we have also added some general purposes classes described below. And if the features we have added are not sufficient for your needs contact support and request an enhancement.

Note: Some JavaScript functions take a path parameter. This can be a directory or a filename (and can include the full path), such as C:\My Documents\test-plan.odt or /home/user/test-plan.odt. In most scripting languages, including JavaScript, the backslash character (\) is used to start an escape sequence inside strings and so cannot be written by itself. For this reason, when writing Windows paths in JavaScript strings we must escape the backslash—for example, "C:\\My Documents\\test-plan.odt".

Squish ECMAScript Support

This section is about the ECMAScript API subset that is supported in Squish. Squish also adds non-standard objects like File, XML and SQL, and a testing-specific API which are described in other sections of JavaScript Notes and Extension APIs.

Keywords

as, break, case, catch, const, continue, default, delete, do, else, export, extends, false, finally, for, from, function, if, in, instanceof, import, let, new, null, of, return, static, super, switch, this, throw, true, try, typeof, var, void, while, with

Punctuators

{}, \c {}, (, ), [, ], ., ,, ; <, >, <=, >=, ==, !=, ===, !==, +, -, *, /, %,**, ++, --, <<, >>, >>>, &, |, ^, !, ~, &&, ||, ??, ... ?, :, =, +=, -=, *=, /=, %=, **=, <<=, >>=,>>>=, &=, |=,^=, &&=, ||=, ??= and =>.

The Global Object

Value Properties

  • NaN
  • Infinity
  • undefined

Function Properties

  • decodeURI()
  • decodeURIComponent()
  • encodeURI()
  • encodeURIComponent()
  • escape()
  • eval()
  • isFinite()
  • parseFloat()
  • parseInt()
  • unescape()

Constructor Properties

  • Array
  • Boolean
  • Date
  • Error
  • Function
  • Map
  • Number
  • Object
  • RegExp
  • Set
  • String
  • EvalError
  • RangeError
  • ReferenceError
  • SyntaxError
  • TypeError
  • URIError

Other Properties

  • JSON
  • Math

Array

Prototype Function Properties

  • concat()
  • every()
  • filter()
  • forEach()
  • indexOf()
  • join()
  • lastIndexOf()
  • map()
  • pop()
  • push()
  • reduce()
  • reduceRight()
  • reverse()
  • shift()
  • slice()
  • some()
  • sort()
  • splice()
  • toLocaleString()
  • toString()
  • unshift()

Boolean

Prototype Function Properties

  • toString()
  • valueOf()

Date

Prototype Function Properties

  • getDate()
  • getDay()
  • getFullYear()
  • getHours()
  • getMilliseconds()
  • getMinutes()
  • getMonth()
  • getSeconds()
  • getTime()
  • getTimezoneOffset()
  • getUTCDate()
  • getUTCDay()
  • getUTCFullYear()
  • getUTCHours()
  • getUTCMilliseconds()
  • getUTCMinutes()
  • getUTCMonth()
  • getUTCSeconds()
  • getYear()
  • setDate()
  • setFullYear()
  • setHours()
  • setMilliseconds()
  • setMinutes()
  • setMonth()
  • setSeconds()
  • setTime()
  • setUTCDate()
  • setUTCFullYear()
  • setUTCHours()
  • setUTCMilliseconds()
  • setUTCMinutes()
  • setUTCMonth()
  • setUTCSeconds()
  • setYear()
  • toDateString()
  • toGMTString()
  • toISOString()
  • toJSON()
  • toLocaleDateString()
  • toLocaleString()
  • toLocaleTimeString()
  • toString()
  • toTimeString()
  • toUTCString()
  • valueOf()

Error

Prototype Value Properties

  • message
  • name

Function Properties

  • toString()

Function

Prototype Value Properties

  • length
  • name

Prototype Function Properties

  • apply()
  • bind()
  • call()
  • toString()

The JSON Object

Function Properties

  • parse()
  • stringify()

Map

Prototype Function Properties

  • clear()
  • delete()
  • forEach()
  • get()
  • has()
  • keys()
  • set()
  • values()

The Math Object

Value Properties

  • E
  • LN10
  • LN2
  • LOG10E
  • LOG2E
  • PI
  • SQRT1_2
  • SQRT2

Function Properties

  • abs()
  • acos()
  • asin()
  • atan()
  • atan2()
  • ceil()
  • cos()
  • exp()
  • floor()
  • log()
  • max()
  • min()
  • pow()
  • random()
  • round()
  • sin()
  • sqrt()
  • tan()

Number

Prototype Function Properties

  • toExponential()
  • toFixed()
  • toLocaleString()
  • toPrecision()
  • toString()
  • valueOf()

Object

Function Properties

  • create()
  • defineProperties()
  • defineProperty()
  • freeze()
  • getOwnPropertyDescriptor()
  • getOwnPropertyNames()
  • getPrototypeOf()
  • is()
  • isExtensible()
  • isFrozen()
  • isSealed()
  • keys()
  • preventExtensions()
  • seal()
  • setPrototypeOf()

Prototype Function Properties

  • eval()
  • hasOwnProperty()
  • isPrototypeOf()
  • propertyIsEnumerable()
  • toLocaleString()
  • toString()
  • valueOf()
  • __defineGetter__()
  • __defineSetter__()

RegExp

Value Properties

  • $1...$9

Prototype Value Properties

  • global
  • ignoreCase
  • lastIndex
  • multiline
  • source

Set

Prototype Function Properties

  • add()
  • clear()
  • delete()
  • entries()
  • forEach()
  • has()
  • keys()
  • values()

String

Constructor Function Properties

  • fromCharCodeAt()

Prototype Function Properties

  • anchor()
  • big()
  • blink()
  • bold()
  • charAt()
  • charCodeAt()
  • concat()
  • endsWith()
  • fixed()
  • fontcolor()
  • fontsize()
  • includes()
  • indexOf()
  • italics()
  • lastIndexOf()
  • link()
  • match()
  • repeat()
  • replace()
  • search()
  • slice()
  • small()
  • split()
  • startsWith()
  • strike()
  • sub()
  • substr()
  • substring()
  • sup()
  • toLowerCase()
  • toString()
  • toUpperCase()
  • trim()
  • trimLeft()
  • trimRight()
  • valueOf()

File Object

The File object provides basic file handling functions such as checking for a file's existence, opening a file for reading or writing, and removing a file. In general paths that include directories can be separated using / (which doesn't need escaping), even on Windows.

Example:

var file = File.open("C:\\testdata\\input.txt", "r");
file.encoding = "system"; // Should only be needed for some Windows AUTs
var text = file.read();
inputField.setText(text);

The default file encoding is "utf-8" which is the best encoding to use for text files.

Here are some quick links to the File object's properties and methods.

file.close()

This method closes the file object it is called on. Once closed a file object cannot be read from or written to.

File.copy(source, target)

This function copies the file source to target. If this fails an exception is thrown.

The copy fails if target already exists. If desired, Boolean File.remove(fileName) can be used beforehand to make room for the copy.

String file.encoding

This property defines the encoding to use when reading or writing files. The default encoding is "utf-8". For AUTs that don't support UTF-8 (such as some Windows applications), setting the encoding to "system" may prove helpful since this makes Squish use the current system locale. Other possible values are "ucs-2" (2 byte Unicode, for reading UTF-16 on Windows) 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.

Boolean File.exists(fileOrDirectory)

This function returns true if the specfied fileOrDirectory exists; otherwise it returns false. The fileOrDirectory may include an absolute or relative path, or no path, in which case the current working directory is used.

File File.open(fileName)

File File.open(fileName, mode)

This function tries to open the specified fileName (which may include an absolute or relative path, or no path, in which case the current working directory is used). The optional mode parameter defaults to "r" (open for reading). If the mode is specified it must be: "a" (open for append), or "r" (open for reading), or "w" (open for writing). If the fileName cannot be opened a catchable exception is thrown.

Once a file has been successfully opened its methods can be called. For files opened in append or write mode the file.write(string) method can be called, and for files opened in read mode the String file.read() and String file.readln() methods can be called. And for any opened file, the file.close() method can be called.

StringList File.glob(pattern, [pattern...])

This function returns the list of paths matching any of the given patterns.

String file.read()

This method reads in the entire contents of the file object returned by the File File.open(fileName) function—providing the file was opened in read mode. The file's content is assumed to be plain text using the UTF-8 encoding (unless the file.encoding property is changed).

String file.readln()

This method reads in the next line from the file object returned by the File File.open(fileName) function—providing the file was opened in read mode. The file's content is assumed to be plain text using the UTF-8 encoding (unless the file.encoding property is changed). Each line is returned without any end of line characters, and if an attempt to read beyond the last line is made, null is returned.

Boolean File.remove(fileName)

This function tries to remove the specified fileName (which may include an absolute or relative path, or no path, in which case the current working directory is used). If the file was successfully removed the function returns true; otherwise it returns false.

String File.separator

The global File object's read-only separator property holds the file separator used by the operating system. For example, on Windows it holds, "\", and on Unix-like systems, "/".

Number File.size(fileName)

This function returns the size of the specified fileName (which may include an absolute or relative path, or no path, in which case the current working directory is used).

file.write(string)

This method writes the given string to the file object returned by the File File.open(fileName) function—providing the file was opened in append or write mode. The string is written using the UTF-8 encoding (unless the file.encoding property is changed).

console Object

The console object provides functions for basic interaction with script execution. The console object is not a standard JavaScript object, but is well known from web browsers.

Here are some quick links to the console Object's methods:

console.assert(bool, string [optional])

If the first parameter is evaluated to false the script execution will be stopped and an error message is written to the test results, otherwise nothing will happen. The second parameter is optional and allows writing user specified message to the test result.

Here is an example that shows the usage of this function:

var index = findIndexOfSomething( "something" );
Console.assert( index >= 0, "Something not found, execution aborted!" );
something[ index ].doSomething();

OS Object

The OS object provides functions for basic interaction with the operating system. It includes functions for executing commands (i.e., for running programs), for getting and setting the current directory, and for getting and setting environment variables.

Here are some quick links to the OS Object's properties and methods:

Array OS.argv

The OS object's read-only argv property holds the absolute filename to the current test script followed by the list of script arguments passed to squishrunner (see also squishrunner).

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);

String OS.cwd()

This function returns the current working directory as a string.

Example:

var path = OS.cwd();
test.log("Current working directory: " + path);

String OS.getenv(name)

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]);

String OS.machine

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.

String OS.name

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.

OS.pause(msecs)

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);

Boolean OS.rmdir(path)

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);

Boolean OS.mkpath(path)

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);

OS.setenv(name, value)

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 bugs@example.com");

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);

XML Object

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.

XMLNode XML.parse(markup)

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.

XMLNode xmlNode.firstChild

This read-only node property holds this node's first child—or a null node if this node has no children.

String xmlNode.getAttribute(attributeName)

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.

ListOfXMLNode xmlNode.getElementsByTagName(tagName)

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.

XMLNode XMLNode.selectSingleNode(XPathExpression)

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.

jsTupelOfValues xmlNode.selectNodes(XPath.Expression)

This function evaluates an XPath.Expression on an XMLNode object's parent document and returns a list of XMLNode objects.

jsValue XMLNode.getSingleValueByXPath(XPathExpression)

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.

jsTupelOfValues XMLNode.getValuesByXPath(XPath.Expression)

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'.

Boolean xmlNode.isNull

This read-only node property is true if the node is a null node; otherwise it is false.

XMLNode xmlNode.nextSibling

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).

String xmlNode.nodeName

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>".

Integer xmlNode.nodeType

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

String xmlNode.nodeValue

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

XMLNode xmlNode.parentNode

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.)

String xmlNode.textContent

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.

String xmlNode.toXMLString()

This function returns an XML-formatted string representation of the XMLNode object including tags, attributes and child elements.

SQL

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.

SQLConnection SQL.connect(informationObject)

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.

Number sqlConnection.execute(sql)

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).

int sqlResult.size

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.

sqlResult.toFirst()

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%';");
// result is automatically set the first row
while (result.isValid) {
    // do something with the result
    result.toNext();
}

String sqlResult.value(fieldNumber|fieldName)

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%';");
// result is automatically set the first row
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.

Socket Object

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()

This method closes the socket connection. Once closed a socket object cannot be read from or written to.

socket Socket.connect(host, port)

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.

String socket.encoding

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.

String socket.localAddress

The socket object's localAddress property holds the address used on the local machine for the socket.

Number socket.localPort

The socket object's localPort property holds the port used on the local machine for the socket.

Number socket.readInt8()

This method reads a signed 8-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.

Number socket.readInt32()

This method reads a signed 32-bit integer from the socket. On success the integer value is returned otherwise a catchable exception is thrown.

String socket.readLine()

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.

Number socket.remotePort

The socket object's remotePort property holds the port used on the remote machine for the socket.

Number socket.timeout

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.

Socket.writeString(string)

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();

WebSocket WebSocket.connect( hostname)

Connects to hostname:port and returns a WebSocket object on success. On failure, an exception is thrown.

websocket.close()

Closes a WebSocket connection.

websocket.sendTextMessage( message)

Sends a text message through the WebSocket. Throws an exception on failure.

String websocket.receiveTextMessage()

Receives a message from the WebSocket. Throws an exception if there is nothing to receive.

String websocket.host

A readonly property that holds the host this socket is connected to.

Boolean websocket.open

A readonly property that tells if this socket is currently open.

Number websocket.port

A readonly property that holds the port this socket is connected to.

Number websocket.timeout

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.

XMLHttpRequest Object

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.

XMLHttpRequest XMLHttpRequest()

The constructor for the XMLHttpRequest type.

XMLHttpRequest.abort()

This function will reset the client object and change the readyState property back to UNSENT.

String XMLHttpRequest.getResponseHeader(header)

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".

String XMLHttpRequest.getAllResponseHeaders()

This function returns all headers from the response. Whereas each name/value pair is separated by a CR/LF sequence.

XMLHttpRequest.open(method, url, async, [username], [password])

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.

Number XMLHttpRequest.readyState

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.

String XMLHttpRequest.responseText

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);

XMLHttpRequest.send([data], [boundary])

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.

XMLHttpRequest.setRequestHeader(header, value)

This function adds a header to the list of request headers, of if header is already in the list of headers, combines its value with value An example showing an explicit setting of the type of message being sent:

client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send(message);

Number XMLHttpRequest.status

This read-only property holds the HTTP status code of the previous request. For example, 200 if a GET request succeeded. See the Status Code Registry for a complete listing.

String XMLHttpRequest.statusText

This read-only property holds the HTTP status text of the previous request. For example, "OK" if a GET request succeeded. See the Status Code Registry for a complete listing.

FormData Object

The FormData object offers a key-value-based container for handling data collected in forms. It resembles the FormData Web API. Most of the functions have been implemented to enable test suites to prepare, handle and send FormData using XMLHttpRequest.send([data], [boundary]) of the XMLHttpRequest Object.

The following example shows the creation of a FormData object and usage of all its methods. Accompanying descriptions follow further below.

var data = new FormData();

// appending values
data.append("key", "value 1");
data.append("key", "value 2");
var valueList = data.getAll("key");

// looking for values
if (data.has("key")) {
  // ...
}

// overwriting values
data.set("key", "new value");
var singleValue = data.get("key");

// removing values
data.remove("key");

data.append(key, value)

This method appends a value of any type identified by a key. The FormData container can store multiple values for one key. All values are handled as strings. Additional parsing is needed for handling other types.

It is also possible to append files. In contrast to the Web API for FormData documentation, Squish utilizes the File API offered by File Object. The following example appends a plain text file to a FormData instance.

Note: Sending binary files is currently not supported.

var data = new FormData();
var file = File.open("data.txt","r");
data.append("test.txt", file.read());
file.close();

For more details about the File object and its methods, see File File.open(fileName), String file.read() and file.close().

String data.get( key)

Gets a single value stored with data.append(key, value) or data.set(key, value). It returns either a single value or the first stored value for keys with multiple values.

ListOfString data.getAll( key)

Returns all values for a given key as a list.

Boolean data.has(key)

Returns true if the container has a value for key, otherwise false.

data.remove( key)

Removes all values for key. If multiple values were stored all of them are removed.

data.set(key, value)

Overrides the stored key-value pair with the provided value. If there were multiple values before, all of them will be removed before adding the new value.

© 2023 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners.
The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation.
Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.