2011-08-19 9 views
9

Puede usar el indicador --stop-on-failure para interrumpir la prueba de la unidad cuando falla una de las pruebas.Vuelva a ejecutar la última prueba fallida en PHPUnit

¿Hay alguna manera rápida de decirle a PHPUnit que vuelva a ejecutar esta prueba fallida, en lugar de proporcionar la ruta completa de forma manual?

Respuesta

9

Eche un vistazo a la opción cli --filter. Puede encontrar un ejemplo en el organisation docs y en el CLI Docs.

--filter

sólo se ejecuta pruebas cuyo nombre coincide con el patrón dado. El patrón puede ser el nombre de una prueba única o una expresión regular que coincida con múltiples nombres de prueba.

Suponga que su carrera phpunit Tests/ y Tests/Stuff/ThatOneTestClassAgain::testThisWorks falla:

sus opciones son:

phpunit --filter ThatOneTestClassAgain

y

phpunit --filter testThisWorks

o la mayoría de las otras cadenas que de alguna manera tiene sentido

+2

Si usted tiene una configuración phpunit.xml para sus pruebas, he creado un pequeño script bash que usará el registro phpunit de su última ejecución de prueba para llenar este --filter con clases que contengan pruebas fallidas. Simplemente lea los comentarios sobre esta [esencia] (https://gist.github.com/bksunday/6922149#file-test-run-failed). – bksunday

2

La forma en que lo he encontrado para implementarlo es bastante fácil, pero requiere que se implemente el registro. Configura phpunit para iniciar sesión en un archivo json. A continuación, se altera el orden PHPUnit a algo similar a:

cd /home/vagrant/tests && php -d auto_prepend_file=./tests-prepend.php /usr/local/bin/phpunit 

Lo que esto hace es auto_prepend un archivo PHP antes de la ejecución de PHPUnit. De esta forma, podemos capturar $ argsv y suministrar el comando de filtro requerido automáticamente a phpunit.

pruebas-prepend.php (asegúrese de modificar la ruta de archivo del registro JSON)

<?php 

global $argv, $argc; 
if(empty($argv) === false) { 
    // are we re-running? 
    $has_rerun = false; 
    foreach ($argv as $key => $value) { 
     if($value === '--rerun-failures') { 
      $has_rerun = true; 
      unset($argv[$key]); 
      break; 
     } 
    } 
    if($has_rerun === true) { 
     // validate the path exists and if so then capture the json data. 
     $path = realpath(dirname(__FILE__).'/../logs/report.json'); 
     if(is_file($path) === true) { 
      // special consideration taken here as phpunit does not store the report as a json array. 
      $data = json_decode('['.str_replace('}{'.PHP_EOL, '},{'.PHP_EOL, file_get_contents($path).']'), true); 
      $failed = array(); 
      // capture the failures as well as errors but taking care not to capture skipped tests. 
      foreach ($data as $event) { 
       if($event['event'] === 'test') { 
        if($event['status'] === 'fail') { 
         $failed[] = array($event['test'], 'failed'); 
        } 
        elseif($event['status'] === 'error' && $event['trace'][0]['function'] !== 'markTestIncomplete') { 
         $failed[] = array($event['test'], 'error\'d'); 
        } 
       } 
      } 
      if(empty($failed) === true) { 
       echo 'There are no failed tests to re-run.'.PHP_EOL.PHP_EOL; 
       exit; 
      } 
      else{ 
       echo '--------------------------------------------------------------------'.PHP_EOL; 
       echo 'Re-running the following tests: '.PHP_EOL; 
       foreach ($failed as $key => $test_data) { 
        echo ' - '.$test_data[0].' ('.$test_data[1].')'.PHP_EOL; 
        // important to escapre the namespace backslashes. 
        $failed[$key] = addslashes($test_data[0]); 
       } 
       echo '--------------------------------------------------------------------'.PHP_EOL.PHP_EOL; 
      } 
      $argv[] = '--filter'; 
      $argv[] = '/('.implode('|', $failed).')/'; 
      // important to update the globals in every location. 
      $_SERVER['argv'] = $GLOBALS['_SERVER']['argv'] = $GLOBALS['argv'] = $argv = array_values($argv); 
      $_SERVER['argc'] = $GLOBALS['_SERVER']['argc'] = $GLOBALS['argc'] = $argc = count($argv); 
     } 
     else{ 
      echo 'The last run report log at '.$path.' does not exist so it is not possible to re-run the failed tests. Please re-run the test suite without the --rerun-failures command.'.PHP_EOL.PHP_EOL; 
      exit; 
     } 
    } 
} 
Cuestiones relacionadas