Selenium IDE-Incorporando while (转http://www.adictosaltrabajo.com/tutoriales/tutoriales.php?pagina=seleniumWhile)

Fecha de publicación del tutorial: 2009-08-20

2.457


  Regístrate para votar

Share |

 

 


Selenium IDE-Incorporando while en los test
0. Índice de contenidos. 1. IntroducciónComo hemos visto en otros tutoriales publicados en Adictos Selenium IDE es un plugin de Firefox perteneciente al juego de herramientas SeleniumHQ y que permite realizar juegos de pruebas sobre aplicaciones web. Este IDE trae por defecto un conjunto muy amplio de comandos para poder realizar nuestros test de manera satisfactoria. Sin embargo puede que en ocasiones necesitemos realizar algunas operaciones que queden fuera del alcance de los comandos propios de Selenium IDE. En estos casos el propio IDE nos permite ampliar estos comandos con nuevas funciones definidas por el usuario y escritas en Java  script  .
En el caso que nos ocupa utilizaremos un  script  que nos permitirá realizar bucles dentro de nuestros test pero podríamos definir  script  s que se adaptaran a cada una de nuestras necesidades. 2. Entorno

El tutorial está escrito usando el siguiente entorno:

  • Hardware: Portátil Dell Latitude E5500(Core Duo T9550 2.66GHz, 4GB RAM, 340 GB HD).
  • Sistema operativo: Windows XP.
  • Firefox 3.0.13
  • Selenium IDE 1.0.2

3. Extensión goto_sel_ide.jsEsta extensión , no es una extensión propia,sino recopilada desde http://51elliot.blogspot.com/2008/02/selenium-ide-goto.html y con ella ,no solo podremos incluir bucles en nuestros test,sino que ademas podremos realizar sentencias condicionales como veremos mas adelante.
A continuación vemos las funciones incluidas en esta extensión:

 

 

view plaincopy to clipboardprint?

 

  1. var gotoLabels= {};   
  2. var whileLabels = {};   
  3.   
  4. // overload the original Selenium reset function   
  5. Selenium.prototype.reset = function() {   
  6.     // reset the labels   
  7.     this.initialiseLabels();   
  8.     // proceed with original reset code   
  9.     this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;   
  10.     this.browserbot.selectWindow("null");   
  11.     this.browserbot.resetPopups();   
  12. }   
  13.   
  14. Selenium.prototype.initialiseLabels = function()   
  15. {   
  16.     gotoLabels = {};   
  17.     whileLabels = { ends: {}, whiles: {} };   
  18.     var command_rows = [];   
  19.     var numCommands = testCase.commands.length;   
  20.     for (var i = 0; i < numCommands; ++i) {   
  21.         var x = testCase.commands[i];   
  22.         command_rows.push(x);   
  23.     }   
  24.     var cycles = [];   
  25.     for( var i = 0; i < command_rows.length; i++ ) {   
  26.         if (command_rows[i].type == 'command')   
  27.         switch( command_rows[i].command.toLowerCase() ) {   
  28.             case "label":   
  29.                 gotoLabels[ command_rows[i].target ] = i;   
  30.                 break;   
  31.             case "while":   
  32.             case "endwhile":   
  33.                 cycles.push( [command_rows[i].command.toLowerCase(), i] )   
  34.                 break;   
  35.         }   
  36.     }     
  37.     var i = 0;   
  38.     while( cycles.length ) {   
  39.         if( i >= cycles.length ) {   
  40.             throw new Error( "non-matching while/endWhile found" );   
  41.         }   
  42.         switch( cycles[i][0] ) {   
  43.             case "while":   
  44.                 if( ( i+1 < cycles.length ) && ( "endwhile" == cycles[i+1][0] ) ) {   
  45.                     // pair found   
  46.                     whileLabels.ends[ cycles[i+1][1] ] = cycles[i][1];   
  47.                     whileLabels.whiles[ cycles[i][1] ] = cycles[i+1][1];   
  48.                     cycles.splice( i, 2 );   
  49.                     i = 0;   
  50.                 } else ++i;   
  51.                 break;   
  52.             case "endwhile":   
  53.                 ++i;   
  54.                 break;   
  55.         }   
  56.     }   
  57. }   
  58.   
  59. Selenium.prototype.continueFromRow = function( row_num )   
  60. {   
  61.     if(row_num == undefined || row_num == null || row_num < 0) {   
  62.         throw new Error( "Invalid row_num specified." );   
  63.     }   
  64.     testCase.debugContext.debugIndex = row_num;   
  65. }   
  66.   
  67. // do nothing. simple label   
  68. Selenium.prototype.doLabel = function(){};   
  69.   
  70. Selenium.prototype.doGotolabel = function( label )   
  71. {   
  72.     if( undefined == gotoLabels[label] ) {   
  73.         throw new Error( "Specified label '" + label + "' is not found." );   
  74.     }   
  75.     this.continueFromRow( gotoLabels[ label ] );   
  76. };   
  77.   
  78. SeleniumSelenium.prototype.doGoto = Selenium.prototype.doGotolabel;   
  79.   
  80. Selenium.prototype.doGotoIf = function( condition, label )   
  81. {   
  82.     if( eval(condition) ) this.doGotolabel( label );   
  83. }   
  84.   
  85. Selenium.prototype.doWhile = function( condition )   
  86. {   
  87.     if( !eval(condition) ) {   
  88.         var last_row = testCase.debugContext.debugIndex;   
  89.         var end_while_row = whileLabels.whiles[ last_row ];   
  90.         if( undefined == end_while_row ) throw new Error( "Corresponding 'endWhile' is not found." );   
  91.         this.continueFromRow( end_while_row );   
  92.     }   
  93. }   
  94.   
  95. Selenium.prototype.doEndWhile = function()   
  96. {   
  97.     var last_row = testCase.debugContext.debugIndex;   
  98.     var while_row = whileLabels.ends[ last_row ] - 1;   
  99.     if( undefined == while_row ) throw new Error( "Corresponding 'While' is not found." );   
  100.     this.continueFromRow( while_row );   
  101. }  

 

var gotoLabels= {}; var whileLabels = {}; // overload the original Selenium reset function Selenium.prototype.reset = function() {     // reset the labels     this.initialiseLabels();     // proceed with original reset code     this.defaultTimeout = Selenium.DEFAULT_TIMEOUT;     this.browserbot.selectWindow("null");     this.browserbot.resetPopups(); } Selenium.prototype.initialiseLabels = function() {     gotoLabels = {};     whileLabels = { ends: {}, whiles: {} };     var command_rows = [];     var numCommands = testCase.commands.length;     for (var i = 0; i < numCommands; ++i) {         var x = testCase.commands[i];         command_rows.push(x);     }     var cycles = [];     for( var i = 0; i < command_rows.length; i++ ) {         if (command_rows[i].type == 'command')         switch( command_rows[i].command.toLowerCase() ) {             case "label":                 gotoLabels[ command_rows[i].target ] = i;                 break;             case "while":             case "endwhile":                 cycles.push( [command_rows[i].command.toLowerCase(), i] )                 break;         }     }      var i = 0;     while( cycles.length ) {         if( i >= cycles.length ) {             throw new Error( "non-matching while/endWhile found" );         }         switch( cycles[i][0] ) {             case "while":                 if( ( i+1 < cycles.length ) && ( "endwhile" == cycles[i+1][0] ) ) {                     // pair found                     whileLabels.ends[ cycles[i+1][1] ] = cycles[i][1];                     whileLabels.whiles[ cycles[i][1] ] = cycles[i+1][1];                     cycles.splice( i, 2 );                     i = 0;                 } else ++i;                 break;             case "endwhile":                 ++i;                 break;         }     } } Selenium.prototype.continueFromRow = function( row_num ) {     if(row_num == undefined || row_num == null || row_num < 0) {         throw new Error( "Invalid row_num specified." );     }     testCase.debugContext.debugIndex = row_num; } // do nothing. simple label Selenium.prototype.doLabel = function(){}; Selenium.prototype.doGotolabel = function( label ) {     if( undefined == gotoLabels[label] ) {         throw new Error( "Specified label '" + label + "' is not found." );     }     this.continueFromRow( gotoLabels[ label ] ); }; Selenium.prototype.doGoto = Selenium.prototype.doGotolabel; Selenium.prototype.doGotoIf = function( condition, label ) {     if( eval(condition) ) this.doGotolabel( label ); } Selenium.prototype.doWhile = function( condition ) {     if( !eval(condition) ) {         var last_row = testCase.debugContext.debugIndex;         var end_while_row = whileLabels.whiles[ last_row ];         if( undefined == end_while_row ) throw new Error( "Corresponding 'endWhile' is not found." );         this.continueFromRow( end_while_row );     } } Selenium.prototype.doEndWhile = function() {     var last_row = testCase.debugContext.debugIndex;     var while_row = whileLabels.ends[ last_row ] - 1;     if( undefined == while_row ) throw new Error( "Corresponding 'While' is not found." );     this.continueFromRow( while_row ); }  
Para poder hacer uso de esta extensión hemos de indicar a Selenium donde se encuentra desde el menú de opciones:



Será necesario cerrar y volver a abrir la ventana de IDE para que Selenium lea el fichero y tener los nuevos comandos disponibles.

4. Usando los nuevos comandos.En este punto vamos a ver como utilizar los nuevos comandos. En realidad no difiere mucho de cuando utilizamos el resto de comandos pero si que hay que tener en cuenta algunas consideraciones.
Comando while:



Como vemos en la imagen lo primero que hacemos es definir dos variables, una que marca el inicio y otra que marca el fin del bucle. En este caso, nuestro bucle dará cinco vueltas, ejecutando en cada una de ellas todos aquellos comandos que haya entre el comando while y endWhile. Como siempre después de realizar las acciones correspondientes aumentamos el contador que nos marca el fin del bucle.

Comando gotoLabel:
Este comando es muy sencillo de utilizar y nos permite desplazarnos a cualquier punto de nuestro test de una manera directa obviando todas aquellas acciones que este definidas desde el punto de origen hasta el punto de destino.



En realidad este comando no es de mucha utilidad pero es la base de comando gotoIf que veremos a continuación.

Comando gotoIf: Este comando en realidad no solo nos permite hacer una sentencia condicional sino que si esta condición se cumple permite ir directamente a otro punto de nuestro test. Por ejemplo:
Basándonos en el ejemplo del comando while ,imaginemos que nuestro test necesita hacer una serie de acciones para todas las iteraciones del bucle excepto para la ultima. Podría quedar algo como:


5. Conclusiones.Como hemos visto a lo largo del tutorial Selenium IDE nos permite de una manera sencilla incorporar nuevas funciones o comandos mediante la modificación del User-Extension. En esta ocasión he querido compartir esta extensión ya que me parecía muy interesante el uso de loops dentro de los test a pesar de que los otros dos nuevos comandos quizás no se adapten del todo a vuestras necesidades. Aunque a partir de ahora esto no debe suponer ningún problema ya que sabemos como definir nuestras propias extensiones mediante Java  script  .
Espero que les sirva de utilidad.

Un saludo.

Saúl

mailto:sgdiaz@autentia.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值