ZK Testing with Selenium IDE fr

From Documentation
DocumentationSmall Talks2013JulyZK Testing with Selenium IDE fr
ZK Testing with Selenium IDE fr

Author
Robert Wenzel, Engineer, Potix Corporation
Date
July 30, 2013
Version
ZK 6.5 (or later)


Introduction

Vous avez donc votre chouette application ZK et vous aimeriez maintenant être de certain qu'elle va fonctionner correctement sur différents navigateurs (et continuera de fonctionner après de changements, ce qui survient souvent de nos jours...). Vous avez bien entendu testé tout ce qui était possible avec votre test unitaire et des tests d'intégration ;-). Vous avez essayé toutes les possibilités offertes par ZATS pour avoir la certitude que vos composants ZK fonctionnent correctement ensemble dans un environnement simulé.

Vous en arrivez donc finalement au point de vouloir garantir le bon fonctionnement de votre application (ou au moins les éléments essentiels de celle-ci) dans un environnement réel (avec d'autres navigateurs, serveur réel d'applications, trafic et latence réseaux réels etc.) - alors, Selenium entre en jeux.

À propos de cet article

Différentes approches existent pour créer des tests avec Selenium:

Par programmation - méthode préférée des développeurs - est déjà développée dans ce Small Talk. Cette méthode vous offre un contrôle maximum sur l'exécution du test et vous permet d'écrire des tests réutilisables, flexibles, facile à mettre à jour et même des cas "intelligents". Bien sure, pour écrire de tels tests, il faut du temps et des ressources.

Il arrive parfois qu'une personne ayant un profil moins technique doive écrire ces tests. On entend alors souvent parler d'outils "record and replay". Selenium IDE possède cette caractéristique "record and replay" mais aussi beaucoup d'autres options adapter et étendre les tests après enregistrement. Dans de raraes cas, les tests enregistrés peuvent être rejoués de façon instantanée. Cependant, particulièrement avec AJAX, certains éléments vont permettre d'éviter l'exécution de vos tests hors carde.

Voici deux exemples (et vous pouvez facilement en trouver d'autres):

  • problèmes avec Missing clicks
  • quel'qu'un a enregistré ceci video qui explique quelques problèmes

Mais pas de panique, cet article va vous expliquer comment gérer ces cas!

La conclusion majeure est: Voyez plutôt Selenium IDE comme un outil d'enregistrement/adaptation/maintenance et de ré-exécution/débogage lorsque vous construisez vos tests.

Cet article va montrer (via une application web exemple) comment:

  • autoriser un enregistrement de test initial dans ZK
  • adapter les tests pour pouvoir les rejouer
  • garder vos tests maintenables et robustes face aux changements dans vos pages
  • ajouter les actions manquantes

Nombre d'idées dans cet article sont basées sur des solutions à des problèmes généraux depuis certains forums et aussi l'expérience des projets passés. Certaines sont simplement le reflet de mes préférences personnelles sur la manière de gérer les choses. Cet article ne montre pas une manière unique d'écrire des tests pour des applications ZK mais met juste en évidence des problèmes et des solutions, discute de certains considérations prises, et explique pourquoi cette approche a été choisie.

Bonne lecture et n'hésitez pas à commenter !!

Environment

  • Firefox 22
  • Selenium IDE 2.1.0 (Selenium IDE 2.0.0 ne fonctionne pas avec FF >=22)
  • JDK 6/7
  • ZK 6.5.3
  • Maven 3.0

Étapes

Initialisez votre environnement pour cet exemple

  • Installez le plugin Selenium IDE dans Firefox via Addons ou download documentation page
  • Maven 3.0 download & install
  • download le projet exemple, il contient les dossiers suivants:
    • selenium_example/ (l'application exemple, le projet maven)
    • extensions/ (les extension selenium utilisées dans cet article)
    • test_suite/ (une suite de tests Selenium illustrant les concepts discutés ici)
  • lancez depuis une ligne de commande
cd selenium_example_app
mvn jetty:run
ou exécutez selenium_testing_app/launch_for_PROD.bat / .sh

Situation initiale

  1. Lancez Firefox
  2. Lancez Selenium IDE CTRL+ALT+S
  3. Mettez l'URL de base à "http://localhost:8080/"
  4. Ouvrez l'application exemple http://localhost:8080/selenium_testing
  5. Enregistrez le login-test et essayez de le ré-exécuter
New Test
open /selenium_testing/login.zul
type id=jXDW5 test
type id=jXDW8 test
clickAndWait id=jXDWb

Cela parait difficile à lire / maintenir et ne fonctionne même pas :'(

En jetant un coup d’œil aux commandes enregistrées et en comparant les IDs à la page source, nous remarquons que ces derniers sont générés et changés à chaque rafraîchissement de la page. Aucune chance donc d'enregistrer / rejouer de cette manière.

Une manière de rendre les IDs prévisibles est montrée dans la section suivante.

Générateur d'ID sur mesure

Comme mentionnée dans l'autre Small Talks sur les tests, une stratégie est d'utiliser une implémentation d'un générateur d'ID sur mesure pour créer des ID's de composants qui soient prévisibles, lisibles (avec un nom business) et facilement sélectionnable par selenium.

public class TestingIdGenerator implements IdGenerator {

	public String nextComponentUuid(Desktop desktop, Component comp,
			ComponentInfo compInfo) {
        int i = Integer.parseInt(desktop.getAttribute("Id_Num").toString());
        i++;// Start from 1
        
        StringBuilder uuid = new StringBuilder("");
        
        desktop.setAttribute("Id_Num", String.valueOf(i));
        if(compInfo != null) {
        	String id = getId(compInfo);
        	if(id != null) {
        		uuid.append(id).append("_");
        	}
        	String tag = compInfo.getTag();
        	if(tag != null) {
        		uuid.append(tag).append("_");
        	}
        }
        return uuid.length() == 0 ? "zkcomp_" + i : uuid.append(i).toString();
    }

Les IDs ressembleront à ceci:

  • {id}_{tag}_{##} (pour les composants avec un id donné)
  • {tag}_{##} (pour les composants sans id donnée - p.e. listitems dans une listbox)
  • {zkcomp}_{##} (pour les autres cas, histoire simplement de les rendre uniques)

p.e. un bouton dans un fichier zul

<button id="login" label="login" />

deviendra quelque chose comme ceci en HTML dans un navigateur (le nombre peut varier):

<button id="login_button_12" class="z-button-os" type="button">login</button>

Pour séparer la production de la configuration test, on peut inclure un ficher de config supplémentaire au démarrage pour autoriser le TestingIdGenerator uniquement dans les tests. Avec Zk, ceci est possible en configurant la propriété de librairies org.zkoss.zk.config.path (voir aussi notre Testing Tips)

p.e. via l'arguement VM -Dorg.zkoss.zk.config.path=/WEB-INF/zk-test.xml

Windows:

set MAVEN_OPTS=-Dorg.zkoss.zk.config.path=/WEB-INF/zk-test.xml
mvn jetty:run

Linux:

export MAVEN_OPTS=-Dorg.zkoss.zk.config.path=/WEB-INF/zk-test.xml
mvn jetty:run

ou exécutez selenium_testing_app/launch_for_TEST.bat / .sh


On a maintenant des ID's déterminés lors de l'enregistrement d'un test.

Après l'enregistrement, on relance le test et on obtient ceci:

login test
open /selenium_testing/login.zul
type id=username_textbox_6 test
type id=password_textbox_9 test
clickAndWait id=login_button_12

Ça parait déjà mieux et ça s'explique de sois-même, mais malheureusement cela no fonctionne toujours pas si on le relance.

Pourquoi cela se passe-t-il et comment le régler ? Voyons la section suivante ...

Détails spécifiques à ZK

Vu la nature des applications web riches, JavaScript est souvent très utilisé mais Selenium IDE n'enregistre pas par défaut tous les événements. Dans notre cas, les événements "blur" des champs d'entrée n'ont pas été enregistrés alors que ZK se base sur eux pour déterminer les champs mis à jour. On doit donc ajouter manuellement la commande selenium "fireEvent target blur". Selenium n'offre malheureusement pas d'équivalente à "focus".

login test
open /selenium_testing/login.zul
type id=username_textbox_6 test
fireEvent id=username_textbox_6 blur
type id=password_textbox_9 test
fireEvent id=password_textbox_9 blur
clickAndWait id=login_button_12
assertLocation */selenium_testing/index.zul
verifyTextPresent Welcome test
verifyTextPresent Feedback Overview

Si on relance le script, maintenant cela fonctionne :D et on voit la page overview (on a aussi ajouté quelques vérifications pour cela).

Extensions Selenium

Si vous avez le sentiment qu'il est difficile de se souvenir de la syntaxe de "fireEvent" ou si vous pensez qu'il est trop compliqué d'ajouter une ligne additionnelle juste pour mettre à jour un champ d'entrée, utiliser une Selenium Core extension peut vous aider. Le fichier d'extension, généralement appelé user-extensions.js peut être utilisé par Selenium IDE et par Selenium RC lorsque les tests se font en dehors de Selenium IDE (merci de vous référer à selenium documentation).

L'extrait suivant montrent deux actions simples:

blur
pratique pour éviter "fireEvent locator blur"
typeAndBlur
combine le type avec un événement blur, pour rendre ZK attentif aux changement de la valeur entrée
Selenium.prototype.doBlur = function(locator) {
    // All locator-strategies are automatically handled by "findElement"
    var element = this.page().findElement(locator);
    // Fire the "blur" event
    this.doFireEvent(locator, "blur")
};

Selenium.prototype.doTypeAndBlur = function(locator, text) {
    // All locator-strategies are automatically handled by "findElement"
    var element = this.page().findElement(locator);

    // Replace the element text with the new text
    this.page().replaceText(element, text);
    // Fire the "blur" event
    this.doFireEvent(locator, "blur")
};

Pour l'activer, ajoutez le fichier (extensions/user-extension.js dans le zip de l'exemple) à la configuration de Selenium IDE. (le fichier contient une autre extension ... voir custom locators)

(Selenium IDE Options > Options... > [General -Tab] > Selenium Core extensions)

Redémarrez ensuite Selenium IDE - fermez la fenêtre et rouvrez-la - p.e. avec [CTRL+ALT+S]

Test adapté qui utilise l'action blur:

login test
open /selenium_testing/login.zul
type id=username_textbox_6 test
blur id=username_textbox_6
type id=password_textbox_9 test
blur id=password_textbox_9
clickAndWait id=login_button_12

Même test en utilisant typeAndBlur:

login test
open /selenium_testing/login.zul
typeAndBlur id=username_textbox_6 test
typeAndBlur id=password_textbox_9 test
clickAndWait id=login_button_12

Il n'est pas nécessaire d'utiliser l'une de ces extensions mais ma préférence personnelle va à l'économie d'une ligne pour chaque entrée.

Une autre chose à garder à l'esprit est le manque de robustesse et l'effort de maintenance à fournir pour les tests quand des changements apparaissent dans l'UI ... les numéros générés à la fin de chaque ID restent un obstacle parce qu'ils sont sujets à changer chaque fois qu'un composant est ajouté ou retiré au dessus de ce composant.

Ne serait-il pas sympa de n'avoir à adapter aussi souvent les tests ? Voyons la suite...

Améliorer la robustesse et la maintenance

Locators dans Selenium

Pour enlever les nombres hard codés des ID composants de notre test, Selenium offre p.e. XPath ou CSS locators.

En utilisant XPath, est-il possible de sélectionner un nœud à l'aide de son préfixe ID ?:

//input[starts-with(@id, 'username_')]

Cela va fonctionner tant que le préfixe "username_" est unique sur la page, sans quoi l'action sera exécutée sur le premier élément trouvé. C'est donc une bonne idée, dans ce scénario, de donner aux widgets des ID appropriés (plus: cela va aussi augmenter la lisibilité du code source).

Dans des cas plus complexes, on peut sélectionner des composants imbriqués pour distinguer les composants avec le même ID (p.e. dans des espaces ID différents). p.e. si le composant "street" apparaît plusieurs fois sur la page, utilisez ceci:

//div[starts-with(@id, 'deliveryAddress_')]//input[starts-with(@id, 'street_')]
//div[starts-with(@id, 'billingAddress_')]//input[starts-with(@id, 'street_')]

Un autre exemple pour localiser le bouton "delete" dans la ligne sélectionnée d'une listbox qui utilise des préfixes ID, CSS-class et comparaison de texte.

//div[starts-with(@id, 'overviewList_')]//tr[contains(@class, 'z-listitem-seld')]//button[text() = 'delete']

NOTE: Veillez à ne pas utiliser l'opérateur "//" de façon trop extensive dans XPath, cela pourrait ne pas fonctionner (cela n'a jamais été un problème pour moi jusqu’à présent vu qu'il y a des goulots d’étranglement bien pire en terme de performance qui affectent la vitesse d'exécution de votre test - voir plus tard).

Ce lien sheet provided by Michael Sorens est un excellente référence avec plein d'exemples utiles sur comment sélectionner des éléments de page dans diverses situations.

On peut donc maintenant changer le test pour utiliser cette sorte de XPath locator, en cherchant uniquement avec le préfixe ID:

login test
open /selenium_testing/login.zul
typeAndBlur //input[starts-with(@id, 'username_')] test
typeAndBlur //input[starts-with(@id, 'password_')] test
clickAndWait //button[starts-with(@id, 'login_')]

Ceci fait, l'ordre des composants peut changer sans casser le test, tant que les IDs ne sont pas changés. Ceci requirt bien entendu un peu de travail manuel mais l'effort investi une fois payera rapidement au cours de l'évolution des votre projet.

Custom Locator et LocatorBuilder

Si vous ne voulez pas changer le locator vers XPath de façon manuelle à chaque fois que vous enregistre un test, Selenium IDE vous offre une solution qui va encore augmenter la lisibilité.

Custom Locator

Dans le user-extensions.js d'ici plus haut, vous allez trouver un custom locator qui va cacher une partie de la complexité de XPath pour des scénarios simples. C'est basé sur le format des IDs générés par TestingIdGenerator (voir plus haut).
// The "inDocument" is the document you are searching.
PageBot.prototype.locateElementByZkTest = function(text, inDocument) {
    // Create the text to search for
	
    var text2 = text.trim();

	var separatorIndex = text2.indexOf(" ");
	
	var elementNameAndIdPrefix = (separatorIndex != -1 ? text2.substring(0, separatorIndex) : text2).split("#");
	var xpathSuffix = separatorIndex != -1 ? text2.substring(separatorIndex + 1) : "";
	
	var elementName = elementNameAndIdPrefix[0] || "*";
	var idPrefix = elementNameAndIdPrefix[1];

	var xpath = "//" + elementName + "[starts-with(@id, '" + idPrefix + "')]" + xpathSuffix;

    return this.xpathEvaluator.selectSingleNode(inDocument, xpath, null, this._namespaceResolver);
};

Ce locator va travailler selon 2 formes

1. zktest=#login_
2. zktest=input#username_

XPaths généré/questionné en interne sera

1. //*[starts-with(@id, 'login_')]
2. //input[starts-with(@id, 'username_')]
  1. cherchera les éléments dont l'ID commence par "login_"
  2. testera aussi les éléments avec tag html, et trouvera l'élément <input> avec le préfixe ID "username_..."

De plus, il est possible de joindre n'importe quel XPath supplémentaire pour affiner les résultats.

p.e. (pour localiser la deuxième option d'un élement <select>)

zktest=select#priority_ /option[2]

deviendra dans XPath

//select[starts-with(@id, 'priority_')]/option[2]

Même si ce locator est très basique (peut être étendu si besoin), il augmente déjà la lisibilité de nombreux use-cases.

Custom LocatorBuilder

Pour rendre ceci très maniable, Selenium IDE offre aussi des extensions (ne pas mélanger avec Selenium Core Extension)

Ajoutez le ficher extension IDE extensions/zktest-Selenium-IDE-extension.js depuis example.zip à la config selenium

(Selenium IDE Options > Options... > [General -Tab] > Selenium IDE extensions)

et déplacez le vers le haut dans la liste de priorités du Locator Builder.

(Selenium IDE Options > Options... > [Locator Builders - Tab])

Il contient le LocatorBuilder suivant qui va générer le locator dans la forme "zktest=elementTag#IdPrefix" mentionnée ci-dessus en utilisant uniquement la première partie de l'ID (le préfixe ID - son nom business). Si un ID ne contient pas 3 tokens séparés par "_", il utilisera l'ID complet à la plac en incluant le numéro séquentiel. Ceci indiquera que l'élément n'a pas d'ID spécifié et une autre approche de localisation peut être meilleure, ou donnez lui juste un ID dans le fichier zul.

 
LocatorBuilders.add('zktest', function(e) {
	var idTokens = e.id.split("_")
	if (idTokens.length > 2) {
		idTokens.pop();
		idTokens.pop();
		return "zktest=" + e.nodeName.toLowerCase() + "#" + idTokens.join("_") + "_";
	} else {
		return "zktest=" + "#" + e.id;
	}
	return null;
});

Redémarrez Selenium IDE et enregistrez le test à nouveau... vous aurez ceci (après avoir changé les événements de type à typeAndBlur).

New Test
open /selenium_testing/login.zul
typeAndBlur zktest=input#username_ test
typeAndBlur zktest=input#password_ test
clickAndWait zktest=button#login_

More Tests

Let's record a test case for editing and saving an existing "feedback item" in the list, verify the results, and a logout test. These tests introduce new challenges testing an ajax applications with Selenium - and their solution or workarounds.

Now that we are actually changing data I adapted the login test, to use a random user each time. So that the Mock implementation will serve fresh data for each test run, without having to restart the server, or having to cleanup (there are other strategies possible to do the same - that's just what I use here).

login test
store javascript{'testUser'+Math.floor(Math.random()*10000000)} username
open /selenium_testing/login.zul
typeAndBlur zktest=input#username_ ${username}
typeAndBlur zktest=input#password_ ${username}
clickAndWait zktest=button#login_
assertLocation */selenium_testing/index.zul
verifyTextPresent logout ${username}

Edit and Save Test

After recording and applying the typeAndBlur actions we get the following.

edit save test
open /selenium_testing/index.zul
click zktest=#button_27
typeAndBlur zktest=input#subject_ Subject 1 (updated)
typeAndBlur zktest=input#topic_ consulting
select zktest=select#priority_ label=low
click zktest=#listitem_62
typeAndBlur zktest=textarea#comment_ test comment (content also updated)
click zktest=button#submit_
assertTextPresent Feedback successfully updated
verifyTextPresent subject=Subject 1 (updated)
verifyTextPresent [text=test comment (content also updated)]
verifyTextPresent priority=low
click zktest=button#backToOverview_
assertTextPresent Feedback Overview

We still see some hard-coded numbers. I'll just delete the "click zktest=#listitem_62" as the "select" will command will just do fine (Selenium IDE will sometimes record more than you need, and sometimes not enough - by default).

Interesting for now is the locator "zktest=#button_27" - one of the the "edit" button. If we try to give it an ID in the zul code it will fail to render (duplicate ID), because the button is rendered multiple times - once for each <listitem>. (one workaround could be to surround it by an <idspace> component or include the buttons from a different file). But it is not necessary - using the right locator XPath.

Locating an Element inside a Listbox

If you just want to locate the first edit button in the list you can use (it will find the button by its text and not by its ID):

pure XPath:

//*[starts-with(@id, 'overviewList_')]//button[text() = 'edit']

or combine with the "zktest" selector from the selenium extension above

zktest=#overviewList_ //button[text() = 'edit']

more interesting is it to locate by index, e.g. exactly the second edit button

xpath=(//*[starts-with(@id, 'overviewList_')]//button[text() = 'edit'])[2]

or even more fun to select the "edit" button inside a <listitem> containing a specific text in a cell

xpath=//*[starts-with(@id, 'overviewList_')]//*[starts-with(@id, 'listitem_')][.//*[starts-with(@id, 'listcell_')][text() = 'Subject 2']]//button[text() = 'edit']

This can get infinitely complex, and reduce the readability of your testcase. That's why it is also a good idea to write comments (see screenshot below) in your test case (yes, test cases can have comments too).

Even though complex this last locator is still quite stable to changes in the UI. Especially when the <listbox> content changes, you can still use it to find the same <listitem> (and its contained button) several times in a test case.

Using Variables

Repeating those complex locators in the test scripts will give you a headache maintaining them, when e.g. the label of the button changes from "edit" to "update". It is better to "store" locator strings or parts of them in variables, which can be reused throughout the test.

variables and comments example

These are just a few general ideas, about what can be done to reduce the work in maintaining test cases, increasing stability or make them more readable - at reasonable investment when setting them up (recording and adjusting) initially.

Waiting for AJAX

However rerunning the test suite at full speed (which is what we should always aim for) will or may sometimes - fail, because we don't wait long enough for ajax responses to render... there is no full page reload so Selenium IDE does not wait automatically.

An idea might be to reduce the test speed... which would affect every step in all test cases, so we try to avoid that. Also in our feedback example there is a longer operation when clicking the "submit" button (2 seconds). Delaying every Step by 2 seconds would be devastating for our overall replay duration.

Another possibility is using the pause command and specify the number of milliseconds to wait. Also here the execution speed might vary so we are either waiting too short, so that errors still occur, or we wait too long ("just to be sure") and waste time - both not desirable.

Luckily Selenium comes with a variety of waitFor... actions, which stops the execution until a condition is met. A useful subsection is:

  • waitForTextPresent - wait until a text is present anywhere on the page
  • waitForText - wait until an element matching a locator has the text
  • waitForElementPresent - wait until an element matched by a locator becomes rendered
  • waitForVisible - wait until an element matched by a locator becomes visible

The previously recorded "edit save test" would likely fail in line 3 just after the click on the edit button. Between Step 2 and 3 ZK is updating parts of the page using AJAX, causing a short delay (but long enough for our test to fail - when running at full speed).

edit save test
open /selenium_testing/index.zul
click zktest=#overviewList_ //button[text() = 'edit']
typeAndBlur zktest=input#subject_ Subject 1 (updated)
typeAndBlur zktest=input#topic_ consulting
select zktest=select#priority_ label=low
typeAndBlur zktest=textarea#comment_ test comment (content also updated)
click zktest=button#submit_
assertTextPresent Feedback successfully updated
... ... ...

So we have to wait e.g. until the new Headline "New/Edit Feedback" is present that the AJAX update has finished. And wait after submitting the feedback article accordingly - replace the "assertTextPresent" with "waitForTextPresent". Also the last assert... can be replaced.

edit save test
open /selenium_testing/index.zul
click zktest=#overviewList_ //button[text() = 'edit']
waitForTextPresent New/Edit Feedback
typeAndBlur zktest=input#subject_ Subject 1 (updated)
typeAndBlur zktest=input#topic_ consulting
select zktest=select#priority_ label=low
typeAndBlur zktest=textarea#comment_ test comment (content also updated)
click zktest=button#submit_
waitForTextPresent Feedback successfully updated
verifyTextPresent subject=Subject 1 (updated)
verifyTextPresent [text=test comment (content also updated)]
verifyTextPresent priority=low
click zktest=button#backToOverview_
waitForTextPresent Feedback Overview

Now this test can run as fast as possible adapting automatically, to any speedup, or slowdown of the test server.

It is also possible to implicitly wait in general for AJAX to finish at a technical level [covered here]. Personally I think it is tempting at first. After a second thought, I prefer the idea to explicitly wait (via waitForXXX) for your expected results - only when there is need to wait.

Like that you find out directly that something on your page has affected the performance (= user experience) - in case the test suddenly fails after a change affecting the responsiveness of your application.

Additionally, there might be another delay after the AJAX response has finished, until the expected component is finally rendered on the page or visible (e.g. due to an animation). So this approach may still fail - just bear that in mind.

Logout Test

This test should be very simple, but still there is a catch. When trying to record this test, we notice that Seleniume-IDE won't record clicking on the logout button. Selenium IDE is not very predictable about which events are recorded and which are ignored. In this case the it is a <toolbarbutton> which is rendered as a <div> so maybe that's why.

(There is a [stackoverflow question about this] and also an [IDE extension] available to enable recording of ALL clicks in a test. I tried this one - and didn't like the big number of clicks recorded. In the end I leave it up to you to uncomment this in the IDE extension for Locator Builder provided above and judge yourself - maybe you want to test exactly this.)

As we know its name (or we can easily find out with tools like firebug) we just add another click event manually and change the locator to "zktest=div#logout_"

logout test
click zktest=div#logout_
waitForTextPresent Login (with same username as password)
assertLocation */selenium_testing/login.zul

Other Components Examples

Other components require some extra attention too when recording events on them (sometimes you might wonder why the results are varying). So here are just a few examples.

Button (mold="trendy")

The "new/edit page" of the example application contains 2 submit buttons - rendered using different molds: "default" and "trendy". Both have the same effect (save the feedback item). When you try to record the click event of the second one - labelled "submitTrendy" - Selenium IDE just ignores the click.

Funny thing is, when you first focus another window on your desktop and then click the button directly - without prior focusing the browser window - it gets recorded. But our custom locator builder does not match here. So we get some other generic locator strings. (The "trendy" button is rendered using a layout table and images for the round corners.)

button trendy recorded locator

The second choice contains the component ID, we can use to build our own locator string.

zktest=#submitTrendy_

This would usually be sufficient but not in this example. When we test it, clicking on the "Find" button in Selenium IDE we see it is selecting the whole cell around it. ZK has generated some html elements of the layout grid around our button sharing the same ID prefix. Inspecting the element in the browser we can see the element we really want to click and that it is an element with a style class "z-button"

<span id="submitTrendy_button_129" class="z-button">

So a more specific locator would look like this

zktest=span#submitTrendy_

or that

zktest=#submitTrendy_ [@class = "z-button"]

equivalent XPaths are:

//span[starts-with(@id, 'submitTrendy_')]
//*[starts-with(@id, 'submitTrendy_')][@class="z-button"]

Menu

Recording events on a <menubar> (even with submenus) is generally very simple. Unless you click the "wrong" areas while recording highlighted in red see image below. If you just click the menu(item)-texts (green) Selenium IDE will create nice locators, otherwise it will fallback to some other strategy, using CSS or generated XPath which might surprise you (this is no bug in Selenium IDE, it is just a different html element receiving the click event).

menu test (not working for us)
click css=td.z-menu-inner-m > div
click css=span.z-menuitem-img

avoid red areas, and click on the green areas

What you get avoiding the red areas.

menu test (what we want)
click zktest=button#feedbackMenu_
click zktest=a#newFeedbackMenuItem_

Tabbox

When all your <tab>s and <tabpanel>s (and nested components) have unique IDs everything is simple, but when it comes to dynamically added tabs without nice Ids things get a bit tricky.

So in our example some manual work is required to record interactions with the "comments" tabbox.

The "new comment"-button is again a toolbarbutton like the "logout"-button, so its events are not recorded automatically to create a new comment-tab just add this "click zktest=div#newComment_" manually will create a new tab. Now how to activate the new tab (Comment 1).

Locating a Tab

Automatic recording will give us this, which will work for now, and fail again after a change to the page.

click zktest=#tab_261-cnt

To avoid the hard-coded index, and truly being sure the second tab (inside our comments tabbox) is selected I would prefer this

//div[starts-with(@id, 'comments_')]//li[starts-with(@id, 'tab_')][2]

or (locating by label)

//div[starts-with(@id, 'comments_')]//li//span[text() = 'Comment 1']

It could be simplified increasing the chance of possible future failure (if there is another li inside the "comments" tabbox) using the custom zktest locator

zktest=div#comments_ //li//span[text() = 'Comment 1']

Locating a Tabpanel

Locating e.g. the <textarea> to edit the comment of the currently selected tab is somewhat more difficult, as the <tabpanels> component is not in the same branch of the Browser-DOM tree as the <tabs> component.

Easiest is to locate by index (if you know it):

//div[starts-with(@id, 'comments_')]//div[starts-with(@id, 'tabpanel_')][2]//textarea

or

zktest=div#comments_ //div[starts-with(@id, 'tabpanel_')][2]//textarea

Selecting by label of selected Tab is somewhat complex (I am sure there is a simpler solution to it - if you know feel free to share):

xpath=(//div[starts-with(@id, 'comments_')]//textarea[starts-with(@id, 'comment_')])[count(//div[starts-with(@id, 'comments_')]//li[.//span[text() = 'Comment 2']]/preceding-sibling::*)+1]

Once again we see locators are very flexible - just be creative.

Combobox

Comboboxes are also very dynamic components. So if you just want to test your page, it is easiest to just "typeAndBlur" a value into them.

typeAndBlur zktest=input#topic_ theValue

If you really need to test the <comboitems> are populated correctly, my first suggestion is to test your ListSubModel implementation in a unit test in pure java code. But if you really really need to test this in a page test you can select the combobox-dropdown button with:

zktest=i#topic_ /i
or
zktest=i#topic_ [contains(@id, '-btn')]

XPath equivalents

//i[starts-with(@id, 'topic_')]/i
or
//i[starts-with(@id, 'topic_')][contains(@id, '-btn')]

To select the "consulting" <comboitem> - via mouse - you could use the following:

New Test
click zktest=i#topic_ /i
waitForVisible zktest=div#topic_ /table
click zktest=div#topic_ //tr[starts-with(@id, 'comboitem_')]//td[text() = 'consulting']

In many cases there is no general recipe, about what is right. In most cases it helps to inspect the page source and do what you need.

Putting it all together

The example package contains a running test suite featuring all the discussed topics from above.

It contains 4 test cases. 3 from above and a longer test case "new re-edit test" showing some more complex component interactions.

  • login test
  • edit save test
  • new re-edit test
  • logout test

To see it running you need to:

  1. Unpack the downloaded zip file
  2. Launch the testing application in test mode (/selenium_testing_app/launch_for_TEST.bat or selenium_testing_app/launch_for_TEST.sh)
  3. Open the Selenium IDE in Firefox ([CTRL+ALT+S])
  4. Make sure the extensions are configured (/extensions/user-extension.js) - if not, configure them, close and restart Selenium IDE
  5. In Selenium IDE open the sample test suite (/test_suite/suite.html)
  6. Check the Base URL - should be http://localhost:8080/
  7. Click the button "Play entire Test Suite"
  8. Lean back and watch...

Run against different Browsers using Selenium Server

There are many ways of running your tests against different browsers using Selenium Server. As this is not the focus of this document, here are just a few command line examples to see if your suite will actually run outside of Selenium IDE using Selenium Server 2.33 (while writing this document the latest version 2.33 only supports Firefox up to version 21.0)

Place the selenium-server-standalone-2.33.0.jar in the folder where you unzipped this example and run a command prompt at the same path: (of course you might have to adapt the paths of your browser executables)

execute with Firefox 21.0:

java -jar selenium-server-standalone-2.33.0.jar -userExtensions extensions/user-extensions.js -htmlSuite "*firefox C:\Program Files (x86)\Mozilla Firefox 21\firefox.exe" "http://localhost:8080" test_suite/suite.html test_suite/results.html

execute with google chrome:

java -jar selenium-server-standalone-2.33.0.jar -userExtensions extensions/user-extensions.js -htmlSuite "*googlechrome C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "http://localhost:8080" test_suite/suite.html test_suite/results.html

Appendix

Download

selenium-IDE-example.zip

Comments



Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.