Recorder.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. namespace Codeception\Extension;
  3. use Codeception\Event\StepEvent;
  4. use Codeception\Event\TestEvent;
  5. use Codeception\Events;
  6. use Codeception\Exception\ExtensionException;
  7. use Codeception\Lib\Interfaces\ScreenshotSaver;
  8. use Codeception\Module\WebDriver;
  9. use Codeception\Step\Comment as CommentStep;
  10. use Codeception\Test\Descriptor;
  11. use Codeception\Util\FileSystem;
  12. use Codeception\Util\Template;
  13. /**
  14. * Saves a screenshot of each step in acceptance tests and shows them as a slideshow on one HTML page (here's an [example](http://codeception.com/images/recorder.gif))
  15. * Activated only for suites with WebDriver module enabled.
  16. *
  17. * The screenshots are saved to `tests/_output/record_*` directories, open `index.html` to see them as a slideshow.
  18. *
  19. * #### Installation
  20. *
  21. * Add this to the list of enabled extensions in `codeception.yml` or `acceptance.suite.yml`:
  22. *
  23. * ``` yaml
  24. * extensions:
  25. * enabled:
  26. * - Codeception\Extension\Recorder
  27. * ```
  28. *
  29. * #### Configuration
  30. *
  31. * * `delete_successful` (default: true) - delete screenshots for successfully passed tests (i.e. log only failed and errored tests).
  32. * * `module` (default: WebDriver) - which module for screenshots to use. Set `AngularJS` if you want to use it with AngularJS module. Generally, the module should implement `Codeception\Lib\Interfaces\ScreenshotSaver` interface.
  33. *
  34. *
  35. * #### Examples:
  36. *
  37. * ``` yaml
  38. * extensions:
  39. * enabled:
  40. * Codeception\Extension\Recorder:
  41. * module: AngularJS # enable for Angular
  42. * delete_successful: false # keep screenshots of successful tests
  43. * ```
  44. *
  45. */
  46. class Recorder extends \Codeception\Extension
  47. {
  48. protected $config = [
  49. 'delete_successful' => true,
  50. 'module' => 'WebDriver',
  51. 'template' => null,
  52. 'animate_slides' => true
  53. ];
  54. protected $template = <<<EOF
  55. <!DOCTYPE html>
  56. <html lang="en">
  57. <head>
  58. <meta charset="utf-8">
  59. <meta name="viewport" content="width=device-width, initial-scale=1">
  60. <title>Recorder Result</title>
  61. <!-- Bootstrap Core CSS -->
  62. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
  63. <style>
  64. html,
  65. body {
  66. height: 100%;
  67. }
  68. .carousel,
  69. .item,
  70. .active {
  71. height: 100%;
  72. }
  73. .navbar {
  74. margin-bottom: 0px !important;
  75. }
  76. .carousel-caption {
  77. background: rgba(0,0,0,0.8);
  78. padding-bottom: 50px !important;
  79. }
  80. .carousel-caption.error {
  81. background: #c0392b !important;
  82. }
  83. .carousel-inner {
  84. height: 100%;
  85. }
  86. .fill {
  87. width: 100%;
  88. height: 100%;
  89. text-align: center;
  90. overflow-y: scroll;
  91. background-position: top;
  92. -webkit-background-size: cover;
  93. -moz-background-size: cover;
  94. background-size: cover;
  95. -o-background-size: cover;
  96. }
  97. </style>
  98. </head>
  99. <body>
  100. <!-- Navigation -->
  101. <nav class="navbar navbar-default" role="navigation">
  102. <div class="navbar-header">
  103. <a class="navbar-brand" href="#">{{feature}}
  104. <small>{{test}}</small>
  105. </a>
  106. </div>
  107. </nav>
  108. <header id="steps" class="carousel{{carousel_class}}">
  109. <!-- Indicators -->
  110. <ol class="carousel-indicators">
  111. {{indicators}}
  112. </ol>
  113. <!-- Wrapper for Slides -->
  114. <div class="carousel-inner">
  115. {{slides}}
  116. </div>
  117. <!-- Controls -->
  118. <a class="left carousel-control" href="#steps" data-slide="prev">
  119. <span class="icon-prev"></span>
  120. </a>
  121. <a class="right carousel-control" href="#steps" data-slide="next">
  122. <span class="icon-next"></span>
  123. </a>
  124. </header>
  125. <!-- jQuery -->
  126. <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
  127. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  128. <!-- Script to Activate the Carousel -->
  129. <script>
  130. $('.carousel').carousel({
  131. wrap: true,
  132. interval: false
  133. })
  134. $(document).bind('keyup', function(e) {
  135. if(e.keyCode==39){
  136. jQuery('a.carousel-control.right').trigger('click');
  137. }
  138. else if(e.keyCode==37){
  139. jQuery('a.carousel-control.left').trigger('click');
  140. }
  141. });
  142. </script>
  143. </body>
  144. </html>
  145. EOF;
  146. protected $indicatorTemplate = <<<EOF
  147. <li data-target="#steps" data-slide-to="{{step}}" {{isActive}}></li>
  148. EOF;
  149. protected $indexTemplate = <<<EOF
  150. <!DOCTYPE html>
  151. <html lang="en">
  152. <head>
  153. <meta charset="utf-8">
  154. <meta name="viewport" content="width=device-width, initial-scale=1">
  155. <title>Recorder Results Index</title>
  156. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
  157. </head>
  158. <body>
  159. <!-- Navigation -->
  160. <nav class="navbar navbar-default" role="navigation">
  161. <div class="navbar-header">
  162. <a class="navbar-brand" href="#">Recorded Tests
  163. </a>
  164. </div>
  165. </nav>
  166. <div class="container">
  167. <h1>Record #{{seed}}</h1>
  168. <ul>
  169. {{records}}
  170. </ul>
  171. </div>
  172. </body>
  173. </html>
  174. EOF;
  175. protected $slidesTemplate = <<<EOF
  176. <div class="item {{isActive}}">
  177. <div class="fill">
  178. <img src="{{image}}">
  179. </div>
  180. <div class="carousel-caption {{isError}}">
  181. <h2>{{caption}}</h2>
  182. <small>scroll up and down to see the full page</small>
  183. </div>
  184. </div>
  185. EOF;
  186. public static $events = [
  187. Events::SUITE_BEFORE => 'beforeSuite',
  188. Events::SUITE_AFTER => 'afterSuite',
  189. Events::TEST_BEFORE => 'before',
  190. Events::TEST_ERROR => 'persist',
  191. Events::TEST_FAIL => 'persist',
  192. Events::TEST_SUCCESS => 'cleanup',
  193. Events::STEP_AFTER => 'afterStep',
  194. ];
  195. /**
  196. * @var WebDriver
  197. */
  198. protected $webDriverModule;
  199. protected $dir;
  200. protected $slides = [];
  201. protected $stepNum = 0;
  202. protected $seed;
  203. protected $recordedTests = [];
  204. public function beforeSuite()
  205. {
  206. $this->webDriverModule = null;
  207. if (!$this->hasModule($this->config['module'])) {
  208. $this->writeln("Recorder is disabled, no available modules");
  209. return;
  210. }
  211. $this->seed = uniqid();
  212. $this->webDriverModule = $this->getModule($this->config['module']);
  213. if (!$this->webDriverModule instanceof ScreenshotSaver) {
  214. throw new ExtensionException(
  215. $this,
  216. 'You should pass module which implements Codeception\Lib\Interfaces\ScreenshotSaver interface'
  217. );
  218. }
  219. $this->writeln(sprintf(
  220. "⏺ <bold>Recording</bold> ⏺ step-by-step screenshots will be saved to <info>%s</info>",
  221. codecept_output_dir()
  222. ));
  223. $this->writeln("Directory Format: <debug>record_{$this->seed}_{testname}</debug> ----");
  224. }
  225. public function afterSuite()
  226. {
  227. if (!$this->webDriverModule or !$this->dir) {
  228. return;
  229. }
  230. $links = '';
  231. foreach ($this->recordedTests as $link => $url) {
  232. $links .= "<li><a href='$url'>$link</a></li>\n";
  233. }
  234. $indexHTML = (new Template($this->indexTemplate))
  235. ->place('seed', $this->seed)
  236. ->place('records', $links)
  237. ->produce();
  238. file_put_contents(codecept_output_dir().'records.html', $indexHTML);
  239. $this->writeln("⏺ Records saved into: <info>file://" . codecept_output_dir().'records.html</info>');
  240. }
  241. public function before(TestEvent $e)
  242. {
  243. if (!$this->webDriverModule) {
  244. return;
  245. }
  246. $this->dir = null;
  247. $this->stepNum = 0;
  248. $this->slides = [];
  249. $testName = preg_replace('~\W~', '_', Descriptor::getTestAsString($e->getTest()));
  250. $this->dir = codecept_output_dir() . "record_{$this->seed}_$testName";
  251. @mkdir($this->dir);
  252. }
  253. public function cleanup(TestEvent $e)
  254. {
  255. if (!$this->webDriverModule or !$this->dir) {
  256. return;
  257. }
  258. if (!$this->config['delete_successful']) {
  259. $this->persist($e);
  260. return;
  261. }
  262. // deleting successfully executed tests
  263. FileSystem::deleteDir($this->dir);
  264. }
  265. public function persist(TestEvent $e)
  266. {
  267. if (!$this->webDriverModule or !$this->dir) {
  268. return;
  269. }
  270. $indicatorHtml = '';
  271. $slideHtml = '';
  272. foreach ($this->slides as $i => $step) {
  273. $indicatorHtml .= (new Template($this->indicatorTemplate))
  274. ->place('step', (int)$i)
  275. ->place('isActive', (int)$i ? '' : 'class="active"')
  276. ->produce();
  277. $slideHtml .= (new Template($this->slidesTemplate))
  278. ->place('image', $i)
  279. ->place('caption', $step->getHtml('#3498db'))
  280. ->place('isActive', (int)$i ? '' : 'active')
  281. ->place('isError', $step->hasFailed() ? 'error' : '')
  282. ->produce();
  283. }
  284. $html = (new Template($this->template))
  285. ->place('indicators', $indicatorHtml)
  286. ->place('slides', $slideHtml)
  287. ->place('feature', ucfirst($e->getTest()->getFeature()))
  288. ->place('test', Descriptor::getTestSignature($e->getTest()))
  289. ->place('carousel_class', $this->config['animate_slides'] ? ' slide' : '')
  290. ->produce();
  291. $indexFile = $this->dir . DIRECTORY_SEPARATOR . 'index.html';
  292. file_put_contents($indexFile, $html);
  293. $testName = Descriptor::getTestSignature($e->getTest()). ' - '.ucfirst($e->getTest()->getFeature());
  294. $this->recordedTests[$testName] = substr($indexFile, strlen(codecept_output_dir()));
  295. }
  296. public function afterStep(StepEvent $e)
  297. {
  298. if (!$this->webDriverModule or !$this->dir) {
  299. return;
  300. }
  301. if ($e->getStep() instanceof CommentStep) {
  302. return;
  303. }
  304. $filename = str_pad($this->stepNum, 3, "0", STR_PAD_LEFT) . '.png';
  305. $this->webDriverModule->_saveScreenshot($this->dir . DIRECTORY_SEPARATOR . $filename);
  306. $this->stepNum++;
  307. $this->slides[$filename] = $e->getStep();
  308. }
  309. }