6.5. Creating Tests by Hand

6.5.1. Modifying and Refactoring Recorded Tests
6.5.2. Creating Data Driven Tests

Now that we have seen how to record a test and modify it by inserting verification points, we are ready to see how to create tests manually. The easiest way to do this is to modify and refactor recorded tests, although it is also perfectly possible to create manual tests from scratch.

Potentially the most challenging part of writing manual tests is to use the right object names, but in practice, this is rarely a problem. We can either copy the symbolic names that Squish has already added to the Object Map when recording previous tests, or we can copy object names directly from recorded tests. And if we haven't recorded any tests and are starting from scratch we can use the Spy. We do this by clicking the Launch AUT toolbar button. This starts the AUT and switches to the Squish Spy Perspective (Section 16.1.2.1). We can then interact with the AUT until the object we are interested in is visible. Then, inside the Squish IDE we can navigate to the object in the Application Objects view and use the context menu to both add the object to the Object Map (so that Squish will remember it) and to the clipboard (so that we can paste it into our test script). And at the end we can click the Quit AUT toolbar button to terminate the AUT and return Squish to the Squish Test Management Perspective (Section 16.1.2.2). (See How to Use the Spy (Section 13.19.3) in the User Guide (Chapter 13) for more details on using the Spy.)

We can view the Object Map by clicking the Object Map toolbar button (see also, the Object Map view (Section 16.2.9)). Every application object that Squish interacts with is listed here, either as a top-level object, or as a child object (the view is a tree view). We can retrieve the symbolic name used by Squish in recorded scripts by right-clicking the object we are interested in and then clicking the context menu's Copy item. This is useful for when we want to modify existing test scripts or when we want to create test scripts from scratch, as we will see later on in the tutorial.

Squish's Object Map

6.5.1. Modifying and Refactoring Recorded Tests

Suppose we want to test the AUT's Add functionality by adding three new names and addresses. We could of course record such a test but it is just as easy to do everything in code. The steps we need the test script to do are: first click File|New to create a new address book, then for each new name and address, click Edit|Add, then fill in the details, and click OK. And finally, click File|Quit without saving. We also want to verify at the start that there are no rows of data and at the end that there are three rows. We will also refactor as we go, to make our code as neat and modular as possible.

First we must create a new empty test case. Click File|New Test Case... and set the test case's name to be tst_adding. Squish will automatically create an empty test.py (or test.js, and so on) file.

Command line users can simply create a tst_adding directory inside the test suite's directory and create and edit the test.py file (or test.js and so on) within that directory.

The first thing we need is a way to start the AUT and then invoke a menu option. Here are the first few lines from the recorded tst_general script:

Python

def main():
    startApplication("addressbook_swt")
    activateItem(waitForObjectItem(":Address Book_org.eclipse.swt.widgets.Menu", "File"))
    activateItem(waitForObjectItem(":File_org.eclipse.swt.widgets.Menu", "Open..."))

JavaScript

function main()
{
    startApplication("addressbook_swt");
    activateItem(waitForObjectItem(":Address Book_org.eclipse.swt.widgets.Menu", "File"));
    activateItem(waitForObjectItem(":File_org.eclipse.swt.widgets.Menu", "Open..."));

Perl

sub main {
    startApplication("addressbook_swt");
    activateItem(waitForObjectItem(":Address Book_org.eclipse.swt.widgets.Menu", "File"));
    activateItem(waitForObjectItem(":File_org.eclipse.swt.widgets.Menu", "Open..."));

Ruby

def main
  startApplication("addressbook_swt")
  activateItem(waitForObjectItem(":Address Book_org.eclipse.swt.widgets.Menu", "File"))
  activateItem(waitForObjectItem(":File_org.eclipse.swt.widgets.Menu", "Open..."))

Tcl

proc main {} {
    startApplication "addressbook_swt"
    invoke activateItem [waitForObjectItem ":Address Book_org.eclipse.swt.widgets.Menu" "File"]
    invoke activateItem [waitForObjectItem ":File_org.eclipse.swt.widgets.Menu" "Open..."]

Notice that the pattern in the code is simple: start the AUT, then wait for the menu bar, then activate the menu bar; wait for the menu item, then activate the menu item. In both cases we have used the waitForObjectItem function. This function is used for a multi-valued objects (such as lists, tables, trees—or in this case, a menubar and a menu), and allows us to access the object's items (which are themselves objects of course), by passing the name of the object containing the item and the item's text as arguments.

[Note]Note

It may seem a waste to put our functions in tst_adding because we could also use them in tst_general and in other test cases. However, to keep the tutorial simple we will put the code in the tst_adding test case. It is of course very easy to create shared scripts, but we defer coverage of that to the user guide. (See How to Create and Use Shared Data and Shared Scripts (Section 13.21) for how to share scripts.)

If you look at the recorded test (tst_general) or in the Object Map you will see that Squish sometimes uses different names for the same things. For example, the menubar is identified in two different ways, initially as ":Address Book_org.eclipse.swt.widgets.Table", and then later on as ":Address Book - MyAddresses.adr_org.eclipse.swt.widgets.Table". The reason for this is that Squish needs to uniquely identify every object in a given context, and it uses whatever information it has to hand. So in the case of identifying menubars (and many other objects), Squish uses the window title text to give it some context. (For example, an application's File or Edit menus may have different options depending on whether a file is loaded and what state the application is in.)

Naturally, when we write test scripts we don't want to have to know or care which particular variation of a name to use, and Squish supports this need by providing alternative naming schemes, as we will see shortly.

Once we start writing tests, sometimes the AUT will appear to freeze when we run one of our tests. When this happens, just wait for Squish to time out the AUT (about 20 seconds), and then look at the error message in the test log window. If you get an error similar to this:

Error Script Error Apr 9, 2010
Detail LookupError: Item 'New...' in object ':Address Book.adr_org.eclipse.swt.widgets.Menu' not found or ready.
Called from: C:\squish\examples\java\addressbook\suite_py\tst_adding\test.py: 18 
Location C:\squish\examples\java\addressbook\suite_py\tst_adding\test.py:3 

don't worry! It just means that Squish doesn't have an object with the given name in the Object Map. We can easily add the names we need either by recording a dummy test and interacting with all the AUT objects we plan to use in our tests or by using the Spy tool. In addition to the Spy's object picker we can also use the Spy's Application Objects view (Section 16.2.1) to locate the objects we are interested in and use the context menu to add them to the Object Map. However, recording a dummy test is often quicker for adding lots of objects to the Object Map, providing we interact with all the AUT objects we are interested in.

We've spent a bit of time on the issue of naming since it is probably the part of writing scripts that leads to the most error messages (usually of the "object ... not found" kind shown above.) Once we have identified the objects we are going to access in our tests, writing test scripts using Squish is very straightforward. And of course you can almost certainly use the scripting language you are most familiar with since Squish supports the most popular ones available.

We are now almost ready to write our own test script. It is probably easiest to begin by recording a dummy test. So click File|New Test Case... and set the test case's name to be tst_dummy. Then click the dummy test case's Record Test Case toolbar button (). Once the AUT starts, click File|New, then click the (empty) table, then click Edit|Add and add an item, then press Return or click OK. Finally, click File|Quit to finish, and say No to saving changes. Then replay this test just to confirm that everything works okay. The sole purpose of this is to make sure that Squish adds the necessary names to the Object Map since it is probably quicker to do it this way than to use the Spy for every object of interest. After replaying the dummy test you can delete it if you want to.

With all the object names we need in the Objec Map we can now write our own test script completely from scratch. We will start with the main function, and then we will look at the supporting functions that the main function uses.

Python

def main():
    startApplication("addressbook_swt")
    table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}")
    invokeMenuItem("File", "New...")
    test.compare(table.getItemCount(), 0)
    data = [("Andy", "Beach", "andy.beach@nowhere.com", "555 123 6786"),
            ("Candy", "Deane", "candy.deane@nowhere.com", "555 234 8765"),
            ("Ed", "Fernleaf", "ed.fernleaf@nowhere.com", "555 876 4654")]
    for details in data:
        addNameAndAddress(details)
    test.compare(table.getItemCount(), 3)
    closeWithoutSaving()

JavaScript

function main()
{
    startApplication("addressbook_swt");
    var table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}");
    invokeMenuItem("File", "New...");
    test.compare(table.getItemCount(), 0);
    var data = [
        ["Andy", "Beach", "andy.beach@nowhere.com", "555 123 6786"],
        ["Candy", "Deane", "candy.deane@nowhere.com", "555 234 8765"],
        ["Ed", "Fernleaf", "ed.fernleaf@nowhere.com", "555 876 4654"]];
    for (var row = 0; row < data.length; ++row)
        addNameAndAddress(data[row]);

    test.compare(table.getItemCount(), 3);
    closeWithoutSaving();
}

Perl

sub main
{
    startApplication("addressbook_swt");
    my $table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}");
    invokeMenuItem("File", "New...");
    test::compare($table->getItemCount(), 0);
    my @data = (["Andy", "Beach", "andy.beach\@nowhere.com", "555 123 6786"],
                ["Candy", "Deane", "candy.deane\@nowhere.com", "555 234 8765"],
                ["Ed", "Fernleaf", "ed.fernleaf\@nowhere.com", "555 876 4654"]);
    foreach $details (@data) {
        addNameAndAddress(@{$details});
    }
    test::compare($table->getItemCount(), 3);
    closeWithoutSaving;
}

Ruby

def main
  startApplication("addressbook_swt")
  table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}")
  invokeMenuItem("File", "New...")
  Test.verify(table.getItemCount() == 0)
  data = [["Andy", "Beach", "andy.beach@nowhere.com", "555 123 6786"],
          ["Candy", "Deane", "candy.deane@nowhere.com", "555 234 8765"],
          ["Ed", "Fernleaf", "ed.fernleaf@nowhere.com", "555 876 4654"]]
  data.each do |oneNameAndAddress|
    addNameAndAddress(oneNameAndAddress)
  end
  Test.verify(table.getItemCount() == data.length)
  closeWithoutSaving
end

Tcl

proc main {} {
    startApplication "addressbook_swt"
    set table [waitForObject "{type='org.eclipse.swt.widgets.Table' visible='true'}"]
    invokeMenuItem "File" "New..."
    test compare [invoke $table getItemCount] 0
    set data [list \
        [list "Andy" "Beach" "andy.beach@nowhere.com" "555 123 6786"] \
        [list "Candy" "Deane" "candy.deane@nowhere.com" "555 234 8765"] \
        [list "Ed" "Fernleaf" "ed.fernleaf@nowhere.com" "555 876 4654"] ]
    for {set i 0} {$i < [llength $data]} {incr i} {
        addNameAndAddress [lindex $data $i]
    }
    test compare [invoke $table getItemCount] 3
    closeWithoutSaving
}

We begin by starting the application with a call to the startApplication function. The name we pass as a string is the name registered with Squish (normally the name of the .class file that has the class which contains the main method). Then we obtain a reference to the Table. The object name we used was not put in the Object Map when the tst_general test case was recorded, so we recorded a dummy test to make sure the name was added—we could just as easily have used the Spy of course. We then copied the name from the Object Map into our code. The waitForObject function waits until an object is ready (visible and enabled) and returns a reference to it—or it times out and raises a catchable exception. We have used a symbolic name to access the table—these are the names that Squish uses when recording tests—rather than a real/multi-property name (which we will soon see an example of). It is best to use symbolic names where possible because if any AUT object name changes, with symbolic names we just have to update the Object Map (Section 15.10), without needing to change our test code.The table variable can be used to access any of the Table's public methods and properties.

The invokeMenuItem function is one we have created specially for this test. It takes a menu name and a menu option name and invokes the menu option. After using the invokeMenuItem function to do File|New, we verify that the table's row count is 0. The test.verify function is useful when we simply want to verify that a condition is true rather than compare two different values. (For Tcl we usually use the test.compare function rather than the test.verify function simply because it is slightly simpler to use in Tcl.)

Next, we create some sample data and call a custom addNameAndAddress function to populate the table with the data using the AUT's Add dialog. Then we again compare the table's row count, this time to the number of rows in our sample data. And finally we call a custom closeWithoutSaving function to terminate the application.

We will now review each of the three supporting functions, so as to cover all the code in the tst_adding test case, starting with the invokeMenuItem function.

Python

def invokeMenuItem(menu, item):
    activateItem(waitForObjectItem("{menuStyle='SWT.BAR' type='org.eclipse.swt.widgets.Menu'}", menu))
    activateItem(waitForObjectItem("{caption='%s' type='org.eclipse.swt.widgets.Menu'}" % menu, item))

JavaScript

function invokeMenuItem(menu, item)
{
    activateItem(waitForObjectItem("{menuStyle='SWT.BAR' type='org.eclipse.swt.widgets.Menu'}", menu));
    activateItem(waitForObjectItem("{caption='" + menu + "' type='org.eclipse.swt.widgets.Menu'}", item));
}

Perl

sub invokeMenuItem
{
    my($menu, $item) = @_;
    activateItem(waitForObjectItem("{menuStyle='SWT.BAR' type='org.eclipse.swt.widgets.Menu'}", $menu));
    activateItem(waitForObjectItem("{caption='$menu' type='org.eclipse.swt.widgets.Menu'}" , $item));
}

Ruby

def invokeMenuItem(menu, item)
  activateItem(waitForObjectItem(
      "{menuStyle='SWT.BAR' type='org.eclipse.swt.widgets.Menu'}", menu))
  activateItem(waitForObjectItem(
      "{caption='#{menu}' type='org.eclipse.swt.widgets.Menu'}", item))
end

Tcl

proc invokeMenuItem {menu item} {
    invoke activateItem [waitForObjectItem "{menuStyle='SWT.BAR' type='org.eclipse.swt.widgets.Menu'}" $menu]
    invoke activateItem [waitForObjectItem "{caption='$menu' type='org.eclipse.swt.widgets.Menu'}" $item]
}

As we mentioned earlier, the symbolic names Squish uses for menus and menu items (and other objects) can vary depending on the context, and often with the start of the name derived from the window's title. For applications that put the current filename in the title—such as the Address Book example—names will include the filename, and we must account for this.

In the case of the Address Book example, the main window's title is “Address Book” (at startup), or “Address Book - Unnamed” (after File|New, but before File|Save or File|Save As), or “Address Book - filename” where the filename can of course vary. Our code accounts for all these cases by making use of real (multi-property) names.

Symbolic names always begin with a colon and embed various bits of information about an object and its type. Real names are represented by a brace enclosed list of space-separated key–value pairs. Every real name must specify the type property and at least one other property. Here we've used the type and visible properties to uniquely identify the menubar, and the type and caption properties to uniquely identify the menu.

Once we have identified the object we want to interact with we use the waitForObjectItem function to retrieve a reference to it and in this case we then apply the activateItem function to it. The waitForObjectItem function pauses Squish until the specified object and its item are visible and enabled. So, here, we waited for the menu bar and one of its menu bar items, and then we waited for a menu bar item and one of its menu items. And as soon as the waiting is over each time we activate the object and its item using the activateItem function.

Python

def addNameAndAddress(details):
    invokeMenuItem("Edit", "Add...")
    for name, text in zip(("Forename", "Surname", "Email", "Phone"), details):
        type(waitForObject(":Address Book - Add.%s:_org.eclipse.swt.widgets.Text" % name), text)
    clickButton(waitForObject(":Address Book - Add.OK_org.eclipse.swt.widgets.Button"))

JavaScript

function addNameAndAddress(details)
{
    invokeMenuItem("Edit", "Add...");
    var fieldNames = ["Forename", "Surname", "Email", "Phone"];
    for (var i = 0; i < details.length; ++i)
        type(waitForObject(":Address Book - Add." + fieldNames[i] + ":_org.eclipse.swt.widgets.Text"), details[i]); 
    clickButton(waitForObject(":Address Book - Add.OK_org.eclipse.swt.widgets.Button"));
}

Perl

sub addNameAndAddress
{
    my($details) = @_;
    invokeMenuItem("Edit", "Add...");
    my @fieldNames = ("Forename", "Surname", "Email", "Phone");
    for (my $i = 0; $i < scalar(@fieldNames); $i++) {
        my $fieldName = $fieldNames[$i];
        type(waitForObject(":Address Book - Add.$fieldName:_org.eclipse.swt.widgets.Text"), $_[$i]); 
    }
    clickButton(waitForObject(":Address Book - Add.OK_org.eclipse.swt.widgets.Button"));
}

Ruby

def addNameAndAddress(oneNameAndAddress)
  invokeMenuItem("Edit", "Add...")
  ["Forename", "Surname", "Email", "Phone"].each_with_index do
    |fieldName, index|
    text = oneNameAndAddress[index]
    type(waitForObject(
	":Address Book - Add.#{fieldName}:_org.eclipse.swt.widgets.Text"), text)
  end
  clickButton(waitForObject(":Address Book - Add.OK_org.eclipse.swt.widgets.Button"))
end

Tcl

proc addNameAndAddress {details} {
    invokeMenuItem "Edit" "Add..."
    set fieldNames [list "Forename" "Surname" "Email" "Phone"]
    for {set field 0} {$field < [llength $fieldNames]} {incr field} {
        set fieldName [lindex $fieldNames $field]
        set text [lindex $details $field]
        invoke type [waitForObject ":Address Book - Add.$fieldName:_org.eclipse.swt.widgets.Text"] $text
    }
    invoke clickButton [waitForObject ":Address Book - Add.OK_org.eclipse.swt.widgets.Button"]
}

For each set of name and address data we invoke the Edit|Add menu option to pop up the Add dialog. Then for each value received we populate the appropriate field by waiting for the relevant Text to be ready and then typing in the text using the type function. And at the end we click the dialog's OK button. We got the line at the heart of the function by copying it from the recorded tst_general test and simply parameterizing it by the field name and text. Similarly, we copied the code for clicking the OK button from the tst_general test case's code.

Python

def closeWithoutSaving():
    invokeMenuItem("File", "Quit")
    closeMessageBox(":SWT", SWT.NO)

JavaScript

function closeWithoutSaving()
{
    invokeMenuItem("File", "Quit");
    closeMessageBox(":SWT", SWT.NO);
}

Perl

sub closeWithoutSaving
{
    invokeMenuItem("File", "Quit");
    closeMessageBox(":SWT", SWT::NO);
}

Ruby

def closeWithoutSaving
  invokeMenuItem("File", "Quit")
  closeMessageBox(":SWT", SWT::N_O)
end

Tcl

proc closeWithoutSaving {} {
    invokeMenuItem "File" "Quit"
    invoke closeMessageBox ":SWT" [enum SWT NO]
}

Here we use the invokeMenuItem function to do File|Quit, and then click the "save unsaved changes" dialog's No button. The last line was copied from the recorded test, but with the filename changed from "MyAddresses.adr" to "Unnamed" since in the course of the test we invoked File|New but never saved the file. (An alternative would have been to use a real (multi-property) name to identify the unsaved changes dialog's No button.)

The entire test is under 30 lines of code—and would be even less if we put some of the common functions (such as invokeMenuItem and closeWithoutSaving) in a shared script. And much of the code was copied directly from the recorded test, and in some cases parameterized.

This should be sufficient to give a flavor of writing test scripts for an AUT. Keep in mind that Squish provides far more functionality than we used here, (all of which is covered in the API Reference Manual (Chapter 14) and the Tools Reference Manual (Chapter 15)). And Squish also provides access to the entire public APIs of the AUT's objects.

However, one aspect of the test case is not very satisfactory. Although embedding test data as we did here is sensible for small amounts, it is rather limiting, especially when we want to use a lot of test data. Also, we didn't test any of the data that was added to see if it correctly ended up in the Table. In the next section we will create a new version of this test, only this time we will pull in the data from an external data source, and check that the data in the Table is correct.

6.5.2. Creating Data Driven Tests

In the previous section we put three hard-coded names and addresses in our test. But what if we want to test lots of data? One approach is to import a dataset into Squish and use the dataset as the source of the values we insert into our tests. Squish can import data in .tsv (tab-separated values format), .csv (comma-separated values format), and .xls (Microsoft® Excel™ spreadsheet format—but not .xlsx format). [6]

Test data can either be imported using the Squish IDE, or manually using a file manager or console commands. We will describe both approaches, starting with using the Squish IDE.

For the addressbook_swt application we want to import the MyAddresses.tsv data file. To do this we must start by clicking File|Import Test Resource to pop-up the Import Squish Resource dialog (Section 16.3.3). Inside the dialog click the Browse button to choose the file to import—in this case MyAddresses.tsv. Make sure that the Import As combobox is set to “TestData”. By default the Squish IDE will import the test data just for the current test case, but we want the test data to be available to all the test suite's test cases: to do this check the Copy to Test Suite for Sharing radio button. Now click the Finish button. You can now see the file listed in the Test Suite Resources view (in the Test Data tab), and if you click the file's name it will be shown in an Editor view (Section 16.2.6). The screenshot shows Squish after the test data has been added.

[Note]For command-line users

It is also possible to import test data outside the Squish IDE using a file manager (such as File Explorer) or console commands. To do this, create a directory inside the test suite's directory called shared. Now make a directory inside the shared directory called testdata. Now copy the data file (in this example, MyAddresses.tsv) into the shared\testdata directory. Now quit the Squish IDE if it is running and start it up again. If you click the Test Suite Resources view's Test Data tab you should see the data file. Click the file's name to see it in an Editor view (Section 16.2.6).

Squish with some imported test data

Although in real life we would modify our tst_adding test case to use the test data, for the purpose of the tutorial we will make a new test case called tst_adding_data that is a copy of tst_adding and which we will modify to make use of the test data.

The only function we have to change is main, where instead of iterating over hard-coded items of data, we iterate over all the records in the dataset. We also need to update the expected row count at the end since we are adding a lot more records now, and we will also add a function to verify each record that's added.

Python

def main():
    startApplication("addressbook_swt")
    table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}")
    invokeMenuItem("File", "New...")
    test.compare(table.getItemCount(), 0)
    limit = 10 # To avoid testing 100s of rows since that would be boring
    for row, record in enumerate(testData.dataset("MyAddresses.tsv")):
        forename = testData.field(record, "Forename")
        surname = testData.field(record, "Surname")
        email = testData.field(record, "Email")
        phone = testData.field(record, "Phone")
        addNameAndAddress((forename, surname, email, phone)) # pass as a single tuple
        checkNameAndAddress(table, record)
        if row > limit:
            break
    waitForObject(table)
    test.compare(table.getItemCount(), row + 1)
    closeWithoutSaving()

JavaScript

function main()
{
    startApplication("addressbook_swt");
    var table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}");
    invokeMenuItem("File", "New...");
    test.compare(table.getItemCount(), 0);
    var limit = 10; // To avoid testing 100s of rows since that would be boring
    var records = testData.dataset("MyAddresses.tsv");
    var row = 0;
    for (; row < records.length; ++row) {
        var record = records[row];
        var forename = testData.field(record, "Forename");
        var surname = testData.field(record, "Surname");
        var email = testData.field(record, "Email");
        var phone = testData.field(record, "Phone");
        addNameAndAddress([forename, surname, email, phone]);
        checkNameAndAddress(table, record);
        if (row > limit)
            break;
    }
    waitForObject(table);
    test.compare(table.getItemCount(), row + 1);
    closeWithoutSaving();
}

Perl

sub main
{
    startApplication("addressbook_swt");
    my $table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}");
    invokeMenuItem("File", "New...");
    test::compare($table->getItemCount(), 0);
    my $limit = 10; # To avoid testing 100s of rows since that would be boring
    my @records = testData::dataset("MyAddresses.tsv");
    my $row = 0;
    for (; $row < scalar(@records); $row++) {
        my $record = $records[$row];
        my $forename = testData::field($record, "Forename");
        my $surname = testData::field($record, "Surname");
        my $email = testData::field($record, "Email");
        my $phone = testData::field($record, "Phone");
        addNameAndAddress($forename, $surname, $email, $phone);
        checkNameAndAddress($table, $record);
        if ($row > $limit) {
            last;
        }
    }
    test::compare($table->getItemCount(), $row + 1);
    closeWithoutSaving;
}

Ruby

def main()
  startApplication("addressbook_swt")
  table = waitForObject("{type='org.eclipse.swt.widgets.Table' visible='true'}")
  invokeMenuItem("File", "New...")
  Test.verify(table.getItemCount() == 0)
  limit = 10 # To avoid testing 100s of rows since that would be boring
  rows = 0
  TestData.dataset("MyAddresses.tsv").each_with_index do
      |record, row|
    forename = TestData.field(record, "Forename")
    surname = TestData.field(record, "Surname")
    email = TestData.field(record, "Email")
    phone = TestData.field(record, "Phone")
    addNameAndAddress([forename, surname, email, phone]) # pass as a single Array
    checkNameAndAddress(table, record)
    break if row > limit
    rows += 1
  end
  Test.verify(table.getItemCount() == rows + 1)
  closeWithoutSaving
end

Tcl

proc main {} {
    startApplication "addressbook_swt"
    set table [waitForObject "{type='org.eclipse.swt.widgets.Table' visible='true'}"]
    invokeMenuItem "File" "New..."
    test compare [invoke $table getItemCount] 0
    set limit 10
    set data [testData dataset "MyAddresses.tsv"]
    set columns [llength [testData fieldNames [lindex $data 0]]]
    set row 0
    for {} {$row < [llength $data]} {incr row} {
        set record [lindex $data $row]
        set forename [testData field $record "Forename"]
        set surname [testData field $record "Surname"]
        set email [testData field $record "Email"]
        set phone [testData field $record "Phone"]
        set details [list $forename $surname $email $phone]
        addNameAndAddress $details
        checkNameAndAddress $table $record
        if {$row > $limit} {
            break
        }
    }
    test compare [invoke $table getItemCount] [expr $row + 1]
    closeWithoutSaving
}

Squish provides access to test data through its testData module's functions—here we used the testData.dataset function to access the data file and make its records available, and the testData.field function to retrieve each record's individual fields.

Having used the test data to populate the Table we want to be confident that the data in the table is the same as what we have added, so that's why we added the checkNameAndAddress function. We also added a limit to how many records we would compare, just to make the test run faster.

Python

def checkNameAndAddress(table, record):
    waitForObject(table)
    item = table.getItem(0) # new rows are always inserted at row 0
    for column in range(len(testData.fieldNames(record))):
        value = item.getText(column)
        test.compare(value, testData.field(record, column))

JavaScript

function checkNameAndAddress(table, record)
{
    waitForObject(table);
    var item = table.getItem(0); // new rows are always inserted at row 0
    for (var column = 0; column < testData.fieldNames(record).length; ++column) {
        var value = item.getText(column);
        test.compare(value, testData.field(record, column));
    }
}

Perl

sub checkNameAndAddress
{
    my($table, $record) = @_;
    waitForObject($table);
    my $item = $table->getItem(0); # new rows are always inserted at row 0
    my @columnNames = testData::fieldNames($record);
    for (my $column = 0; $column < scalar(@columnNames); $column++) {
        my $value = $item->getText($column);
        test::compare($value, testData::field($record, $column));
    }
}

Ruby

def checkNameAndAddress(table, record)
  item = table.getItem(0) # new rows are always inserted at row 0
  for column in 0...TestData.fieldNames(record).length
    Test.compare(item.getText(column), TestData.field(record, column))
  end
end

Tcl

proc checkNameAndAddress {table record} {
    waitForObject $table
    set item [invoke $table getItem 0]
    set columns [llength [testData fieldNames $record]]
    for {set column 0} {$column < $columns} {incr column} {
        set value [invoke $item getText $column]
        test compare $value [testData field $record $column]
    }
}

This function accesses individual items in the Table. We then use Squish's test.compare function to check that the value in the cell is the same as the value in the test data we used. Note that this particular AUT always adds a new row before the current row (or as the first row if there are no rows yet), and always makes the added row the current row. The effect of this is that every new name and address is always added as the first row, and this is why we hard-coded the row to be 0.

The screenshot show Squish's Test Summary log after the data-driven tests have been run.

Squish after a successful data-driven test run

Squish can also do keyword-driven testing. This is a bit more sophisticated than data-driven testing. See How to Do Keyword-Driven Testing (Section 13.14).




[6] Both .csv and .tsv files are assumed to use the Unicode UTF-8 encoding—the same encoding used for all test scripts.