Automatización de Pruebas Web con Selenium RC y Ant

En este post vamos a ver cómo realizar pruebas sobre páginas web de una forma sencilla y rápida. En primer lugar vamos a explicar qué es Selenium:
Selenium es un framework de pruebas portable para aplicaciones web. Las pruebas pueden ser escritas directamente en tablas HTML o codificadas en un gran número de lenguajes de programación (PHP, Ruby, Java, JavaScript, etc.) y se ejecutan directamente sobre el navegador (soporta Firefox, IE, Opera, Safari y algunos más). Además podemos desplegar Selenium en distintos sistemas operativos.
Selenium está formado por varios proyectos:
  • Selenium Core: Es el sistema de pruebas original basado en JavaScript. Actualmente es usado por Selenium Remote Control aunque puede utilziarse como un sistema de pruebas JavaScript/HTML
  • Selenium IDE: Es un plugin de Firefox que facilita la tarea de grabar y ejecutar pruebas HTML. Podemos incluso exportar dichos test HTML a los distintos lenguajes de programación.
  • Selenium Remote Control: Es un sistema cliente/servidor que nor permite controlar los navegadores web localmente o sobre otros ordenadores usando un lenguaje de programación y el framework de pruebas.
  • Selenium Grid: Permite la ejecución de pruebas en varios servidores de una forma distribuida
  • Otros proyectos: Selenium on Rails, Selenium on Ruby y CubiText (Eclipse)

Como puede verse, disponemos de muchas herramientas para hacer pruebas dentro de Selenium. En el siguiente blog se muestra un tutorial sobre cómo hacer pruebas mediante Selenium IDE:

En este tema mostraré cómo crear un proyecto Ant que ejecute las pruebas de forma automática. Para ello ejecutaremos una prueba simple sobre la página DZone.

En primer lugar vamos a crear la estructura de directorios de nuestro proyecto:
Proyecto
|-lib
|_|-selenium-server.jar
|_|-sslSupport
|_|_|-cybervillainsCA.cer
|-testdir
|_|-ficheroTest.html
|_|-TestSuite.html
|-reports
|-build.xml

Ahora veremos uno a uno los directorios:
  • lib: Los ficheros dentro de la carpeta 'lib' podemos obtenerlos de la distribución de Selenium RC, en la página de descarga de Selenium
  • testdir: Dentro de este directorio almacenaremos los tests HTML creados con Selenium IDE o creados a mano. Importante crear un fichero TestSuite.html que consiste en una página web con referencias a los tests que queremos ejecutar. Este fichero tiene la siguiente estructura y puede crearse también mediante el plugin Selenium IDE.

<!--
Copyright 2004 ThoughtWorks, Inc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<html>
<head>
<meta content="text/html; charset=ISO-8859-1" http-equiv="content-type">
<title>Test Suite</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td>
<a href="./ficheroTest.html">ficheroTest.html</a>
</td></tr>
</tbody>
</table>
</body>
</html>

Añadiremos tantas filas en la tabla como ficheros de test tengamos. En nuestro caso sólo tenemos un fichero de test con el siguiente aspecto:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<link rel="selenium.base" href="http://www.dzone.com/" />
<title>New Test</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr>
<td rowspan="1" colspan="3">New Test</td>
</tr>
</thead>
<tbody>
<tr>
<td>open</td>
<td>/links/index.html</td>
<td></td>
</tr>
<tr>
<td>verifyTitle</td>
<td>dzone.com - fresh links for developers</td>
<td></td>
</tr>
<tr>
<td>verifyElementPresent</td>
<td>//img[@alt='DZone Logo']</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Add a new link</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Popular links</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>New links</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Saved</td>
<td></td>
</tr>
<tr>
<td>verifyTextPresent</td>
<td>Shared</td>
<td></td>
</tr>
</tbody>
</table>
</body>
</html>

Como vemos, la estructura de un fichero de test HTML de Selenium es muy simple, una tabla en la que cada fila es un comando de selenium. En este ejemplo se realizan las siguientes opciones:
  1. Especificamos la URL base (selenium.base) mediante un elemento <link>
  2. Abrimos la página links/index.html dentro de la URL base
  3. Verificamos el título de la página
  4. Verificamos que exista una imagen con el atributo 'alt' igual a DZone Logo
  5. Verificamos unos cuantos de textos presentes ('Add a new link', 'Popular links', 'New Links', etc.

  • reports: En este directorio se almacenará el resultado de pasar los test

Una vez que tenemos la estructura creada con nuestros ficheros de test sólo nos queda crear el fichero build.xml que contendrá los comandos para iniciar el servidor de Selenium y ejecutar los test contra él. A continuación se muestra el fichero de Ant:
<project name="functional-tests" default="test-principal" basedir=".">  
<target name="all">    
<antcall target="run-selenium-tests" />
<antcall target="stop-server" />
</target>
<target name="clean">
<delete dir="reports"/>
</target>  
<target name="test-principal">
<property name="base.url" value="http://www.dzone.com/" />
<property name="test.dir" value="testdir" />
<property name="reports.dir" value="reports" />
<antcall target="all"/>
</target>
<target name="run-selenium-tests">
<property name="firefox" value="*chrome" />
<mkdir dir="${reports.dir}" />
<java jar="lib/selenium-server.jar" fork="true">
<arg line="-htmlSuite &quot;${firefox}&quot;" />
<arg line="&quot;${base.url}&quot;" />
<arg line="&quot;${test.dir}/TestSuite.html&quot;" />
<arg line="&quot;${reports.dir}/results.html&quot;" />
<arg line="-timeout 90" />
</java>
</target>
<target name="start-server">
<java jar="lib/selenium-server.jar" fork="true" spawn="true" />
<echo taskname="selenium-shutdown" message="Servidor iniciado" />
</target>
<target name="stop-server">
<get taskname="selenium-shutdown" src="http://localhost:4444/selenium-server/driver/?cmd=shutDown" dest="result.txt" ignoreerrors="true" />
<echo taskname="selenium-shutdown" message="Servidor apagado" />
</target>
</project>

Hay que tener en cuenta que las propiedades se definen en el target 'test-principal', aquí podemos cambiar la URL base para aplicarla a nuestro proyecto y también cambiar el nombre de los directorios si queremos. Puedes descargar el proyecto sin el contenido de la carpeta 'lib' aquí.
Espero que os sea de utilidad, saludos.

1 comentarios:

Argies_Dario dijo...

Muchas gracias, me fue util.

Publicar un comentario