Converting Scripts From One Scripting Language To Another

Applies to TestComplete 15.47, last modified on January 20, 2023

TestComplete supports several scripting languages. In some case, you may need to convert script code from one language to another. Typically, this is not the code samples from TestComplete documentation, as it includes examples in all the supported languages. Usually, this happens when you find some third-party code that does what you need, but is written in a scripting language other than the one that your test project uses.

Modern programming and testing tools (including TestComplete) don’t convert scripts automatically, you have to do this manually.

Different scripting languages have similar code structures, but declare and implement them in slightly different manners. Below are equivalents of code structures used in the scripting languages that TestComplete supports. Use this list as a hint to convert scripts faster.

Tip: C#Script, C++Script and JScript (not JavaScript), use the same scripting engine, so there is no need to convert script code from one of these languages to another. You can use JScript code with no changes in C#Script and C++Script projects, and vice versa.

Brief overview

The table below lists sample scripting statements that demonstrate syntactic differences between the scripting languages.

Case sensitivity

Sensitive

Sensitive

Procedure declaration

function MyProcedure()
{
  …
}

def MyProcedure():
  ...

Function declaration

function MyFunction()
{
  …
  return 0;
}

def MyFunction():
  ...
  return 0

Variable declaration

let x, y;
var x, y;

 

Constant declaration

const c = 45;

x = 0
y = 0

Boolean values

true false

True False

String literal

"String"
'String'

"String"
'String'
"""String"""

String concatenation

"Abra" + "cadabra"

"Abra" + "cadabra"

Comments

/* Multi-line
comment */

// Single-line comment

# Single-line comment

Assignment

x = 10;

x = 10

Object assignment

x = MyObject;

x = MyObject

Getting object property

x = obj.MyProperty;
x = obj.$get("MyProperty");

x = obj.MyProperty

Calling object method

x.MyMethod(Param1, Param2);
x.$call("MyMethod", Param1, Param2);

x.MyMethod(Param1, Param2)

Arithmetic operations

Addition

x + 5

x + 5

Subtraction

y - 9

y - 9

Multiplication

x * y

x * y

Division

x / 2

x / 2

Modulus arithmetic

x % 2

x % 2

Integer division

 

x // 3

Increment

i++
i = i+1

i += 1
i = i+1

Decrement

i- -
i = i-1

i -= 1
i = i-1

Exponentiation

Math.pow(x,3)

x ** 3

Comparison operators

Equality

x == 10

x == 10

Inequality

x != 0

x != 0

Less than

x < 17

x < 17

Greater than

x > 0

x > 0

Less than or equal to

x <= 5

x <= 5

Greater than or equal to

x >= 10

x >= 10

Test object equivalence

Obj1 == Obj2
equal(Obj1, Obj2)

Obj1 == Obj2

Logical operators

Logical negation

! x

not x

Logical conjunction

x && y

x and y

Logical disjunction

x || y

x or y

Logical exclusion

x ^ y

 

Bitwise operators

Bitwise negation

~ x

~ x

Bitwise conjunction

x & y

x & y

Bitwise disjunction

x | y

x | y

Bitwise exclusion

x ^ y

x ^ y

Bitwise left shift

x << y

x << y

Bitwise right shift

x >> y

x >> y

Conditionals

If statement

if (x == 10)
  Test1();
else
  Test2();

if x == 10:
  Test1()
else:
  Test2()

Switch/Select statement

switch (someChar)
{
  case "a": TestOnA(); break;
  case "z": TestOnZ(); break;
  default: TestOnElse();
}

if someChar == 'a':
  TestOnA()
elif someChar == 'z':
  TestOnZ()
else:
  TestOnElse()

Loops

For loop

for (let i = 0; i < 10; i++)
  Test1();

for i in range (0, 9):
  Test1()

While loop

while (i < 10)
  Test1();

while i < 10:
  Test1()

Do-While loop

do Test1(); while (i < 10)

while True:
  Test1()
  if i == 9:
    break

Enumerator loops

for i of object
— or —
Enumerator object
— or —
Utils.Enumerator() method

Utils.Enumerator method

Early exit from loop

break;

break

Arrays

Declare an array

let myArr = new Array(3);

myArr = []

Declare and initialize an array

let Arr = [10, 15, 25, 44];
let Arr = new Array(10, 15, 25, 44);

Arr = [10, 15, 25, 44]

Array length

len(myArr)
VarArrayHighBound(myArr,1)+1

Access array element

myArr[1] = 15;

myArr[1] = 15

Blanks

Verify if data is unassigned

strictEqual(x, undefined)
equal(x, aqObject.EmptyVariant)

x == aqObject.EmptyVariant

Test against empty object

strictEqual(myObj, null)

myObj == None
— or —
myObj == aqObject.EmptyObject

Check against blank value

strictEqual(myObj, null);

x == None

Handling exceptions

Handling exceptions

try
{
  Test1();
}
catch (e)
  Log.Error(e.description);

try:
  Test1
except:
  Log.Error(ExceptionMessage)

Sensitive

Sensitive

Sensitive

Insensitive

Insensitive

function MyProcedure()
{
  …
}

function MyProcedure()
{
  …
}

def MyProcedure():
  ...

Sub MyProcedure
  …
End Sub

procedure MyProcedure;
begin
  …
end;

function MyFunction()
{
  …
  return 0;
}

function MyFunction()
{
  …
  return 0;
}

def MyFunction():
  ...
  return 0

Function MyFunction
  …
  MyFunction = 0
End Function

function MyFunction;
begin
  …
  Result := 0;
end;

let x, y;
var x, y;

var x, y;

 

Dim x, y

var x, y;

const c = 45;

var c = 45;

x = 0
y = 0

Const c = 45

const c = 45;

true false

true false

True False

True False

true false

"String"
'String'

"String"
'String'

"String"
'String'
"""String"""

"String"

'String'

"Abra" + "cadabra"

"Abra" + "cadabra"

"Abra" + "cadabra"

"Abra" & "cadabra"
"Abra" + "cadabra"

'Abra' + 'cadabra'

/* Multi-line
comment */

// Single-line comment

/* Multi-line
comment */

// Single-line comment

# Single-line comment

Rem Single-line comment 1
' Single-line comment 2

{ Multi-line
comment }
// Single-line comment

x = 10;

x = 10;

x = 10

x = 10

x := 10;

x = MyObject;

x = MyObject;

x = MyObject

Set x = MyObject

x := MyObject;

x = obj.MyProperty;
x = obj.$get("MyProperty");

x = obj.MyProperty;
x = obj["MyProperty"];

x = obj.MyProperty

x = obj.MyProperty

x := obj.MyProperty;

x.MyMethod(Param1, Param2);
x.$call("MyMethod", Param1, Param2);

x.MyMethod(Param1, Param2);
x["MyMethod"](Param1, Param2);

x.MyMethod(Param1, Param2)

Call x.MyMethod(Param1, Param2)

x.MyMethod(Param1, Param2);

x + 5

x + 5

x + 5

x + 5

x + 5

y - 9

y - 9

y - 9

y - 9

y - 9

x * y

x * y

x * y

x * y

x * y

x / 2

x / 2

x / 2

x / 2

x / 2

x % 2

x % 2

x % 2

x Mod 2

x mod 2

 

 

x // 3

x \ 3

x div 3

i++
i = i+1

i++
i = i+1

i += 1
i = i+1

i = i+1

Inc(i)
i := i+1

i- -
i = i-1

i- -
i = i-1

i -= 1
i = i-1

i = i-1

Dec(i)
i := i-1

Math.pow(x,3)

Math.pow(x,3)

x ** 3

x ^ 3

 

x == 10

x == 10

x == 10

x = 10

x = 10

x != 0

x != 0

x != 0

x <> 0

x <> 0

x < 17

x < 17

x < 17

x < 17

x < 17

x > 0

x > 0

x > 0

x > 0

x > 0

x <= 5

x <= 5

x <= 5

x <= 5

x <= 5

x >= 10

x >= 10

x >= 10

x >= 10

x >= 10

Obj1 == Obj2
equal(Obj1, Obj2)

Obj1 == Obj2

Obj1 == Obj2

Obj1 Is Obj2

Obj1 = Obj2

! x

! x

not x

Not x

not x

x && y

x && y

x and y

x And y

x and y

x || y

x || y

x or y

x Or y

x or y

x ^ y

x ^ y

 

x Xor y

x xor y

~ x

~ x

~ x

Not x

not x

x & y

x & y

x & y

x And y

x and y

x | y

x | y

x | y

x Or y

x or y

x ^ y

x ^ y

x ^ y

x Xor y

x xor y

x << y

x << y

x << y

 

x shl y

x >> y

x >> y

x >> y

 

x shr y

if (x == 10)
  Test1();
else
  Test2();

if (x == 10)
  Test1()
else
  Test2();

if x == 10:
  Test1()
else:
  Test2()

If x = 10 Then
  Test1
Else
 Test2
End If

if x = 10 then
  Test1
else
  Test2;

switch (someChar)
{
  case "a": TestOnA(); break;
  case "z": TestOnZ(); break;
  default: TestOnElse();
}

switch (someChar)
{
  case "a": TestOnA(); break;
  case "z": TestOnZ(); break;
  default: TestOnElse();
}

if someChar == 'a':
  TestOnA()
elif someChar == 'z':
  TestOnZ()
else:
  TestOnElse()

Select Case someChar
  Case "a" TestOnA
  Case "z" TestOnZ
  Case Else TestOnElse
End Select

case someChar of
  'a': TestOnA();
  'z': TestOnZ();
  else TestOnElse();
end;

for (let i = 0; i < 10; i++)
  Test1();

for (i = 0; i < 10; i++)
  Test1();

for i in range (0, 9):
  Test1()

For i = 0 To 9
  Test1
Next

for i := 0 to 9 do
  Test1

while (i < 10)
  Test1();

while (i < 10)
  Test1();

while i < 10:
  Test1()

Do While i < 10
  Test1
Loop

while (i < 10) do
  Test1();

do Test1(); while (i < 10)

do Test1(); while (i < 10)

while True:
  Test1()
  if i == 9:
    break

Do
  Test1
Loop While i < 10

repeat Test1(); until (i = 10);

for i of object
— or —
Enumerator object
— or —
Utils.Enumerator() method

Enumerator object
— or —
Utils.Enumerator() method

Utils.Enumerator method

For Each
— or —
Utils.Enumerator() method

Utils.Enumerator() method

break;

break;

break

Exit For
Exit Do

break;

let myArr = new Array(3);

var myArr = new Array(3);

myArr = []

Dim myArr(3)

var myArr : array[0..2];

let Arr = [10, 15, 25, 44];
let Arr = new Array(10, 15, 25, 44);

var Arr = [10, 15, 25, 44];
var Arr = new Array(10, 15, 25, 44);

Arr = [10, 15, 25, 44]

Dim myArr: myArr = Array(10, 15, 25, 44)

 

myArr.length

myArr.length
myArr["length"]
VarArrayHighBound(myArr,1)+1

len(myArr)
VarArrayHighBound(myArr,1)+1

UBound(myArr)+1
VarArrayHighBound(myArr,1)+1

VarArrayHighBound(myArr,1)+1

myArr[1] = 15;

myArr[1] = 15;

myArr[1] = 15

myArr(1) = 15

myArr[1] := 15;

strictEqual(x, undefined)
equal(x, aqObject.EmptyVariant)

typeof(x) == "undefined"
x == aqObject.EmptyVariant

x == aqObject.EmptyVariant

x = Empty
IsEmpty(x)
x = aqObject.EmptyVariant

x = Unassigned
x = aqObject.EmptyVariant

strictEqual(myObj, null)

myObj == null
— or —
myObj == aqObject.EmptyObject

myObj == None
— or —
myObj == aqObject.EmptyObject

myObj Is Nothing
— or —
myObj Is aqObject.EmptyObject

myObj = nil
— or —
myObj = aqObject.EmptyObject

strictEqual(myObj, null);

x == null

x == None

strictEqual(x, null)

x = nil

try
{
  Test1();
}
catch (e)
  Log.Error(e.description);

try
{
   Test1();
}
catch (e)
  Log.Error(e.description);

try:
  Test1
except:
  Log.Error(ExceptionMessage)

Err.Clear
On Error Resume Next
  Test1
If Err.Number <> 0 Then
  Log.Error Err.Description
End If

try
 Test1;
except
  Log.Error(ExceptionMessage);
end;

Differences in Basic Syntax

JavaScript

JScript, C#Script, C++Script

Python

VBScript

DelphiScript

Variant Data Types

All scripting languages supported by TestComplete use Variant-compatible data types. Variant is a universal type that can be used to store almost any kind of data: numbers, strings, date/time, true/false, references to objects, arrays and so on. All variables and parameters that you create and use in all your test projects are Variant-compatible.

For more information about Variant-compatible data types, see the following topics:

Case Sensitivity

Different scripting languages use different rules for function, variable, constant and parameter names and statements (keywords):

  • JavaScript, JScript, Python, C#Script and C++Script are case-sensitive. That is, they differentiate the letter case in names. For example, they consider Foo() and foo() as different functions.

  • VBScript and DelphiScript are case-insensitive, that is, they do not differentiate upper-case and lower-case characters in names. In these languages, for example, the names Foo() and foo() relate to the same function.

When porting code from a case-insensitive to a case-sensitive language, pay attention to the letter case in function, variable, constant and parameter names and in statements.

Routine Declarations

Routines are divided into two types - procedures and functions. A procedure is a subprogram that performs some actions but does not return any value. Whereas, a function is a subprogram that performs actions and returns the calculated result on exit. The way in which the resulting value is returned depends on the scripting language.

In JavaScript, JScript, C#Script and C++Script, both procedures and functions are declared by using the same function statement. The program instructions are enclosed in curly brackets. The function result is set via the return statement.

JavaScript, JScript

function Func1(A, B)
{
  return A+B;
}

function Test1()
{
  var str;
  Log.Message(Func1(3,4));
  str = "Done.";
  Log.Message(str);
}

C++Script, C#Script

function Func1(A, B)
{
  return A+B;
}

function Test1()
{
  var str;
  Log["Message"](Func1(3,4));
  str = "Done.";
  Log["Message"](str);
}

In Python, procedures and functions are declared by using the def statement. Program instructions are indented. The function result is set by assigning a value to a special return variable. Routine declaration requires a colon (:) after the routine name and arguments.

Python

def Func1(A, B):
  return A+B;

def Test1():
  Log.Message(Func1(3,4))
  str = "Done."
  Log.Message(str)

In VBScript, procedure instructions are enclosed in the Sub and End Sub statements. Function instructions are enclosed in the Function and End Function statements and the function result is defined by assigning a value to the function name.

VBScript

Function Func1(A, B)
  Func1 = A + B
End Function

Sub Test1()
  Dim str
  Log.Message(Func1(3,4))
  str = "Done."
  Log.Message(str)
End Sub

In DelphiScript, procedures and functions are declared via the procedure and function statements. Program instructions are enclosed in the begin and end statements. The function result is set by assigning a value to a special variable named Result. Routine declaration requires a semicolon (;) after the routine name and arguments.

DelphiScript

function Func1(A, B);
begin
  Result := A + B;
end;

procedure Test1();
  var str;
begin
  Log.Message(Func1(3,4));
  str := 'Done.';
  Log.Message(str);
end;

Comments

Comments are used to provide some remarks about the program. Another typical usage of comments is to temporally exclude some code from execution.

In JavaScript, JScript, C#Script, and C++Script, comments are denoted with two forward slashes (//). Also these scripting languages support the so called block comments: any text between the /* and */ characters is treated as a comment.

JavaScript, JScript, C#Script, C++Script

/* Multi-line
   comment */

function Func1(A, B)
{
    // Single-line comment
    Result /* In-line comment */= A + B;
}

In Python, comments are preceded by a number sign (#). The text between the number sign and the end of the line is interpreted as a comment. To create multi-line comments, each line should start with a number sign.

Python

# Multi-line
# comment 
def Func2(A, B):
  # Single-line comment 
  Result = A + B; # End of line comment

In VBScript, comments are preceded by an apostrophe (') or by the Rem keyword. The text between a apostrophe (or Rem) and the end of line is interpreted as a comment. To create multi-line comments, each line should start with an apostrophe or the Rem keyword.

VBScript

Rem Single-line comment 1
Function Func1(A, B)
   ' Single-line comment 2
   Func1 = A + B
End Function

In DelphiScript, single-line comments start with two forward slashes (//), while block comments should be enclosed in curly brackets { } or in the (* and *) characters.

DelphiScript

{ Multi-line
  comment }

(* Multi-line
  comment 2 *)

function Func1(A, B);
begin
    // Single-line comment
    Result { In-line comment 1}:= A +  (* In-line comment 2 *)B;
end;

Conditional Statements

If Statements

Conditional If-Then-(Else) constructs perform different computations or actions depending on whether the specified boolean condition evaluates to true or false. The Else branch is optional and can be omitted.

JavaScript, JScript

function IfThenElseDemo()
{
  if (Sys.OSInfo.Windows64bit)
    Log.Message("A 64-bit version of OS is installed.");
  else
    Log.Message("A 32-bit version of OS is installed.");
}

Python

def IfThenElseDemo():
  if Sys.OSInfo.Windows64bit:
    Log.Message("A 64-bit version of OS is installed.")
  else:
    Log.Message("A 32-bit version of OS is installed.")

VBScript

Sub IfThenElseDemo()
  If (Sys.OSInfo.Windows64bit) Then
    Call Log.Message("A 64-bit version of OS is installed.")
  Else
    Call Log.Message("A 32-bit version of OS is installed.")
  End If
End Sub

DelphiScript

procedure IfThenElseDemo();
begin
  if (Sys.OSInfo.Windows64bit) then
    Log.Message('A 64-bit version of OS is installed.')
  else
    Log.Message('A 32-bit version of OS is installed.');
end;

C++Script, C#Script

function IfThenElseDemo()
{
  if (Sys["OSInfo"]["Windows64bit"])
    Log["Message"]("A 64-bit version of OS is installed.");
  else
    Log["Message"]("A 32-bit version of OS is installed.");
}

Switch/Select Statements

Switch/Select statements compare a given value with the specified constants and take action according to the first constant to match.

JavaScript, JScript

function DaysInMonth(MonthNo, YearNo)
{
  switch (MonthNo)
  {
    case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
    case 2: if (aqDateTime.IsLeapYear(YearNo)) return 29; return 28;
    case 4: case 6: case 9: case 11: return 30;
  }
}

Python

def DaysInMonth(MonthNo, YearNo):
  if MonthNo == 1 or MonthNo == 3 or MonthNo == 5 or MonthNo == 7 or MonthNo == 8 or MonthNo == 10 or MonthNo == 12:
    return 31
  elif MonthNo == 2:
    if aqDateTime.IsLeapYear(YearNo):
      return 29
    else:
      return 28
  elif MonthNo == 4 or MonthNo == 6 or MonthNo == 9 or MonthNo == 11:
    return 30

VBScript

Function DaysInMonth(MonthNo,YearNo)
  Select Case MonthNo
    Case 1,3,5,7,8,10,12 DaysInMonth=31
    Case 2 If aqDateTime.IsLeapYear(YearNo) Then DaysInMonth=29 Else DaysInMonth=28
    Case 4,6,9,11 DaysInMonth=30
  End Select
End Function

DelphiScript

function DaysInMonth(MonthNo, YearNo: Integer): Integer;
begin
  case MonthNo of 
    1,3,5,7,8,10,12: Result:=31;
    2: if aqDateTime.IsLeapYear(YearNo) then Result:=29 else Result:=28;
    4,6,9,11: Result:=30;
  end;
end;

C++Script, C#Script

function DaysInMonth(MonthNo, YearNo)
{
  switch (MonthNo)
  {
    case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
    case 2: if (aqDateTime["IsLeapYear"](YearNo)) return 29; else return 28;
    case 4: case 6: case 9: case 11: return 30;
  }
}

Loops

In each of the supported scripting languages, there are several ways to repeat a set of commands.

For Loops

For loops are typically used when you need to perform some instructions for a fixed number of times. In these loops, you explicitly specify the starting and ending values of the counter. Loop instructions are executed while the counter value is going from the starting to the ending value.

JavaScript

function ForDemo()
{
  for (let i = 0; i <= 10; i++)
  {
   Log.Message(i);
  }
}

JScript

function ForDemo()
{
  for (var i = 0; i <= 10; i++)
  {
   Log.Message(i);
  }
}

Python

def ForDemo():
  for i in range (0, 10):
   Log.Message(i)
# endregion

#region WhileDemo
def WhileDemo():
  i = 0
  while i < 10: # Test finish condition 
   i+=1
   Log.Message(i)

VBScript

Sub ForDemo()
  Dim i
  For i = 0 To 10
    Log.Message(i)
  Next
End Sub

DelphiScript

procedure ForDemo();
var i;
begin
  for i := 0 to 10 do
  begin
    Log.Message(i);
  end;
end;

C++Script, C#Script

function ForDemo()
{
  for (var i = 0; i <= 10; i++)
  {
   Log["Message"](i);
  }
}

While Loops

While loops verify the finish condition before executing any instructions inside the loop. Once the finish condition resolves to true, even before the first iteration, the inside instructions will not be executed at all.

Note: If you use VBScript, you can organize a condition-controlled loop in several ways - by using the Do ... Loop and While ... Wend statements. The Do ... Loop structure is preferred, since it is more flexible and allows early exiting from loops.

JavaScript, JScript

function WhileDemo()
{
  var i = 0;
  while (i < 10) // Test finish condition
  {
   i++;
   Log.Message(i);
  }
}

Python

def WhileDemo():
  i = 0
  while i < 10: # Test finish condition 
   i+=1
   Log.Message(i)

VBScript

Sub WhileDemo()
  Dim i
  i = 0
  Do While i < 10 ' Test finish condition
   i = i + 1
   Log.Message(i)
  Loop
End Sub

DelphiScript

procedure WhileDemo();
var i;
begin
  i := 0;
  while (i < 10) do// Test finish condition
  begin
   i:=i+1;
   Log.Message(i);
  end;
end;

C++Script, C#Script

function WhileDemo()
{
  var i = 0;
  while (i < 10) // Test finish condition
  {
   i++;
   Log["Message"](i);
  }
}

Do - While Loops

Do-While loops verify the finish condition after executing the instructions inside the loop. Thus, the loop body instructions are executed at least once, even if the finish condition resolves to true.

JavaScript, JScript

function DoWhileDemo()
{
  var i = 0;
  do
  {
   i++;
   Log.Message(i);
  }
  while (i < 10) // Test finish condition
}

Python

def DoWhileDemo():
  i = 0
  while True:
    i +=1
    Log.Message(i);
    if i == 9:
      break

VBScript

Sub DoWhileDemo()
  Dim i
  i = 0
  Do
   i = i + 1
   Log.Message(i)
  Loop While (i < 10) ' Test finish condition
End Sub

Sub DoUntilDemo()
  Dim i
  i = 0
  Do
   i = i + 1
   Log.Message(i)
  Loop Until (i = 10) ' Test finish condition
End Sub

DelphiScript

procedure RepeatUntilDemo();
var i;
begin
  i := 0;
  repeat
  begin
   i:=i+1;
   Log.Message(i);
  end;
  until (i = 10); // Test finish condition
end;

C++Script, C#Script

function DoWhileDemo()
{
  var i = 0;
  do
  {
   i++;
   Log["Message"](i);
  }
  while (i < 10) // Test finish condition
}

Enumerator Loops

To iterate through child elements of an object, a special loop type is used in many scripting languages. TestComplete provides the Utils.Enumerator method that you can use to create an enumerator object in any supported scripting language. You may also use language-specific statements, such as the for statement in JavaScript and Python, the Enumerator object in JScript, C#Script or C++Script, the For Each statement in VBScript.

JavaScript

function Test()
{
  // Using language-specific enumeration statements
  for (let item of Sys)
    Log.Message(item.Name);
}

JScript

function Test()
{
  // Using language-specific enumeration statements
  var iterator = new Enumerator(Sys);
  for (; !iterator.atEnd(); iterator.moveNext())
    Log.Message(iterator.item().Name);
}

Python

def Enumerator():
  iterator = Enumerator(Sys) 
  while not iterator.AtEnd:
    Log.Message(iterator.Item.Name)
    iterator.moveNext()

VBScript

Sub Test
  Dim p

  ' Using language-specific enumeration statements
  For Each p In Sys
    Log.Message p.Name
  Next
End Sub

DelphiScript

procedure Test;
var enum;
begin
  // Using language-specific enumeration statements
  enum := Utils.Enumerator(Sys);
  while not enum.AtEnd do
  begin
    Log.Message(enum.Item.Name);
    enum.MoveNext;
  end;
end;

C++Script, C#Script

function Test()
{
  // Using language-specific enumeration statements
  var iterator = new Enumerator(Sys);
  for (; !iterator["atEnd"](); iterator["moveNext"]())
    Log["Message"](iterator["item"]()["Name"]);
}

Early Exiting From Loops

To exit a loop without evaluating the finish condition (for example, to exit an infinite loop), you can use the break statement (in JavaScript, JScript, Python, DelphiScript, C#Script and C++Script) and the Exit For or Exit Do statement (in VBScript).

JavaScript

function EarlyExitDemo()
{
  for (let i = 0; i <= 10; i++)
    {
      Log.Message(i);
      if (i==5) break;
    }
}

function EarlyExitDemo2()
{
  let i = 0;
  do
    {
     i++;
     Log.Message(i);
     if (i==5) break;
    }
  while (i < 10)
}

JScript

function EarlyExitDemo()
{
  for (var i = 0; i <= 10; i++)
    {
      Log.Message(i);
      if (i==5) break;
    }
}

function EarlyExitDemo2()
{
  var i = 0;
  do
    {
     i++;
     Log.Message(i);
     if (i==5) break;
    }
  while (i < 10)
}

Python

def EarlyExitDemo(): 
  for i in range(0, 10):
      Log.Message(i)
      if i == 5: 
        break

def EarlyExitDemo2():
  i = 0;
  while True :
    i+=1 
    Log.Message(i)
    if i == 5: 
      break

VBScript

Sub EarlyExitDemo()
  Dim i
  For i = 0 To 10
    Log.Message(i)
    If i = 5 Then Exit For
  Next
End Sub

Sub EarlyExitDemo2()
  Dim i
  i = 0
  Do
   i = i + 1
   Log.Message(i)
   If i = 5 Then Exit Do 
  Loop While i < 10
End Sub

DelphiScript

procedure EarlyExitDemo();
var i;
begin
  for i := 0 to 10 do
    begin
      Log.Message(i);
      if (i = 5) then break;
    end;
end;

procedure EarlyExitDemo2();
var i;
begin
  i := 0;
  repeat 
    begin
     Inc(i);
     Log.Message(i);
     if (i = 5) then break;
    end;
  until (i = 10);
end;

C++Script, C#Script

function EarlyExitDemo()
{
  for (var i = 0; i <= 10; i++)
    {
      Log["Message"](i);
      if (i==5) break;
    }
}

function EarlyExitDemo2()
{
  var i = 0;
  do
    {
     i++;
     Log["Message"](i);
     if (i==5) break;
    }
  while (i < 10)
}

Arrays

An array stores a collection of elements. To access the elements of an array, index notation is used.

The most frequently used arrays are one-dimensional arrays. Accessing their elements involves a single subscript which can either represent a row or the column index.

Arrays in JavaScript, JScript, C#Script and C++Script

Arrays in Python

Arrays in VBScript

Arrays in DelphiScript

Variant Arrays and Array Objects

In VBScript and DelphiScript, the array data type is treated as Variant containing an array. Whereas in JScript, C#Script and C++Script, arrays are treated as objects. In most cases, it is not important, however, some TestComplete routines accept or return data in the variant array format. To use these routines in JScript, C#Script and C++Script, you need to convert the array from one format to another. See Supported Scripting Languages - Specifics of Usage for details and conversion routines. Although in JavaScript and Python arrays are treated as objects as well, TestComplete supports their format and there is no need to convert JavaScript and Python arrays to variant array format. Also, JavaScript and Python in TestComplete can read items from variant arrays.

To create variant arrays, you can call the TestComplete built-in methods: CreateVariantArray(), CreateVariantArray2() and CreateVariantArray3().

Unassigned Data, Blank Values, Empty Objects

Each of the scripting languages has special means to denote unassigned data, objects or blank values. The following code samples demonstrate how to verify these states:

Checking Unassigned Variables

In JavaScript we recommend that you use the strictEqual method to check if a variable is unassigned (for more information see JavaScript - Specifics of Usage). In JScript, C#Script and C++Script unassigned variables belong to the special undefined data type. In Python, there are no unassigned variables, so there is no special object to check their values. In VBScript, unassigned variables belong to the special Empty data type. Also, during comparison, you can use a VBScript function named IsEmpty. In DelphiScript, an empty variant value is returned by the Unassigned function.

Besides, TestComplete has its own equivalent of an unassigned value - the aqObject.EmptyVariant property, which returns an empty variant value. This property is available in each of the supported scripting languages.

Note: Since there are no unassigned variables in Python, this method returns only True if you explicitly assigned None to the variable.

JavaScript

function VerifyUnassignedVariable()
{
  let myVar;
  if (strictEqual(myVar, undefined))
    Log.Message("The variable is not assigned yet.");
  else
    Log.Message("The variable has a value.");
}

JScript

function VerifyUnassignedVariable()
{
   var myVar;
   //if (myVar == aqObject.EmptyVariant)
   if ( typeof(myVar) == "undefined" )
     Log.Message("The variable is not assigned yet.");
   else
     Log.Message("The variable has a value.");
}

Python

def VerifyUnassignedVariable():
  myVar = None
  if myVar == aqObject.EmptyVariant:   
    Log.Message("The variable is not assigned yet.")
  else:
    Log.Message("The variable has a value.");

VBScript

Sub VerifyUnassignedVariable()
  Dim myVar
   'If myVar = aqObject.EmptyVariant Then
   'If IsEmpty(myVar) Then
   If myVar = Empty Then
     Log.Message "The variable is not assigned yet."
   Else
     Log.Message "The variable has a value."
   End If
End Sub

DelphiScript

procedure VerifyUnassignedVariable;
var myVar;
begin
   //if (myVar = aqObject.EmptyVariant) then
   if (myVar = Unassigned )then
     Log.Message('The variable is not assigned yet.')
   else
     Log.Message('The variable has a value.');
end;

C++Script, C#Script

function VerifyUnassignedVariable()
{
   var myVar;
   //if (myVar == aqObject["EmptyVariant"])
   if ( typeof(myVar) == "undefined" )
     Log["Message"]("The variable is not assigned yet.")
   else
     Log["Message"]("The variable has a value.");
}

Comparing an Object Against an Empty Object

In JavaScript, we recommend that you use the strictEqual method to compare a variable with an undefined value (for more information, see JavaScript - Specifics of Usage). In JScript, C#Script and C++Script, empty objects are interpreted as the null data type. In Python, empty objects are listed as None. In VBScript, an empty object is denoted with the Nothing keyword. Similarly, in DelphiScript, empty objects are treated as the nil constant.

TestComplete also provides the aqObject.EmptyObject property, that returns an empty object. This property is available in each of the supported scripting languages.

The sample code below checks whether the aqFileSystem.FindFiles method has returned a non-null result.

JavaScript

function FileFinder()
{
  let foundFiles, aFile;
  foundFiles = aqFileSystem.FindFiles("C:\\Work\\", "*.exe");
  if (!strictEqual(foundFiles, null))
    while (foundFiles.HasNext())
    {
      aFile = foundFiles.Next();
      Log.Message(aFile.Name);
    }
  else
    Log.Message("No files were found.");
}

JScript

function FileFinder()
{
  var foundFiles, aFile;
  foundFiles = aqFileSystem.FindFiles("C:\\Work\\", "*.exe");
  if (foundFiles != null)
    while (foundFiles.HasNext())
    {
      aFile = foundFiles.Next();
      Log.Message(aFile.Name);
    }
  else
    Log.Message("No files were found.");
}

Python

def FileFinder():
  foundFiles = aqFileSystem.FindFiles("C:\\Work\\", "*.exe");
  if (foundFiles != None):
    while foundFiles.HasNext():
      aFile = foundFiles.Next()
      Log.Message(aFile.Name)
  else:
    Log.Message("No files were found.")

VBScript

Sub FileFinder
  Set foundFiles = aqFileSystem.FindFiles("C:\Work\", "*.exe")
  If Not foundFiles Is Nothing Then
     While foundFiles.HasNext
       Set aFile = foundFiles.Next
       Log.Message aFile.Name
     Wend
  Else
      Log.Message "No files were found."
  End If
End Sub

DelphiScript

procedure FileFinder;
var foundFiles, aFile;
begin
  foundFiles := aqFileSystem.FindFiles('C:\Work\', '*.exe');
  if foundFiles <> nil then
    while foundFiles.HasNext do
    begin
      aFile := foundFiles.Next;
      Log.Message(aFile.Name);
    end
  else
    Log.Message('No files were found.');
end;

C++Script, C#Script

function FileFinder()
{
  var foundFiles, aFile;
  foundFiles = aqFileSystem["FindFiles"]("C:\\Work\\", "*.exe");
  if (foundFiles != null)
    while (foundFiles["HasNext"]())
    {
      aFile = foundFiles["Next"]();
      Log["Message"](aFile["Name"]);
    }
  else
    Log["Message"]("No files were found.");
}

Verifying That a Variable Does Not Contain Any Data

You can verify that a variable does not contain any data by assigning a special value to the variable (null in JavaScript, JScript, VBScript, C#Script, C++Script, None in Python and nil in DelphiScript). To check such a variable, you need to compare its value with the null value. Instead of direct comparison in JavaScript, we recommend that you use the strictEqual method to compare a variable with the null value. In VBScript, you should use the built-in function IsNull() (as the direct comparison varName = null resolves to null rather than to a Boolean value, null).

JavaScript

function VerifyNullValue()
{
  let myVar;
  myVar = null;
  if (strictEqual(myVar, null)) Log.Message("The variable is empty.");
}

JScript

function VerifyNullValue()
{
   var myVar;
   myVar = null;
   if (myVar == null) Log.Message("The variable is empty.");
}

Python

def VerifyNullValue():
   myVar = None 
   if myVar == None:
     Log.Message("The variable is empty.")

VBScript

Sub VerifyNullValue()
   Dim myVar
   myVar = null
   If IsNull(myVar)Then
     Log.Message "The variable is empty."
   End If
End Sub

DelphiScript

procedure VerifyNullValue();
var myVar;
begin
   myVar := nil;
   if (myVar = nil)then
     Log.Message('The variable is empty.');
end;

C++Script, C#Script

function VerifyNullValue()
{
   var myVar;
   myVar = null;
   if (myVar == null) Log["Message"]("The variable is empty.");
}

Handling Exceptions

To handle exceptions in JavaScript, JScript, C#Script and C++Script, use the try ... catch ... finally statements.

JavaScript

function ExceptionDemo()
{
  var myVar;
  try
  {
    NonExistentTest();
  }
  catch (e)
  {
    // Posts an exception message to the test log
    Log.Error(e.message);
  }
  finally
  {
    DoTheCleaning();
  }
}

JScript

function ExceptionDemo()
{
  var myVar;
  try
  {
    NonExistentTest();
  }
  catch (e)
  {
    // Posts an exception message to the test log
    Log.Error(e.description);
  }
  finally
  {
    DoTheCleaning();
  }
}

C++Script, C#Script

function ExceptionDemo()
{
  var myVar;
  try
  {
    NonExistentTest();
  }
  catch (e)
  {
    // Posts an exception message to the test log
    Log["Error"](e["description"]);
  }
  finally
  {
    DoTheCleaning();
  }
}

To handle exceptions in Python, use the try ... except ... else ... finally statement.

To obtain the exception text, you need to catch it in the except statement by using Exception as the e phrase and convert the text to a string by using the Python str() function.

Python

def ExceptionDemo():
  try:
    NonExistentTest()
  except Exception as e:
    # Posts an exception message to the test log
    Log.Error(str(e));
  else:
    # If there is no exception, runs after try, but before finally
    DoSomeThingElse()
  finally:
    DoTheCleaning()

To handle exceptions in VBScript, use the Err object and the On Error statement.

VBScript

Sub ExceptionDemo
  Err.Clear' Resets the exception indicator
  On Error Resume Next ' If an exception occurs,
                       ' TestComplete will continue running
                       ' the script
    NonExistentTest
  If Err.Number <> 0 Then
    ' An exception occurred !!!
    ' Posts the exception messages to the test log
    Log.Error Err.Description
  Else
    ' No exceptions
    Log.Message "Everything is fine."
  End If
End Sub

To handle exceptions in DelphiScript, you can use the try... except... end and try... finally... end statements.

To obtain the exception message in DelphiScript, use the ExceptionMessage function.

DelphiScript

procedure ExceptionDemo;
begin
  try
     try
      begin
        NonExistentTest();
      end;
     except
       // Posts the exception message to the test log
       Log.Error(ExceptionMessage);
     end;
  finally
    DoTheCleaning();
  end;
end;

To learn more about handling exceptions that occur in scripts and in the application under test, see the topic: Handling Exceptions in Scripts.

See Also

Script Tests
Supported Scripting Languages - Specifics of Usage
Handling Exceptions in Scripts

Highlight search results