Mostrando las entradas con la etiqueta testing. Mostrar todas las entradas
Mostrando las entradas con la etiqueta testing. Mostrar todas las entradas

domingo, 24 de abril de 2011

Porqué encontramos bugs en versiones estables

 



Asterisk es uno de los proyectos software orientados a comunicaciones más grandes que existen actualmente, por este motivo, es uno de los proyectos en los que la comunidad tiene más importancia de la que normalmente suele tener en estos proyectos dirigidos por empresas en los que se “inyecta” dinero para pagar a desarrolladores con objeto de continuar el desarrollo y solucionar los distintos fallos que se van encontrando continuamente. Cualquiera que haya estudiado programación, recordará que un programador puede, mediante un diseño estructurado, y una buena planificación, técnica y pruebas, evitar la aparición de bugs, pero jamás se puede garantizar la “no existencia” de estos, por lo que una vez entregado el proyecto, es común que los usuarios continúen aportando su “granito de arena” ofreciendo el famoso “feedback” consistente en comentarios acerca del buen o mal funcionamiento de las características de una aplicación software.


Asterisk, como gran proyecto formado por cientos de archivos, módulos, librerías y un largo etcétera, necesita continuamente el “feedback” de sus usuarios con el objeto de identificar tan pronto como sea posible cualquier comportamiento anómalo, no contemplado y perjudicial para la mayoría de los usuarios, por lo que se pone a disposición de todo el mundo, diferentes versiones -inicialmente inestables- de forma que los usuarios puedan probar dicha versión antes de que se convierta en una versión considerada como estable, pero ¿porqué si existen métodos de detección de errores antes de publicar una versión estable, encontramos bugs en estas últimas?


 


Existe unas versiones conocidas como “team“: http://svn.digium.com/svn/asterisk/team/ en las que los desarrolladores ponen a disposición de los usuarios versiones de Asterisk con nuevas características que estos han solicitado o que el desarrollador quiere implementar en Asterisk. De esta forma, lo que se busca es que los usuarios interesados en estas características, descarguen, prueben y verifiquen junto con el desarrollador que el funcionamiento de las nuevas características son correctas y lo más estable posible (considerando que los usuarios interesados son minoría).



Una vez verificado el funcionamiento de la nueva característica, los cambios que la conforman, son aplicados a una versión “inestable” llamada “Trunk“: http://svn.digium.com/svn/asterisk/trunk/. Esta versión es considerada la “versión de la comunidad” ya que si alguien quiere aportar su grano de arena en la evolución de Asterisk, esta es la versión que puede utilizar para la caza de bugs de forma que cualquier usuario que pruebe la versión Trunk y descubra un bug, debería informar sobre él (y sobre todo, cómo ha conseguido reproducirlo) en la webhttps://issues.asterisk.org/. De esta forma, y tras solucionar los bugs de la versión “trunk”, la versión “estable” (branch) ya no incluirá los bugs más fáciles de reproducir.


Ahora bien, a modo de autocrítica, comentar que el 90% de los usuarios de Asterisk jamás han instalado la versión Trunkel 99% de los usuarios jamás han informado de un bug en la web https://issues.asterisk.org/ pero eso sí, cuando han encontrado un bug, la gran mayoría preguntan en foros, listas y webs para buscar una solución rápidamente ya que la detección ocurre cuando han realizado una instalación a un cliente y este empieza a enfadarse, lo que nos lleva a varias conclusiones:


1.- La mayoría de los usuarios de Asterisk únicamente les interesa el producto (ad hoc) y no tienen interés en colaborar instalando versiones “inestables” y reportando los bugs que se detectan. Es decir: lo mismo les daría utilizar Asterisk, un sistema propietario, comercial o incluso una solución franquiciada tipo centralita-de-toda-la-vida, mientras eso agrade al cliente y sea rentable económicamente.


2.- Una gran cantidad de supuestos profesionales, no prueban las necesidades del cliente ANTES, y por lo tanto se encuentran con los bugs cuando están en medio de la implementación (lo que se conoce coloquialmente como ‘en casa del cliente’). Esto puede ser tanto porque no se conocen bien las necesidades del cliente hasta el último momento (lo que implica una mala gestión) o bien porque el cliente cambia sus necesidades en el último momento (lo que implica un fallo en la parte de consultoría).


3.- Otro motivo puede ser la imposibilidad de hacer pruebas, bien porque el usuario de Asterisk no disponga en sus instalaciones de los recursos necesarios para estas pruebas (un simulador de líneas), tiempo suficiente o los conocimientos necesarios para simular la instalación en local ANTES de comenzar la implementación en el usuario final.


4.- Por último (y quizá este sea el  motivo más común) es que se peca de exceso de confianza, considerando que una versión “estable” ya ha sido probada por suficiente gente y por lo tanto, se puede ahorrar el hecho de revisar si todo funciona como debería ya que -“¿porqué va a fallar algo que ha estado funcionando perfectamente en todas las versiones anteriores?”- Una mezcla entre confianza ciega,despreocupación y cierto grado de vagueza que provoca que en el último momento, cuando el “cliente final” haga de betatester involuntario de la versión estable que le han instalado y configurado, descubra con una gran sorpresa que aquello que le dijeron que funcionaba, no lo hace como esperaba. Está claro que si esta es la razón del porqué existen bugs en las versiones “estables”, no es culpa de los desarrolladores, si no de varios motivos, empezando por aquellos usuarios que no han probado la versión Trunk lo suficiente, continuando por el usuario que instala el Asterisk y que no ha verificado que todo funcionaba correctamente y por último del cliente final por haber seleccionado a una empresa que no es todo lo responsable que debería.


Por estos motivos, y como siempre se suele decir: más vale prevenir que curar, se podrían dar varios consejos para evitar situaciones embarazosas a la vez que se colabora en la estabilidad del proyecto Asterisk:



  • - Intentar obtener todos los datos posibles sobre las necesidades del cliente, configuraciones completas, terminales, funcionamiento estandar del sistema y elaborar una lista completa de “pruebas” de calidad que la solución deberá pasar antes de iniciar la implementación sin “obviar” ninguna características por muy probada que esté y muy común que esta sea. (por ejemplo: no es la primera vez que aparece una versión de Asterisk donde no funciona el Pickup y se detecta demasiado tarde por no haber hecho una simple prueba de 10 segundos).

  • - Intentar formarse tanto técnica como comercialmente para conocer lo que se ofrece, conocer las limitaciones y las ventajas frente al resto de sistemas para evitar ofertar lo que no se sabe hacer y hacer el ridículo cuando el cliente vea cómo preguntan en las listas acerca de algo que en la página web de la empresa se dice que se domina perfectamente.

  • - Intentar simular tan exactamente como sea posible toda la instalación de forma escalada (no hace falta desplegar 500 terminales SIP) pero sí probar todas las características de cada modelo de terminal y verificar la versión de firmware que cumple con todas las características que promete el fabricante.

  • - Cuando se detecte un error en Asterisk, lo primero que hay que hacer es preguntar en las listas de usuarios (asterisk-users y Asterisk-ES) por si es un fallo de configuración  o bien es un verdadero “bug” de Asterisk, en cuyo caso debemos informar de este en https://issues.asterisk.org/, por lo que deberíamos analizar los pasos que hemos realizado y que nos ha producido ese error, de forma que los desarrolladores puedan reproducirlo y descubrir dónde está el error. En caso de que sea realmente un bug, serás recompensado como colaborador bug-hunter de la próxima versión estable. Por este motivo siempre es recomendable cazar los bugs en la versión “trunk”… para evitar que lleguen a la versión “estable”.


Así que la próxima vez que veas a alguien quejarse de que la versión estable tiene algún bug, párate a pensar por un momento la cantidad de personas que han descargado la versión anterior Trunk, y no lo han detectado, seguramente te de una idea de la cantidad de personas que, aun utilizando Asterisk, aprovechándose del trabajo de cientos de desarrolladores que dedican horas de forma totalmente desinteresada a este proyecto, realmente contribuyen a su desarrollo.


En una conversación en un grupo de usuarios de linux hubo una frase que me llamó la atención:



-”En el mundo del software libre, hay dos tipos de empresas: las que contribuyen de una forma u otra en el desarrollo del software libre, y las que únicamente les interesa la gratuidad del producto intentando conseguir todo el jugo posible del esfuerzo de los demás, pero que cuando les toca a ellos desarrollar algo, lo hacen como software privativo para que nadie más pueda usarlo.



Fuente: Sinologic.net

viernes, 30 de abril de 2010

Installing the Asterisk Test Suite

Ayer en el blog oficial de asterisk postearon un artículo interesante acerca de la test suite de asterisk, les recomiendo leer el archivo README que tiene para ver de que se trata la idea, esta muy interesante espero poderlo empezar a probar en mi maquina virtual, saludos. Aquí va el post:

The Asterisk Test Suite is a way of developing external tests to Asterisk in order to test for functionality differences between different versions of Asterisk. By creating automated tests you are able to verify functionality you depend on remains undisturbed by changes in the code base. Tests you write can even be submitted back to the Asterisk project in order for them to be included directly in the test suite where the automated testing framework can execute the tests so developers will be alerted if a change they make causes a test to fail.

In order to write these tests we need to be able to run the test suite on our development machine (typically a virtual machine or some other box which you won’t be using for production). We’ll be installing the test suite on an Ubuntu Server 9.10 along with the dependencies, then running the automated tests. Writing automated tests though is beyond the scope of this document. See the README.txt file in the testsuite/ directory for more information (http://svn.asterisk.org/svn/testsuite/asterisk/trunk/README.txt).

We’ll be starting with a fresh, minimal install of Ubuntu Server 9.10, so once you’ve gotten that installed, feel free to move on.

Installing Dependencies


Before we get started building the test suite, we need to install the dependencies it requires. The following applications are necessary to run all the currently developed tests, but additional dependencies surely will be required in the future. The current list of dependencies is available in the README.txt file within the testsuite/ repository (referenced earlier). Don’t worry about installing all these dependencies now, because we’re going to step through all the applications you need to install throughout the post.

  • SIPp

  • python >= 2.4

  • python-yaml

  • bash

  • asttest

  • StarPy

  • python-twisted


Building Asterisk and the Test Suite


The Asterisk Test Suite must be installed and run as root, so if you’re not root, switch now (sudo su -) and we’ll get started!

First thing we want to do is create our directory structure and then checkout the version of Asterisk we want to test, and then grab the test suite. If you haven’t already installed Subversion, then do that now (apt-get install subversion).
# cd /usr/src/
# mkdir asterisk-complete
# cd asterisk-complete
# mkdir asterisk
# cd asterisk
# svn co http://svn.asterisk.org/svn/asterisk/branches/1.6.2 1.6.2-vanilla
# cd 1.6.2-vanilla
# svn co http://svn.asterisk.org/svn/testsuite/asterisk/trunk testsuite

Notice that we checked out the latest 1.6.2 branch and named it 1.6.2-vanilla. We then changed into the 1.6.2-vanilla directory and checked out the test suite. This is because the scripts being run from the test suite expect to be located in a subdirectory of Asterisk.

The test suite expects Asterisk to already be installed the first time it runs, so we should make sure we can compile Asterisk. We can find the bare dependencies we need with the./configure script and install those one at a time as it fails to find the necessary components for compiling.

Note: Of course you don’t have to run ./configure multiple times — you could just install all the necessary dependencies by running: apt-get install gcc g++ libxml2-dev





# pwd
/usr/src/asterisk-complete/asterisk/1.6.2-vanilla
# ./configure
configure: error: no acceptable C compiler found in $PATH

So we have our first dependency to resolve. In this case we’re missing the GCC compiler, so lets install that now with: apt-get install gcc. Several package dependencies will be listed. Press Y to continue with the installation of GCC and its dependencies.

Now that we have our GCC compiler installed lets see what our next dependency is.
# ./configure
configure: error: C++ preprocessor "/lib/cpp" fails sanity check

We’re missing the GCC C++ preprocessor, which can be installed by running: apt-get install g++. You will see several dependencies listed and they can all be installed by pressing Y.

If we run ./configure again we appear to get much closer, but not quite all the way.
# ./configure
checking for xml2-config... no
configure: *** XML documentation will not be available because the 'libxml2' development package is missing.
configure: *** Please run the 'configure' script with the '--disable-xmldoc' parameter option
configure: *** or install the 'libxml2' development package.

Appears we’re missing the development libraries for the XML documentation. Lets install that now with: apt-get install libxml2-dev. A couple of dependencies will be installed along with libxml2-dev after pressing Y.
# ./configure
configure: error: *** termcap support not found (on modern systems, this typically means the ncurses development package is missing)

Lets install the missing ncurses-dev package and dependencies with: apt-get install ncurses-dev
# ./configure
configure: Package configured for:
configure: OS type  : linux-gnu
configure: Host CPU : i686
configure: build-cpu:vendor:os: i686 : pc : linux-gnu :
configure: host-cpu:vendor:os: i686 : pc : linux-gnu :

That’s it! If you see the big Asterisk symbol in ASCII text then you’ve made it to the end. Of course this is the bare minimum to get Asterisk compiled and installed, but we’ll use this for now. We’ll likely need to install some additional packages later to meet the dependencies of the test suite.

Lets try running the runtests.py script found in the testsuite/ subdirectory located in our Asterisk source. Remember that we checked this out earlier and is not part of the standard Asterisk checkout.
# cd testsuite/
# ./runtests.py
Traceback (most recent call last):
File "./runtests.py", line 15, in <module>
import yaml
ImportError: No module named yaml

OK, so we’re missing the python yaml package. We can install this with: apt-get install python-yaml

If we run the runtests.py script again we’ll get the following error:
# ./runtests.py
I/O Error getting Asterisk version from ../include/asterisk/version.h

This means we didn’t compile and install Asterisk prior to running our tests! So before continuing with our test suite install, we need to install Asterisk.
# cd ..
# pwd
/usr/src/asterisk-complete/asterisk/1.6.2-vanilla
# make install

Now that we have installed Asterisk, lets see where that gets us with our runtests.pyscript. We’re going to pass it the -l flag in order to list the tests we could potentially run, and the status of the dependencies they require.
# cd testsuite/
# ./runtests.py -l
Configured tests:
001) example
--> Summary: Check to see if the Asterisk binary has been installed
--> Minimum Version: 1.4 (True)
--> Dependency: bash -- Met: True
002) ami-login
--> Summary: Test loggin in to the Asterisk Manager Interface
--> Minimum Version: 1.4 (True)
--> Dependency: twisted -- Met: True
--> Dependency: starpy -- Met: False
003) blind-transfer-accountcode
--> Summary: Test account code propagation for SIP blind transfers.
--> Minimum Version: 1.4 (True)
--> Dependency: bash -- Met: True
--> Dependency: sipp -- Met: False
--> Dependency: asttest -- Met: False
004) rfc2833_dtmf_detect
--> Summary: Test RFC2833 DTMF detection
--> Minimum Version: 1.4 (True)
--> Dependency: bash -- Met: True
--> Dependency: sipp -- Met: False
--> Dependency: asttest -- Met: False
005) sip_channel_params
--> Summary: Test Retrieval of SIP CHANNEL parameters
--> Minimum Version: 1.8 (False)
--> Dependency: bash -- Met: True
--> Dependency: sipp -- Met: False
--> Dependency: asttest -- Met: False
006) iax-call-basic
--> Summary: Test a basic IAX2 call
--> Minimum Version: 1.4 (True)
--> Dependency: twisted -- Met: True
--> Dependency: starpy -- Met: False
007) manager-action-events-response
--> Summary: Test the presence and absence of a response from the Events manager action
--> Minimum Version: 1.4 (True)
--> Dependency: bash -- Met: True
--> Dependency: asttest -- Met: False
008) originate-cdr-disposition
--> Summary: Test for proper CDR dispositions when originating calls.
--> Minimum Version: 1.4 (True)
--> Dependency: bash -- Met: True
--> Dependency: sipp -- Met: False
--> Dependency: asttest -- Met: False
009) func_srv
--> Summary: Test func_srv for correctness
--> Minimum Version: 1.8 (False)
--> Dependency: asttest -- Met: False
010) sip_outbound_address
--> Summary: Test explicit outbound host for SIP calls
--> Minimum Version: 1.4 (True)
--> Dependency: bash -- Met: True
--> Dependency: sipp -- Met: False
--> Dependency: asttest -- Met: False

There will likely be more by the time you try this out, but I think that’s a pretty good sampling. Looking through the tests we can see several dependencies being met with True and several others being met with False. Our goal now is to make sure we satisfy all the dependencies for the tests prior to running them. Starting at the top, the first dependency we haven’t satisfied is starpy.

From the StarPy website at http://www.vrplumber.com/programming/starpy/, “StarPy is a Python + Twisted protocol that provides access to the Asterisk PBX’s Manager Interface (AMI) and Fast Asterisk Gateway Interface (FastAGI). Together these allow you write both command-and-control interfaces (used, for example to generate new calls) and to customise user interactions from the dial-plan.  You can readily write applications that use the AMI and FastAGI protocol together with any of the already-available Twisted protocols“. Basically some tests are using it to generate calls in Asterisk to perform various tests.

We can install StarPy with the following commands:
# cd /usr/src/asterisk-complete/
# mkdir thirdparty
# cd thirdparty
# svn co https://starpy.svn.sourceforge.net/svnroot/starpy
# cd starpy/trunk/
# python setup.py install

You can see that we created a thirdparty/ directory within our asterisk-complete/directory and checked out the latest version of StarPy. We then installed it via the setup.pyscript, and that’s it for satisfying the StarPy dependency.

After we change back to our testsuite/starpy dependency is satisfied:
# cd /usr/src/asterisk-complete/asterisk/1.6.2-vanilla/testsuite/
# ./runtests.py -l
...
--> Dependency: starpy -- Met: True
...

Let’s look and see what our next dependency is. Scrolling down a bit we can see the following:
--> Dependency: sipp -- Met: False

We need to install SIPp which is used for generating calls into the system. SIPp is a very useful utility for load testing Asterisk and executing detailed call flows. More information about SIPp is available at http://sipp.sourceforge.net/. We must install SIPp from source because some of the tests are already using advanced functionality for testing things like DTMF, so wecan’t use the precompiled sip-tester package.

Note: Be sure to grab the latest SIPp snapshot. Right now that is version 2009-07-29.


# cd /usr/src/asterisk-complete/thirdparty
# mkdir sipp
# cd sipp
# wget http://sipp.sourceforge.net/snapshots/sipp.2009-07-29.tar.gz
# tar zxvf sipp.2009-07-29.tar.gz
# cd sipp.svn
# make pcapplay
send_packets.c:44:18: error: pcap.h: No such file or directory
make[1]: *** [send_packets.o] Error 1
make[1]: Leaving directory `/usr/src/asterisk-complete/thirdparty/sipp/sipp.svn'
make: *** [pcapplay] Error 2

Uh oh! We’re missing pcap support! Lets install that now.
# apt-get install libpcap-dev

Now we can compile SIPp with pcap support. There is no ‘make install‘ target to run, so we can just copy the resulting sipp binary to /usr/bin (or some other appropriate location that exists in your path).
# make pcapplay
# cp sipp /usr/bin
# cd /usr/src/asterisk-complete/asterisk/1.6.2-vanilla/testsuite/

After verifying that the SIPp dependency is available, we notice the next one in our list is asttest.
--> Dependency: asttest -- Met: False

The asttest dependency is an application distributed as part of the Asterisk test suite. It is dependent on Lua and the Lua development libraries. Switching in to the asttest/ directory and running ‘make‘ will provide the following error:
# cd asttest/
# pwd
/usr/src/asterisk-complete/asterisk/1.6.2-vanilla/testsuite/asttest
# make
make[1]: *** [src/lfs.o] Error 1
make[1]: Leaving directory `/usr/src/asterisk-complete/asterisk/1.6.2-vanilla/testsuite/asttest/lib/lua/luafilesystem-1.4.2'
make: *** [lib/lua/luafilesystem-1.4.2/src/lfs.o] Error 2

We can install the Lua development libraries and dependencies by running: apt-get install liblua5.1-0-dev lua5.1
# apt-get install liblua5.1-0-dev lua5.1

After installing Lua, we can run ‘make install‘ to install asttest.

At this point if you run ./runtests -l you will notice that all the dependencies have been satisfied (unless of course new tests have been added which require additional dependencies not yet required). So go ahead and run the tests and see if your checkout of Asterisk will pass all the tests!
# cd ..
# pwd
/usr/src/asterisk-complete/asterisk/1.6.2-vanilla/testsuite
# ./runtests.py

Once all the tests have completed, you’ll be provided a summary of the test that were run and their pass/fail status. The last part of the output will also be some XML output that you could use in scripts.
=== TEST RESULTS ===
--> example --- PASSED
--> ami-login --- PASSED
--> blind-transfer-accountcode --- PASSED
--> rfc2833_dtmf_detect --- PASSED
--> iax-call-basic --- PASSED
--> manager-action-events-response --- PASSED
--> originate-cdr-disposition --- PASSED

<?xml version="1.0" encoding="UTF-8"?>
<testsuite errors="0" time="158.71" tests="10" name="AsteriskTestSuite">
<testcase time="0.01" name="example"/>
<testcase time="25.51" name="ami-login"/>
<testcase time="12.24" name="blind-transfer-accountcode"/>
<testcase time="12.05" name="rfc2833_dtmf_detect"/>
<testcase time="20.35" name="iax-call-basic"/>
<testcase time="67.09" name="manager-action-events-response"/>
<testcase time="21.48" name="originate-cdr-disposition"/>
</testsuite>

As you can see, all 10 of our tests passed and took 158 seconds to execute. Now that you have the test suite infrastructure setup and executing all the tests, you can start building your own tests. More information about buildings tests is available in the README.txt file within the top level of your testsuite/ directory. Go forth and create tests!

miércoles, 2 de diciembre de 2009

Prueba Asterisk sin “ensuciar” tu sistema

Vamos a ver 2 maneras de hacerlo: instalando Asterisk en multiples lugares y utilizando live_ast.


Instalar Asterisk en distintos lugares


Si queremos tener un Asterisk 1.4 y un Asterisk 1.6 en el mismo sistema haremos lo siguiente para tener cada uno instalado en /opt por ejemplo:


cd asteriak14
./configure --prefix=/opt/asterisk14 --sysconfdir=/opt/asterisk14/etc --localstatedir=/opt/asterisk14}/var
make menuselect
make
make install
make samples


cd asteriak16
./configure --prefix=/opt/asterisk16 --sysconfdir=/opt/asterisk16/etc --localstatedir=/opt/asterisk16}/var
make menuselect
make
make install
make samples


En este ejemplo se asume que tenemos las fuentes de Asterisk 1.4 en un directorio llamado “asterisk14? y las de la 1.6 en “asterisk16?. De esta manera hemos conseguido tener dos versiones completamente aisladas en /opt. Las configuraciones estarán en /opt/asterisk14/etc y /opt/asterisk16/etc respectivamente.


Utilizar live_ast


Ésta es la que he descubierto hoy y me ha gustado  live_ast es un script que Tzafir Cohen hizo en bash que nos permite ejecutar Asterisk en el mismo directorio en el que lo hemos descargado. Esta disponible en trunk y en Asterisk 1.6, pero también funciona con Asterisk 1.4. Veamos como funciona:


cd asterisk-1.6.2
cp contrib/scripts/live_ast .
./live_ast configure
./live_ast install
./live_ast samples
./live_ast run -vvvvvvvvvc


Lo que realiza el script es fijar las variables necesarias para que Asterisk quede completamente instalado en el subdirectorio “live”.


FUENTE