RunFailed.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Codeception\Extension;
  3. use Codeception\Event\PrintResultEvent;
  4. use Codeception\Events;
  5. use Codeception\Extension;
  6. use Codeception\Test\Descriptor;
  7. /**
  8. * Saves failed tests into tests/log/failed in order to rerun failed tests.
  9. *
  10. * To rerun failed tests just run the `failed` group:
  11. *
  12. * ```
  13. * php codecept run -g failed
  14. * ```
  15. *
  16. * Starting from Codeception 2.1 **this extension is enabled by default**.
  17. *
  18. * ``` yaml
  19. * extensions:
  20. * enabled: [Codeception\Extension\RunFailed]
  21. * ```
  22. *
  23. * On each execution failed tests are logged and saved into `tests/_output/failed` file.
  24. */
  25. class RunFailed extends Extension
  26. {
  27. public static $events = [
  28. Events::RESULT_PRINT_AFTER => 'saveFailed'
  29. ];
  30. protected $config = ['file' => 'failed'];
  31. public function _initialize()
  32. {
  33. $logPath = str_replace($this->getRootDir(), '', $this->getLogDir()); // get local path to logs
  34. $this->_reconfigure(['groups' => ['failed' => $logPath . $this->config['file']]]);
  35. }
  36. public function saveFailed(PrintResultEvent $e)
  37. {
  38. $file = $this->getLogDir() . $this->config['file'];
  39. $result = $e->getResult();
  40. if ($result->wasSuccessful()) {
  41. if (is_file($file)) {
  42. unlink($file);
  43. }
  44. return;
  45. }
  46. $output = [];
  47. foreach ($result->failures() as $fail) {
  48. $output[] = $this->localizePath(Descriptor::getTestFullName($fail->failedTest()));
  49. }
  50. foreach ($result->errors() as $fail) {
  51. $output[] = $this->localizePath(Descriptor::getTestFullName($fail->failedTest()));
  52. }
  53. file_put_contents($file, implode("\n", $output));
  54. }
  55. protected function localizePath($path)
  56. {
  57. $root = realpath($this->getRootDir()) . DIRECTORY_SEPARATOR;
  58. if (substr($path, 0, strlen($root)) == $root) {
  59. return substr($path, strlen($root));
  60. }
  61. return $path;
  62. }
  63. }