Easier web app testing by mapping entities to UI objects

Automated, browser-based testing is a key element of web application development, benefiting both simple and complex applications. Writing effective tests for browser-based apps can be a complex, tedious and often repetitive task. In this post, I will be discussing a general approach to write meaningful, loosely-coupled UI tests for web applications by going beyond the Page Object Design Pattern into a more fine-grained approach I call ‘Logical entities to UI object mapping‘. I will show code in written Java 8 leveraging the Selenium and Selenide frameworks to show examples of the method described.

Layers of web app testing responsibility
Layers of web app testing responsibility

In web development, a common component used to perform browser-based testing is Selenium, which is a suite of frameworks and tools to automate browsers. All code in the Selenium projects is licensed under Apache 2.0. Selenium WebDriver is the most important component, which exposes an API to control several web browser and browser engines, and includes several language bindings: Java, C#, Python, Ruby, Perl, PHP and Javascript.

Page Object test design pattern

Selenium and the WebDriver API are very flexible and relatively easy to use. Make sure to check out the Test Design Consideration page of on the Selenium documentation for tips on how to structure your code, specially the Page Object Design Pattern section. There is a great post by Martin Fowler on the subject, plus lots of resources and blog posts on the web.

The following example is from the Selenium documentation, showing how coding a test using the straightforward WebDriver API can result in complex code that mixes many concerns:

 * Tests login feature
public class Login {

        public void testLogin() {
                selenium.type("inputBox", "testUser");
                selenium.type("password", "my supersecret password");
                Assert.assertTrue(selenium.isElementPresent("compose button"),
                                "Login was unsuccessful");

This kind of code, specially when adding lots of selectors and adding more test logic, can quickly transform into hard to maintain, spaguetti code.

When using the Page Object pattern, the original test code can be refactored into a more OOP class that has more semantics:

 * Page Object encapsulates the Sign-in page.
public class SignInPage {

        private Selenium selenium;

        public SignInPage(Selenium selenium) {
                this.selenium = selenium;
                if(!selenium.getTitle().equals("Sign in page")) {
                        throw new IllegalStateException("This is not sign in page, current page is: "

         * Login as valid user
         * @param userName
         * @param password
         * @return HomePage object
        public HomePage loginValidUser(String userName, String password) {
                selenium.type("usernamefield", userName);
                selenium.type("passwordfield", password);

                return new HomePage(selenium);

There are also fair warnings on the tradeoffs involved in applying the pattern, as described in this blog post.

In this case the warning is focused on the risk of grouping unrelated semantic and intent in aggregation ‘page’ classes.

In my case, I also tend to stay away from ‘page’ classes and write UI abstractions around the application’s logical entities. Logical entities are mapped to UI objects and then accessed naturally through their relationships so user actions and navigation are kept intentional. To also keep code within the domain of UI testing, most UI class methods are explicitly called after common user browser actions like clicking, moving the mouse or entering text into forms. In practice I have found that this combination is a ‘sweet spot’ combination of useful abstraction, loose coupling, testability and practicality.

The following diagram illustrates the concept for a typical content management system three level master-detail:

Grouping logical entities in semantic web UI testing, showcasing method names
Grouping logical entities in semantic web UI testing, showcasing method names

I will be showing next some specific examples of applying the ‘Logical entities to UI object mapping’ pattern in Java 8, using Selenide on top of Selenium to automate the browser.

Introducing Selenide

Surprisingly less well-known than it should be, Selenide is a great Selenium WebDriver abstraction layer written in Java that makes it easier to manipulate browsers and write tests than just by using Selenium. Selenide simplifies writing tests based on Selenium with a surprisingly intuitive interface. To demonstrate the simplicity, here’s an example from the getting started:

public void userCanLoginByUsername() {
  $(".loading_progress").should(disappear); // Waits until element disappears
  $("#username").shouldHave(text("Hello, Johny!")); // Waits until element gets text

The interface offered is easy to use and you usually don’t even need to look at the documentation. Waiting for elements to appear is implicit in many parts of the code and Selenide generally works as you would expect. I encourage you to try it, write a few tests and you will be surprised at the simplicity.

Regardless of the added convenience and abstraction of the Selenide library, we can still end with spaguetti code if we are not careful. For instance, if we use CSS selectors to access one UI element with $(org.openqa.selenium.By seleniumSelector) and want to change related classes in the client-side, we need to go everywhere in our testing code and change the CSS selector references.

Separating UI handling from tests

In a OSS project I’ve been recently working on (Morfeu), I am doing extensive testing of the web UI and I’m using the Logical entities to UI object mapping approach all over the place. For instance, in the project there is a list of catalogues (like a master-detail listing) as a logical application entity. Each catalogue has a list of different catalogue entries, which in turn contain documents (not shown in the example), completing a simple three layer of logical app entities. The code to operate and access the master catalogue list is as follows:

public class UICatalogues {

private static final String CATALOGUE_LIST = "#catalogue-list";
private static final String CATALOGUE_LIST_ENTRY = ".catalogue-list-entry";

public static UICatalogues openCatalogues() {
	return new UICatalogues();

public UICatalogues shouldAppear() {
	return this;

public UICatalogues shouldBeVisible() {
	return this;

public List allCatalogueEntries() {
	return $$(CATALOGUE_LIST_ENTRY).stream().map(e -> new UICatalogueEntry(e)).collect(Collectors.toList());

public UICatalogue clickOn(int i) {
	List catalogueEntries = this.allCatalogueEntries();
	int count = catalogueEntries.size();
	if (i>=count) { 
		throw new IndexOutOfBoundsException("Could not click on catalogue entry "+i+" as there are only "+count);
	return UICatalogue.openCatalogue();


To start with, public static UICatalogues openCatalogues() is used to open the catalogues list, it’s a static method as one of the constraints is that there is only one catalogue list and that it appears as soon as the user loads the application. A static method is a convenient way to access the ‘catalogues’ object instance as opposed to a public constructor, which maps to the application semantics. If there was a need to change the behaviour into requiring user action to load the catalogues (such as a mouse click) the implementation could be changed without changing the caller code. If the change were to be quite radical and significantly change the logical entity relationships, like allowing multiple catalogues, the API and caller code could (and should) be refactored to reflect the big change in application behaviour.

The methods UICatalogues shouldAppear() and shouldBeVisible() are pretty self explanatory, and can be used to ensure the catalogue list loads and displays properly.

The methods are quite simple themselves and the usage of Selenide is pretty much self-explanatory.

The next method List allCatalogueEntries() is used to obtain the list of catalogues, and takes advantage of Java 8 streams, mapping the list of found elements into new UICatalogueEntry instances:

public List allCatalogueEntries() {
	return $$(CATALOGUE_LIST_ENTRY).stream().map(e -> new UICatalogueEntry(e)).collect(Collectors.toList());

A stream of low-level catalogue entry elements found by Selenide is mapped to new catalogue instances and then collected into a using Java 8 list collector.

UICatalogueEntry‘s constructor accepts a SelenideElement to provide each catalogue entry instance with its local context. SelenideElement instances are a wrapper of Selenium elements and are the basic building blocks of testing using Selenide.

The last method UICatalogue clickOn(int i) is a convenience method to click on a specific catalogue entry and is also quite straightforward:

public UICatalogue clickOn(int i) {
	List catalogueEntries = this.allCatalogueEntries();
	int count = catalogueEntries.size();
	if (i>=count) { 
		throw new IndexOutOfBoundsException("Could not click on catalogue entry "+i+" as there are only "+count);
	return UICatalogue.openCatalogue();

UICatalogue is also a semantic web UI class that includes the click() method that loads a catalogue, which is returned (in this case also without any parameters in the current implementation).

It should be noted that there are other valid ways to design this. The clickOn method only uses public methods so it could rightly be perceived as ‘client’ code, but as clicking on a catalogue is done very often, this is offered as a way to avoid repetition. It’s important to spend some time thinking about this design, giving consideration to style, operation frequency, potential for repetition, amount of convenience methods and so forth.

Also a bit of a personal code style choice, I am staying away from get/set semantics to better distinguish UI test logic from typical application code (which commonly employs get/set prefixes). A backend code getter could potentially perform a complex operation while the UI code just selects a CSS class and reads a value displayed on the page, hence the shorter method name. Following this logic, user action methods like clickOnXXX will be the ones performing complex operations like navigating to a different page and so forth, so they have a more explicit verb prefix. Of course getter/setters can be used if that suits more your style.

Using the abstraction UI classes

Usage is also straightforward, like this method:

public void catalogueListTest() throws Exception {
	List catalogueEntries = UICatalogues.openCatalogues()
	assertEquals(EXPECTED_CATALOGUES_COUNT, catalogueEntries.size());
	assertEquals("Wrong catalogue content", "Catalogue 1", catalogueEntries.get(0).name());
	assertEquals("Wrong catalogue content", "Catalogue 2", catalogueEntries.get(1).name());
	assertEquals("Wrong catalogue content", "Catalogue 1 yaml", catalogueEntries.get(2).name());

This code is easy to read, and shows exactly what kind of behaviour the is being tested. In this case, it’s testing that once the application is loaded, the catalogues should appear, there should be EXPECTED_CATALOGUES_COUNT entries, and also the particular catalogue order and names. Finally, no error should be shown. Also note the readability of catalogueEntries.get(0).name() vs a more verbose catalogueEntries.get(0).getName().

More complex behaviour is also modelled quite well:

UICellEditor stuffEditor = stuff.edit().shouldAppear();
Optional value = stuffEditor.getValue();
assertEquals("Stuff content", value.get());
assertFalse("Should not be able to create a value for this cell",  stuffEditor.isCreateValueVisible());
assertTrue("Should be able to remove value for this cell",  stuffEditor.isRemoveValueVisible());

value = stuffEditor.getValue();

In this case the code is testing a form that contains a value and can be removed entirely (as opposed to cleared) by clicking on a specific widget or button. Once the widget is activated, the form value disappears and is not there anymore.

More examples like these can be found in the Morfeu project tests.


It is definitely useful to abstract web UI testing using techniques like ‘Logical entities to UI object mapping’ described in this post or the Page Object mapping pattern. If the right abstraction level is applied correctly, test are more meaningful, their intent is more obvious and the actual web app implementation can be changed more easily. Techniques applied with tools like Selenide make writing the semantic UI code even easier and combined with Java 8 stream support, testing code ends up being super-fun to write.


For more examples please take a look at examples from the Selenide documentation on the direct UI and test mix approach:

  public void search_selenide_in_google() {
    $$("#ires .g").shouldHave(sizeGreaterThan(1));
    $("#ires .g").shouldBe(visible).shouldHave(
        text("Selenide: concise UI tests in Java"),

(Note that the example is intended for simplicity and separation of concerns is not the aim of the code). The code is pretty readable and concise, but could be improved by applying the Page Object test design pattern or the one described in this blog post. Alternatively, for smaller tests having the classes in constants or in a test configuration could also be practical.

The Selenide project also has some examples of the more semantic approach using Page Objects here.

Lindy Hop: El regal de Frankie Manning

Frankie Manning ens va deixar un llegat artístic excepcional en el món de la dansa i la coreografia en ser un dels creadors del Lindy Hop. En la seva biografia escrita conjuntament amb la ballarina i escriptora Cynthia R. Millman, Manning ens explica com va nèixer aquesta disciplina de ball de la música Swing, com va crèixer i evolucionar però també com va passar de moda per finalment renèixer als anys 80. Avui en Barcelona és una de les capitals del món d’aquesta disciplina de ball, que compta amb desenes de milers de practicants a tot el món. De retruc, el llibre ens mostra una visió excepcional del barri de Harlem de principis del s. XX, com només la podria explicar un integrant d’una comunitat tant modesta, apasionada i vibrant com és la de la gent d’aquest conegut barri de Nova York. Continueu llegint per acompanyar-me en un viatge apassionant que passa pel ball, el jazz, Nova York i la força de la vida.


Frankie Manning ens va deixar un llegat artístic excepcional en el món de la dansa i la coreografia en ser un dels creadors del Lindy Hop. En la seva biografia escrita conjuntament amb la ballarina i escriptora Cynthia R. Millman, Manning ens explica com va nèixer aquesta disciplina de ball de la música Swing, com va crèixer i evolucionar però també com va passar de moda per finalment renèixer als anys 80. Avui en Barcelona és una de les capitals del món d’aquesta disciplina de ball, que compta amb desenes de milers de practicants a tot el món. De retruc, el llibre ens mostra una visió excepcional del barri de Harlem de principis del s. XX, com només la podria explicar un integrant d’una comunitat tant modesta, apasionada i vibrant com és la de la gent d’aquest conegut barri de Nova York. Continueu llegint per acompanyar-me en un viatge apassionant que passa pel ball, el jazz, Nova York i la força de la vida.

Frankie Manning va nèixer un 26 de maig de 1914 a Jacksonville, Florida. El barri de Campbell Hill on Manning va viure els tres primers anys de la seva vida era modest i l’habitava exclusivament gent de raça negra. Els pares de Frankie es van separar i la seva mare Lucille Manning ben aviat va decidir emportar-se el seu fill a viure plegats a Nova York. La gran ciutat era plena de soldats tornats de la primera gran guerra i contrastava amb els aires de campestres del nord de Florida. Es van instal·lar en un apartament del 109 138th Street, al barri de Harlem. Durant aquells anys Manning va aprendre de primera mà el dia a dia de la discriminació racial que imperava als Estats Units a principis del segle passat. Una experiència que malauradament continuaria en les dècades posteriors.

Lucille era aficionada a ballar, sobretot en les festes que s’organitzaven en cases privades, sovint per pagar el lloguer, pagant entrada i 10 centaus per una mica de bathtub gin (licor fet a casa). Es ballava de tot, amb estils musicals de moda d’aquell temps com el ragtime, el Charleston, etc.

Una mica de música ragtime: “Showtime”, de Thomas Smith

Lucille sovint duia Manning a aquestes festes, resulta fàcil d’imaginar al petit Frankie entusiasmat de la música i ballant deshinibidament com només ho poden fer els nens. Frankie recorda com als 12 anys ja va anar a una festa social al saló Renaissance amb la seva mare, que allí mateix li va dir: “Frankie, mai seràs un ballarí. Estàs massa rígid.”.

Un Frankie preadolescent es va convertir en un regular de la sala de ball de Harlem anomenada Alhambra, (encara oberta), on feien sessions per a joves els diumenges a la tarda.

Alhambra Ballroom
Sala de ball Alhambra, al cor de Harlem

A l’Alhambra és on Manning va veure i ballar el Lindy Hop per primera vegada. Un estil de ball que incorporant influències del Charleston, el collegiate i el breakaway, acababa creant un estil propi de Harlem, informal, animat i amb molt “swing” en parella. El leader, normalment de gènere masculí, és qui condueix el ball, mentres que la follower, habitualment de gènere femení, segueix les indicacions del leader, però sense descuidar la seva creativitat.

Eren temps de canvis, i el mateix 1927 Charles Lindbergh o Luck Lindy, com també se’l coneixeia, acabava de creuar tot sol l’oceà Atlàntic amb l’avioneta Spirit of St. Louis, els diaris havien titulat la gesta de Lindbergh amb “Lindy Hops the Atlantic” (Lindy Salta l’Atlàntic).  Un ballador de l’Alhambra, “Shorty” George Snowden, durant una marató de ball al Manhattan Casino parlava amb un periodista que li va preguntar que era lo que estava ballant, Shorty li va contestar: “Estic ballant el Lindy Hop”. Quedava batejat el fenòmen.

Aviat Manning i la resta de ballarins farien el salt a la sala Savoy, també de Harlem, on el Lindy Hop es va anar consolidant.

Savoy, featuring a gig by Erskine Hawkins and Terry Gibbs
Entrada al Savoy Ballroom, tocaven Erskine Hawkins and Terry Gibbs Orchestra

Erskine Hawkins & His Orchestra interpretant ‘Tuxedo Junction’, que Glenn Miller va portar a un següent nivell

Un eixalabrat Manning de només 18 anys tenia el seu primer fill amb la seva nòvia Dorothy Young, el Novembre del 1932. Frankie va deixar el petit Chazz Young a mans de la seva mare, amb qui no va fructificar la relació. Malgrat la seva falta d’implicació, Chazz i Frankie s’acabarien fent grans amics i el ballarí acabaria exercint les seves responsabilitats com a pare.

La competició Harvest Moon Ball es va celebrar per primera vegada l’Agost de 1935 al Madison Square Garden, amb les categories de foxtrot, vals, tango, rumba i Lindy Hop. Frankie, la seva parella de ball Maggie McMillan i uns quants companys de ball del Savoy van participar en aquella edició i naturalment van guanyar les tres primeres posicions, per davant de la resta d’equips de les altres sales de ball de la ciutat. Manning i Maggie van quedar segons, per darrera de Leon James i Edith Matthews. Edith, una de les primeres grans balladores de Lindy, va ser la inventora del ‘twist’, un moviment estilístic fantàstic de les followers en el pas bàsic del swingout.

Dax Hock i Pamela Gaižutytė, a les finals ESDC All Star Lindy Hop Jack & Jill 2013. La Pam executa uns twists totalment hipnòtics cada vegada que pot =)

Frankie Manning va ser el pioner dels air steps, els passos aeris de Lindy Hop. Conjuntament amb Frieda Washington van practicar durant dues setmanes en el 230 West 140th St, el petit apartament de Manning en aquell moent. Frieda es va fer un fart de caure sobre el matalàs que Frankie havia preparat per practicar, però en poc menys de quinze dies havien perfectionat el Over the back.

Exemples d’execució del pas aeri Over the back

A mitjans dels anys 30, la popularitat del Lindy Hop va crèixer encara més. Manning i una bona colla de balladors van passar a ser ballarins professionals, formant la companyia professional Whitey’s Lindy Hoppers, nom inspirat pel sobrenom de Herbert “Whitey” White, el seu creador i manager. En la llegendària sala Apollo de Harlem, Frankie i els seus companys van actuar amb orquestres tant llegendàries com la de Chick Webb (amb la Reina del Jazz, Ella Fitzgerald!), Cab Calloway, Erskine Hawkins i fins i tot el gran Count Basie.

Amb tanta popularitat, era inevitable que el fenòmen arribés al gran catalitzador de Hollywood. Tant els Whitey’s com altres bandes destacades de Hoppers van aparèixer en diverses pel·licules de l’epoca, tals com Everybody Sing,  Hellzapoppin’, i la celebrada A Day At The Races, dels Germans Marx.

Escena de Lindy Hop a Hellzapoppin’, on es veuen diversos aeris espectaculars, entre ells el Over the Back

Malgrat els èxits, no tot eren flors i violes. Manning recorda una anècdota en un hotel de Boston on treballaven amb Count Basie, la seva banda i la gran Billie Holiday. Després de ballar a l’escenari, els ballarins es van anar canviar i van tornar ràpidament per no perdre’s l’actuació de la gran cantant. Els van fer fora perque eren negres. Count Basie i la Billie van intercedir i la cantant va amenaçar a la direcció de l’hotel que no hi cantaria més si no els deixaven assistir. A la següent actuació els ballarins tenien una taula preparada expressament. Frankie sempre recordaria a la polèmica diva del jazz, assetjada per problemes de drogues i judicials, com a una persona dolça i amb un gran cor. Després de la mort de la cantant, se li van conçedir quatre premis Grammy pòstums.

Apart d’estrelles del Jazz, Frankie Manning també va conèixer celebritats com Clark Gable, Spencer Tracy, Fred Astaire o Judy Garland (la Dorothy de Wizard of Oz i mare de Lizza Minnelli).

La popularitat del Lindy va arribar a Broadway, on es van fer funcions tals com Swingin’ the Dream, on Frankie actuava conjuntament amb estrelles de la talla de Benny Goodman o el mestre de mestres Louis Armstrong.

Mentres la Segona Guerra Mundial devastava Europa, al nou continent l’èxit va portar de gira a sudamèrica a Manning i el seu nou grup, els Congaroo Dancers. Quan els Lindy Hoppers estaven a Rio de Janeiro l’armada imperial japonesa atacava Pearl Harbor. Els Estats Units entraven de ple en la segona gran guerra. Va ser molt llarg i complicat per Frankie i els seus arribar sans i estalvis cap a Nova York. Al cap de gairebé un any de gira i viatge, Manning s’havia gastat tota la recaudació, inclosa la comissió que Whitey havia de cobrar per la gira. Després d’una forta discussió, el mànager i el coreògraf van partir peres per sempre. Va passar poc temps fins que Lucille Manning va rebre les cartes de notificació de l’ingrés obligatori de Frankie Manning a l’exèrcit dels Estats Units. Per tot el país, centenars de milers d’homes s’unien obligatòriament a la gran guerra i els hoppers no en van ser una excepció. Era el principi de la fi de l’era daurada del Lindy Hop.

El juny del 1994 Manning va embarcar en el vaixell de transport de tropes Lurline, rumb a l’invasió de Nova Guinea. Durant la guerra, l’antic ballarí i coreògraf va experimentar de tot: combat actiu amb les tropes japoneses, racisme descarat envers els soldats negres, censura epistolar de l’exèrcit però també anècdotes com les visites d’artistes famosos per pujar la moral de les tropes. En una ocasió Frankie va ballar amb Betty Grable, la cantant, model pin-up, ballarina i llegendària actriu de les “cames del milió de dòlars”.

Betty Grable i les seves famoses cames
La Betty Grable i les seves famoses cames

De tornada de la guerra, les coses ja no van tornar a ser el mateix per Manning i ni la resta de hoppers. Al Savoy no hi havia el mateix ambient i els gustos musicals estaven canviant cap a altres ritmes com el bebop. Sense desanimar-se, el coreògraf va fundar el seu propi grup, els Four Congaroos i va coregrafiar i actuar em èxits en diverses sales dels Estats Units i Canadà. Les iniciatives anaven força bé donades les circumstàncies, realitzant gires amb caps de cartell tals com Nat King Cole i Sarah Vaughan, cantant llegendària i guanyadora de dos premis Grammy.

Malgrat els èxits, es veia que les coses havien canviat molt i que canviarien encara més. Whitey va morir el setembre del 1950, un cop molt dur pels Congaroos. La mort del mànager estimat per tots els hoppers del Savoy va marcar el final d’una era. Durant el següents 4 anys la feina per Manning i els seus va anar minvant fins a quedar en res.

Frankie es va casar el juny del 1954 amb Gloria, la seva parella desde feia sis anys, qui li va dir que es busqués una feina, temporal, per un any o així, per poder pagar les despeses i cuidar la filla que acabaven de tenir, la Marion. Així és com el genial ballarí va entrar a treballar a l’oficina de correus de Lexington Avenue amb el 45th st de Nova York. Tot i que va provar alguna altra feina més, hi va acabar treballant durant els següents 30 anys. Víctima dels nous temps, el Savoy va tancar finalment el 1958.

Plànol del Savoy de la New York Public Library
Plànol del Savoy trobat a la New York Public Library

El 1975 la mare de Frankie va morir víctima d’una malaltia a l’edat de 76 anys. Un any més tard Manning ho deixava amb Gloria i anava a compartir pis amb el seu fill Chazz, que s’acabava de divorciar (Manning es  divorciar oficialment de Gloria el 1989). Les dècades havien passat volant mentres Frankie, tot classificant paquets a l’oficina postal, recordava els seus temps com a ballarí professional.

Malgrat que l’estrella del Lindy Hop s’havia apagat, durant els anys 80 hi havia un petit resorgiment, ajudat per col·laboracions puntuals dels antics hoppers que encara eren vius. Un revival que va rellançar la New York Swing Dance Society, que desde el 1985 organitzava balls al local Cat Club aprop d’Union Square, o en petits locals del conegut barri TriBeCa de Manhattan.

Un punt d’inflexió es va produïr quan un vespre, Manning va rebre una trucada d’una noia desconeguda preguntant si hi havia el “ballarí Frankie Manning”. “No, sóc el Frankie Manning que treballa a correus”, va respondre ell. “Sí, però vosté havia ballat abans, no?” li insistia la jove. “Sí, però ja no ballo”. Havia passat gairebé mitja vida.

El trucava l’Erin Stevens,  qui juntament amb Steven Mitchell eren professors de ball a Cailfòrnia i uns nous entusiastes del Lindy Hop. Coneixien el seu nom a través de la NY Swing Dance Society i l’havien buscat a la guia telefònica. Volien anar a Nova York i que els fes de professor per un parell de setmanes. En Frankie li va di que no, però ella era molt insistent i van quedar en que només havia de veure’ls ballar i després ja es veuria. Frankie va quedar-ne impressionat i va acceptar ensenyar-los a perfeccionar la seva tècnica. Començava una nova era pel Lindy Hop.

El 1987 Frankie va viatjar a Stockholm per perfeccionar la tècnica dels The Rhythm Hot Shots, un grup suec de dansa que havia après a ballar Lindy veient incontables vegades a càmera lenta les seqüències de ball de Hellzapoppin’ i A Day At The Races. Amb els Rythm Hot Shots van visitar plegats Herräng, un petit poble suec on la Swedish Dance Society havia organitzat festivals de ball desde 1982 (el festival de Swing de Herräng Dance Camp mobilitza avui en dia més de 3500 ballarins de tot el món).

Amb la renascuda popularitat del Lindy Hop, la carrera de Frankie va renèixer com a ballarí, professor i coreògraf. Un equip format per Manning, Cholly Atkins, Henry LeTang, i Fayard Nicholas, va guanyar un Tony Award a la millor coreografia en el musical de  Black and Blue, un show estrenat el gener de 1989 al Minskoff Theatre de Broadway. Amb aquest premi sota el braç, el renovat Frankie va treballar com a coreògraf de Malcolm X (1991) de Spike Lee, on fins i tot fa de ballarí en l’escena de ball de la película fent parella amb Norma Miller. Per l’escena, Frankie va fer de professor a les parelles d’actors Denzel Washington i Theresa Randle, juntament amb Spike Lee i Cynthia Thomas. Denzel Washington es va encaparrar en fer un pas aeri (el snatch) després de veure’l les antigues pel·lícules on havien ballat els Whitey’s Lindy Hoppers.

L’escena de ball de Malcolm X amb Denzel Washingon i Theresa Randle

Els anys noranta van portar una explosió de popularitat del Swing (tant el Lindy Hop com la resta d’estils de ball swing com el shag, West Coast, Hollywood, etc.), Frankie va continuar treballant com a coreògraf, consultor musical i professor arreu del món. Ell mateix i també ballarins de la nova era van participar en diversos musicals, programes de televisió, anuncis i pel·licules de tota mena.

En la recta final de la seva carrera, Frankie Manning rebia els premis que se li havien negat en la joventut, tals com presència al City Lore People’s Hall of Fame del Museum of The City of New York, el New York City Arts in Education Roundtable AwardNEA Coreographers FellowshipNEA National Heritage Fellowship, el Yehoodi Legacy Award i el 2005 entrava al Hall of Fame del National Museum of Dance de Nova York.

Als últims anys de la seva vida, Frankie mirava enrera amb alegria. Els seus amics, alumnes i admiradors li organitzaven festes d’aniversari de tota mena (amb balls de Lindy Hop!) i era feliç amb la seva nòvia, Judy Pritchett. Amb les seves propies paraules: “He viscut una vida fantàstica, i crec que ho dec als Lindy Hoppers de tot el món. És d’aquí on trec l’energia. Més que qualsevol altra cosa, això és lo que m’ha fet tirar endavant”.

A la primera meitat de segle, ballar al ritme de música Swing no es considerava una activitat mereixedora de reconeixement artístic. Era un entreteniment de gent de barri, modesta i amb pocs recursos. Frankie Manning no només va ser un dels creadors originals del Lindy Hop, en la part final de la seva vida va resultar instrumental en posar aquest ball al lloc d’honor que li ha pertocat sempre. Amb la seva senzillesa, genialitat artística i humanitat, Manning ens ha deixat a tots els amants de la música i el ball un llegat inigualable.

Gràcies Frankie, el pròxim ball te’l dediquem a tu.

provashell – testing shell scripts the easy way

In this post I will describe the provashell project, an Apache 2.0 licensed bash and shell Unit Testing library using annotations. The library is a self-contained script file with no dependencies that can be embedded or used easily in your project. Extra care has been taken to use POSIX shell features and the code has been tested in the popular shells bash, dash and zsh (latest versions the time of writing this article). I will add some detail on what drove me to do it, what it does, how it works and some examples.

Unit tests should be everywhere there is code. Tests materialise our expectations of the expected behaviour, prevent obscure bugs, generally induce more elegant designs and also serve as very effective up-to-date documentation. The oft-touted benefits are well worth it.

An area commonly overlooked in unit testing is when the code is “just a script”. This is unfortunately a common misconception, code is just code and should therefore be treated as such, with solid engineering principles and rigorous testing. Here’s a thought experiment: try to tell yourself what the differences between a ‘script’ and ‘proper code’ really are. Is it length? There might be a short piece of code that configures all your company’s firewall rules or backups and that is quite an important piece of logic, isn’t it? Is it criticality? Working non-critical code tends to end up included in critical systems and by extension becomes ‘mission-critical’ as well. Is it the language it is coded in? Most languages are pretty much logically equivalent (and Turing complete) so if something coded in Python is translated into Java to do the same thing its very essential nature has not changed at all. Is it necessity? We could go on. Code is just code, and it can and should be tested.

Unit testing for bash and shell scripts

Testing bash and shell scripts is unfortunately not that common. As discussed, shell scripts should still be tested thoroughly. There are plenty of shell testing libraries out there, usually bash-specific implementations, with different licenses. They are mature and well tested implementations. However, I was on the lookout for an Apache 2.0 licensed one that was simple, with no dependencies (such as the latest C++ compiler!) and I could not find one that suited my taste. One never knows anywhere near all there is to know about shell programming (trust me, you do not, specially when taking into account different implementations and so on) so I set about writing one myself that had the outlined characteristics which would also help me to learn more about shell coding.

Main features

The specific characteristics of provashell are as follows:

* Be unit-tested itself – Using plain shell test structures to do the assertion tests themselves. One of course can test the basic assert function and then leverage that tested function to check the other assertions, but I wanted to avoid false positives and keep concerns separate. Using provashell’s own test assert functions to test itself results in more elegant code but is potentially confusing when failures occur due to cascading effects. 

* Be as POSIX-compliant as possible – To that effect, the library has been tested in the latest (as of writing) versions of bash, zsh and dash, the latter being quite POSIX-strict. While bash-isms can be very practical when coding and in interactive shell sessions, cross-shell testing is a good code quality exercise which forces engineers to double check lots of assumptions and shortcuts, generally leading to better scripts. Even though I much prefer to use zsh for interactive sessions (specially when paired with toolchains such as the genial oh my zsh), once you have the mindset of shell implementations being real programming languages, it is fairly easy to mentally switch to bash or -even better-, POSIX shell ‘mode’ when writing persistent scripts. Such mental gymnastics will greatly help if found working on an old or unfamiliar system, with only ksh installed or something like that.

* Run no user-supplied code – This is an important security characteristic. The very first version of provashell used eval to run assertion checks in a flexible way, this resulted in elegant code but it also meant that test data could include shell code that could be run by the test framework. This is insecure and should be avoided if there are other solutions at hand, even if they are a bit more complex or less elegant. The latest version does not use eval anywhere in the code so it will not execute any user o lib user code, except for running the configured setup and teardown functions, of course. Whatever happens in those functions is up to the test developer. In any case, automated unit tests should never include user-supplied or variable data, to significantly low the risk of attacks using Continuous Integration systems or any automated test routines. Following that strategy, provashell does not run any user-supplied code other than the configured setup, teardown functions and the declared tests, and the assertion functions do not execute any external code to the best of my knowledge (you should check the code yourself anyway, grep -R eval src is your friend here).  It goes without saying that test shells should pretty much never be run as root, unless there is a very good reason (which there isn’t).

* Do not do (too much) funky stuff – Try to be as simple as possible and reuse code wherever feasible, so there is little repetition in the test library. It should also be easy to read and understand by any reasonably experienced shell coder. It is worth stressing again that shell scripts are real code and should be treated as such at all times.

* Use annotations to identify tests – Tests can be named any way the developer wants. I like annotations for tests because even though appending ‘Test’ to tests is a really simple convention, sometimes it adds extra cruft to test names in a context where it is not actually needed. For instance, the test called ‘errorIsReturnedOnNetworkTimeout’ is quite self-explanatory and easily understood in a test class context. Having ‘errorIsReturnedOnNetworkTimeoutTest’ does not add much to the definition and extends the name needlessly. It is of course a matter of style and it could argued that adding annotations to tests adds the same cruft, just in a different place. In any case, provashell uses annotations to identify tests and related functions which work well and are simple to use. Here’s a summary diagram of all the supported annotations (they need to go in a bash comment line):

provashell annotations
Function annotations defined by provashell

Yeah! Give me some shell test examples

Usage is pretty straightforward and can be demonstrated with an example. Imagine we have a function we want to test that counts the number of a’s in a text passed as a parameter. It is probably not a very good implementation but is a good enough example:

countAs() {
	c=$(printf %s "$1" | sed 's/[^a]*//g' | tr -d '\n' | wc -m)
	return "$c"

We then have two tests like this:

countAsNormally() {

	countAs 'a'
	assertEq "Does not count one 'a' in a string with only one 'a'" 1 $?

	countAs 'b'
	assertEq "Does not count zero a's in a string with no a's" 0 $?

	countAs 'aaa'
	assertEq "Does not count three straight a's when they are there" 3 $?

	countAs 'abab'
	assertEq "Does not count two a's in a string when they are there" 2 $?


countAsEdgeCases() {
	countAs ''
	assertEq 'Does not count empty string correctly' 0 $?

Once we have defined the tests we need to source the library like this (using whatever path we have for the provashell file):

. provashell

This will run the provashell code within the current context, causing the tests to be executed as expected, including the annotated pre and post functions.

Complete documentation

Extensive docs and examples can be found at the GitHub provashell project page. In any case, the source is quite short and readable.


The provashell library uses the Apache 2.0 license. Pull requests are welcome so fork away!

La història dels espies que també eren poetes

Leo Marks va ser un heroi de guerra molt particular. Va salvar moltes vides a la Segona Guerra Mundial amb la criptografia… i la poesia. Tal com explica el seu genial i autobiogràfic llibre ‘Between Silk and Cyanide‘, tot va començar com les bones històries, amb els clàssics universals.
Continue reading “La història dels espies que també eren poetes”

Easy deployment of Zookeeper and Storm in RPM packages

In this post we will package Storm and its dependencies to achieve seamless deployment of a realtime big data processing system. Following up on the first Meteorit project article, we will be adding the minimal supervisor system mon, Zookeeper, zeromq and finally Storm itself. Packaging will enable fast deployment of the whole processing system using RPM packages.
Continue reading “Easy deployment of Zookeeper and Storm in RPM packages”

September 11th – National Day of Catalonia

Today is a special day for Catalans. We celebrate our National Day of Catalonia, which remembers our final defeat in 1714 against the army of Bourbon king Philip V of Spain in the Spanish Succession war. The end of the war brought the abolition of Catalan rights and institutions, which would not be reinstated and only partially in 1978, long after Franco’s death.

Today is even more special as the Via Catalana, a great human chain of 250 miles will go along the coast of Catalonia to ask for a democratic referendum about the future independence of Catalonia from Spain. Starting from the southern border of Catalonia, going through Barcelona and ending in the border of France, this historical event will reinforce our democratic feelings of freedom and hopefully boost our chances for a democratic resolution.

Logo fo the Via Catalana
Catalan way for Independence

The op-ed post by Artur Mas in the New York Times summarises the situation pretty well, embodying our wish to vote about our future.

To maintain the spirit in the blogosphere, a virtual blog chain has been organised by Blog-via cap a la independència to support the Via Catalana initiative.

This is blog #292, in between Els petits retalls and Descans: el blog d’un home que descansa.

Happy Diada!

Crayon: codi font en colors en WordPress amb cara i ulls

Feia temps que buscava una bona solució per pintar codi font una mica decent. Fins ara tenia el Syntax Highlighter Evolved, basat en el Syntax Highlighter d’Alex Gorbatchev, però no n’estava gaire convençut.
Navegant per altres blocs he vist el resultat del plugin de Crayon per a WordPress, desenvolupat per Aram Kocharyan. El codi font es pot trobar en la seva pàgina de GitHub llest per fer-hi contribucions, amb llicència GPLv2.
Continue reading “Crayon: codi font en colors en WordPress amb cara i ulls”

Handling real-time events with Nginx, Lua and Redis

In this post, we will explore options to handle lots of HTTP events asynchronously using Nginx, Lua for the frontend and Redis as the backend. Although there are plenty of options out there to deal with this, we will check these technologies out in a bit more detail and leaving lots of options open for customisation and tuning, while using tried and true building blocks.
Continue reading “Handling real-time events with Nginx, Lua and Redis”

El conflicte entre les xarxes socials i els mitjans de comunicació

En aquest article parlaré de la confrontació silenciosa actual entre els mitjans de comunicació i les les xarxes socials. Els mitjans no estan desapareixent, ni tampoc saltant pels aires, sino sofrint una erosió terrible en un conflicte que està canviant la indústria de la comunicació mica en mica, tuit a tuit, post a post.

Els mitjans tradicionals arrossegats a la batalla amb les grans xarxes socials
Continue reading “El conflicte entre les xarxes socials i els mitjans de comunicació”