Chess - antoniomartel.com

Archivos por Etiqueta: Selenium

Functional tests with Selenium WebDriver

(Sorry, this is a technical post about software testing, but don’t worry, you can find here some of my non-technical blog posts)

A few years ago we used Selenium IDE in a web application project just to check the functionalities developed at that sprint were working as expected but there were some problems with that. I try to sum up them here:

  • Selenium IDE works only with Mozilla Firefox web browser. That was a problem when you did need to test another browser or your web app worked only in MS Internet Explorer.
  • Tests and tests suites used to become red frequently. Firefox updates (on security mainly) made script commands deprecated easily so it was needed to search for a replacement, when available, or to find a workaround (after a few hours in Stackoverflow). To keep them working in order was costly (and time consuming).
  • There was some kind of a mess with script commands: type or typeKeys, click or clickAt, mouseAt or mouseDown. You never knew.
There were also some advantages, of course, like the way the user actions could be recorded by the IDE. You just had to click somewhere, move the mouse or type something that your movements were recorded by the IDE as script commands. It was needed to adapt or fix them after recording it but it used to made things easier. 
These days I have been playing around with Selenium WebDriver. It doesn’t need to inject javascrit code into the web browser and you can use your favourite programming language to write the tests.
I have written a couple of tests to check one of my web applications just to show you some of its main features and how Selenium WebDriver can work on Chrome. At the end of this post you can find a video showing how these tests work.

This first test is a kind of smoke test just to check that the application is working properly and shows the main page when it is requested:

Below you can find how to get the driver variable for Chrome. Using it you can have access to all WebDriver commands. It is written inside the jUnit @Before annotation so it is going to be executed before any other test run. At the @After method there will be a driver.quit(); sentence.

This last test actually checks that 10 questions are asked at each attempt (no more, no less), chooses randomly one of the multiple choice options and ensures that there is a results page at the end.

This is the Selenium/JUnit tests video recording:

You can find texts like this and many other about how to manage agile projects in my book Agile 101: Practical Project Management (available on Amazon).

References:

IV Conference on Sustainability

Last Thursday I had the honor of giving a presentation on Phase 2 of the Canary Islands Waste Information System (GUIRRE) at the Fourth Conference on Sustainability inside the activities for the World Environment Day.

GUIRRE is a very special project for me for several reasons: It was the first time we run a project using continuous integration (Jenkins) and automated tests using Selenium IDE.

At the beginning of the project, before starting to program, we defined a section called ‘How to test it’ for every feature we had to develop. We recorded tests with Selenium, following the steps of the ‘How to test it’ section. Those tests helped to show that the new feature worked properly. If we found a bug, we recorded also a test to reproduce it. When the test became green, we had fixed it.

Every two weeks, we recorded all tests of the current Sprint on a Selenium ‘suite’. Every night, the continuous integration server, Jenkins, ran the suite and all suites from previous Sprints and reported if there had been mistakes. If the previous morning someone had modified a piece of code affecting a functionality developed some months ago, Jenkins showed us some dark clouds.

The other reason GUIRRE is a dear project to me is because we managed to finish under budget (yes, those projects exist) despite we fully assumed the cost of learning Jenkins and Selenium, and that the budget was very adjusted. Quite a challenge.

I leave below a few pictures of the event and a link to the paper I presented. Hope you find it of interest.

Pruebas automatizadas con Selenium

En mi última entrada hablaba de Selenium y como, gracias a herramientas como ésta, había conseguido reducir el número de errores en las aplicaciones en las que se ha utilizado.

En la entrada de hoy describiré con un ejemplo uno de los múltiples usos que puede tener un automatizador de navegadores como Selenium. Para ello utilizaré la web RottenPotatoes construido con Ruby on Rails sobre Heroku, la plataforma de aplicaciones en la nube que se utilizó en el curso CS-169.1x Software as a Service (a propósito, curso muy recomendable de edx.org)

Si quisiéramos probar una de las funcionalidades que acabamos de desarrollar en nuestra aplicación, podríamos utilizar Selenium IDE (plugin para Firefox) y escribir o grabar un pequeño test que probase que esta funcionalidad ha sido correctamente implementada.

Pongamos como ejemplo que queremos probar el nuevo filtro de películas por clasificación. Para ello, con Mozilla Firefox abierto, ejecutamos el plugin Selenium IDE y creamos un nuevo test:

Abrimos la página a testear con el comando Selenese:

 

Command Target
open http://stormy-beyond-4091.herokuapp.com/movies

 

con lo que obtendríamos una nueva pestaña con nuestra aplicación:

desmarcamos los botones G, PG-13 y R y pulsamos el botón ‘Refresh’ con los siguientes comandos:

 

Command Target Value
uncheck id=ratings_G
uncheck id=ratings_PG-13
uncheck id=ratings_R

 

check
id=ratings_PG
clickAndWait
id=ratings_submit
Con estas acciones debemos haber obtenido una página donde se muestran sólo las películas para todos los públicos (PG). Verificamos que sólo se muestran las películas ‘Los increibles’ y ‘En busca del arca perdida’. De paso comprobamos también que en los resultados no se ha devuelto por error la película ‘2001: Odisea del espacio’:

 

Command Target Value
verifyTextPresent The Incredibles
verifyTextPresent Raiders of the Lost Ark
verifyTextNotPresent 2001: A Space Odyssey

 

Además comprobamos también que el número de películas mostradas es de sólo dos. Para ello comprobaremos que en la tabla devuelta hay 3 filas (2 <tr> para las dos películas y 1 <tr> adicional para la cabecera de la tabla):

 

Command Target Value
verifyXPathCount //table//tr 3

 

Un test como éste puede ser creado para cada nueva funcionalidad que desarrollemos y ser incluida posteriormente junto al resto de tests que hayamos creado a la batería de pruebas que realiza el servidor de Integración Continua (Jenkins por ejemplo). De esta forma los test son pasados cada noche, o a la hora en que lo programemos y si hubiésemos subido al Subversion un código que hace que alguna funcionalidad muestre un error, el servidor de Integración Continua nos avisará inmediatamente.

Les dejo el test disponible para su descarga en el siguiente enlace: Selenium Test

Si te interesa saber más sobre la certificación, estimaciones, ventajas y desventajas de Scrum o cómo gestionar proyectos de forma ágil quizás te interese mi libro: Gestión práctica de proyectos con Scrum.

Si en cambio quieres poner a prueba tus conocimientos de Scrum haciendo un test en español antes de tomar el examen de scrum.org aquí tienes el Test no oficial de Scrum (aplicación realizada con Ruby on Rails y desplegada en Heroku).

Ponencia en las IV Jornadas de Sostenibilidad en Canarias

El pasado jueves tuve el honor de dar una ponencia sobre la Fase 2 del Sistema de Información de Residuos de Canarias (GUIRRE) en las IV Jornadas de Sostenibilidad en Canarias dentro de las actividades del Gobierno de Canarias por el Día Mundial del Medio Ambiente.

GUIRRE es un proyecto bastante especial para mí por varias razones. La primera de ellas porque fue la primera vez que ejecutamos un proyecto utilizando integración continua (Jenkins) y tests con Selenium IDE.

Al inicio del proyecto, antes de comenzar a programar, definimos una sección ‘Cómo probarlo’ para cada funcionalidad a desarrollar. Grabamos tests con Selenium, siguiendo lo indicado en esta sección, que servían para demostrar que la nueva característica funcionaba correctamente. Si encontrábamos un bug, grabábamos también un test que lo reprodujese. Cuando el test dejaba de marcarse en rojo, ya lo habíamos arreglado.

Cada dos semanas, grabábamos todos los test del Sprint en una ‘suite’ de Selenium. Cada noche, el servidor de integración continua, Jenkins, ejecutaba esta suite y las suites de todos los Sprints anteriores e informaba si había habido errores. Si la mañana anterior un programador había modificado código que afectaba a las funcionalidades desarrollada hace unos meses, Jenkins nos mostraba unos nubarrones muy oscuros.

La otra razón por la que GUIRRE es un proyecto muy querido para mí es porque se logró terminar por debajo de lo presupuestado (sí estos proyectos existen) a pesar de asumir totalmente el coste del aprendizaje con Jenkins y Selenium y de que el presupuesto era muy ajustado. Todo un reto.

Les dejo más abajo una fotos del acto y un enlace a la ponencia que presenté. Espero que les sea de su interés.

Esta web utiliza cookies propias y de terceros para su correcto funcionamiento y para fines analíticos. Contiene enlaces a sitios web de terceros con políticas de privacidad ajenas que podrás aceptar o no cuando accedas a ellos. Al hacer clic en el botón Aceptar, acepta el uso de estas tecnologías y el procesamiento de tus datos para estos propósitos. Más información
Privacidad