PageRenderTime 65ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/Group-I/jobeet/lib/vendor/symfony/lib/vendor/lime/lime.php

https://bitbucket.org/hosseinzolfi/db-lab-spring-2011/
PHP | 1500 lines | 1174 code | 177 blank | 149 comment | 130 complexity | ad4a26e895787211084ffdd29271757c MD5 | raw file
Possible License(s): ISC, AGPL-3.0, LGPL-2.1, BSD-3-Clause, LGPL-3.0
  1. <?php
  2. /**
  3. * This file is part of the symfony package.
  4. * (c) 2004-2006 Fabien Potencier <fabien.potencier@gmail.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * Unit test library.
  11. *
  12. * @package lime
  13. * @author Fabien Potencier <fabien.potencier@gmail.com>
  14. * @version SVN: $Id: lime.php 29529 2010-05-19 13:41:48Z fabien $
  15. */
  16. class lime_test
  17. {
  18. const EPSILON = 0.0000000001;
  19. protected $test_nb = 0;
  20. protected $output = null;
  21. protected $results = array();
  22. protected $options = array();
  23. static protected $all_results = array();
  24. public function __construct($plan = null, $options = array())
  25. {
  26. // for BC
  27. if (!is_array($options))
  28. {
  29. $options = array('output' => $options);
  30. }
  31. $this->options = array_merge(array(
  32. 'force_colors' => false,
  33. 'output' => null,
  34. 'verbose' => false,
  35. 'error_reporting' => false,
  36. ), $options);
  37. $this->output = $this->options['output'] ? $this->options['output'] : new lime_output($this->options['force_colors']);
  38. $caller = $this->find_caller(debug_backtrace());
  39. self::$all_results[] = array(
  40. 'file' => $caller[0],
  41. 'tests' => array(),
  42. 'stats' => array('plan' => $plan, 'total' => 0, 'failed' => array(), 'passed' => array(), 'skipped' => array(), 'errors' => array()),
  43. );
  44. $this->results = &self::$all_results[count(self::$all_results) - 1];
  45. null !== $plan and $this->output->echoln(sprintf("1..%d", $plan));
  46. set_error_handler(array($this, 'handle_error'));
  47. set_exception_handler(array($this, 'handle_exception'));
  48. }
  49. static public function reset()
  50. {
  51. self::$all_results = array();
  52. }
  53. static public function to_array()
  54. {
  55. return self::$all_results;
  56. }
  57. static public function to_xml($results = null)
  58. {
  59. if (is_null($results))
  60. {
  61. $results = self::$all_results;
  62. }
  63. $dom = new DOMDocument('1.0', 'UTF-8');
  64. $dom->formatOutput = true;
  65. $dom->appendChild($testsuites = $dom->createElement('testsuites'));
  66. $errors = 0;
  67. $failures = 0;
  68. $errors = 0;
  69. $skipped = 0;
  70. $assertions = 0;
  71. foreach ($results as $result)
  72. {
  73. $testsuites->appendChild($testsuite = $dom->createElement('testsuite'));
  74. $testsuite->setAttribute('name', basename($result['file'], '.php'));
  75. $testsuite->setAttribute('file', $result['file']);
  76. $testsuite->setAttribute('failures', count($result['stats']['failed']));
  77. $testsuite->setAttribute('errors', count($result['stats']['errors']));
  78. $testsuite->setAttribute('skipped', count($result['stats']['skipped']));
  79. $testsuite->setAttribute('tests', $result['stats']['plan']);
  80. $testsuite->setAttribute('assertions', $result['stats']['plan']);
  81. $failures += count($result['stats']['failed']);
  82. $errors += count($result['stats']['errors']);
  83. $skipped += count($result['stats']['skipped']);
  84. $assertions += $result['stats']['plan'];
  85. foreach ($result['tests'] as $test)
  86. {
  87. $testsuite->appendChild($testcase = $dom->createElement('testcase'));
  88. $testcase->setAttribute('name', $test['message']);
  89. $testcase->setAttribute('file', $test['file']);
  90. $testcase->setAttribute('line', $test['line']);
  91. $testcase->setAttribute('assertions', 1);
  92. if (!$test['status'])
  93. {
  94. $testcase->appendChild($failure = $dom->createElement('failure'));
  95. $failure->setAttribute('type', 'lime');
  96. if (isset($test['error']))
  97. {
  98. $failure->appendChild($dom->createTextNode($test['error']));
  99. }
  100. }
  101. }
  102. }
  103. $testsuites->setAttribute('failures', $failures);
  104. $testsuites->setAttribute('errors', $errors);
  105. $testsuites->setAttribute('tests', $assertions);
  106. $testsuites->setAttribute('assertions', $assertions);
  107. $testsuites->setAttribute('skipped', $skipped);
  108. return $dom->saveXml();
  109. }
  110. public function __destruct()
  111. {
  112. $plan = $this->results['stats']['plan'];
  113. $passed = count($this->results['stats']['passed']);
  114. $failed = count($this->results['stats']['failed']);
  115. $total = $this->results['stats']['total'];
  116. is_null($plan) and $plan = $total and $this->output->echoln(sprintf("1..%d", $plan));
  117. if ($total > $plan)
  118. {
  119. $this->output->red_bar(sprintf("# Looks like you planned %d tests but ran %d extra.", $plan, $total - $plan));
  120. }
  121. elseif ($total < $plan)
  122. {
  123. $this->output->red_bar(sprintf("# Looks like you planned %d tests but only ran %d.", $plan, $total));
  124. }
  125. if ($failed)
  126. {
  127. $this->output->red_bar(sprintf("# Looks like you failed %d tests of %d.", $failed, $passed + $failed));
  128. }
  129. else if ($total == $plan)
  130. {
  131. $this->output->green_bar("# Looks like everything went fine.");
  132. }
  133. flush();
  134. }
  135. /**
  136. * Tests a condition and passes if it is true
  137. *
  138. * @param mixed $exp condition to test
  139. * @param string $message display output message when the test passes
  140. *
  141. * @return boolean
  142. */
  143. public function ok($exp, $message = '')
  144. {
  145. $this->update_stats();
  146. if ($result = (boolean) $exp)
  147. {
  148. $this->results['stats']['passed'][] = $this->test_nb;
  149. }
  150. else
  151. {
  152. $this->results['stats']['failed'][] = $this->test_nb;
  153. }
  154. $this->results['tests'][$this->test_nb]['message'] = $message;
  155. $this->results['tests'][$this->test_nb]['status'] = $result;
  156. $this->output->echoln(sprintf("%s %d%s", $result ? 'ok' : 'not ok', $this->test_nb, $message = $message ? sprintf('%s %s', 0 === strpos($message, '#') ? '' : ' -', $message) : ''));
  157. if (!$result)
  158. {
  159. $this->output->diag(sprintf(' Failed test (%s at line %d)', str_replace(getcwd(), '.', $this->results['tests'][$this->test_nb]['file']), $this->results['tests'][$this->test_nb]['line']));
  160. }
  161. return $result;
  162. }
  163. /**
  164. * Compares two values and passes if they are equal (==)
  165. *
  166. * @param mixed $exp1 left value
  167. * @param mixed $exp2 right value
  168. * @param string $message display output message when the test passes
  169. *
  170. * @return boolean
  171. */
  172. public function is($exp1, $exp2, $message = '')
  173. {
  174. if (is_object($exp1) || is_object($exp2))
  175. {
  176. $value = $exp1 === $exp2;
  177. }
  178. else if (is_float($exp1) && is_float($exp2))
  179. {
  180. $value = abs($exp1 - $exp2) < self::EPSILON;
  181. }
  182. else
  183. {
  184. $value = $exp1 == $exp2;
  185. }
  186. if (!$result = $this->ok($value, $message))
  187. {
  188. $this->set_last_test_errors(array(sprintf(" got: %s", var_export($exp1, true)), sprintf(" expected: %s", var_export($exp2, true))));
  189. }
  190. return $result;
  191. }
  192. /**
  193. * Compares two values and passes if they are not equal
  194. *
  195. * @param mixed $exp1 left value
  196. * @param mixed $exp2 right value
  197. * @param string $message display output message when the test passes
  198. *
  199. * @return boolean
  200. */
  201. public function isnt($exp1, $exp2, $message = '')
  202. {
  203. if (!$result = $this->ok($exp1 != $exp2, $message))
  204. {
  205. $this->set_last_test_errors(array(sprintf(" %s", var_export($exp2, true)), ' ne', sprintf(" %s", var_export($exp2, true))));
  206. }
  207. return $result;
  208. }
  209. /**
  210. * Tests a string against a regular expression
  211. *
  212. * @param string $exp value to test
  213. * @param string $regex the pattern to search for, as a string
  214. * @param string $message display output message when the test passes
  215. *
  216. * @return boolean
  217. */
  218. public function like($exp, $regex, $message = '')
  219. {
  220. if (!$result = $this->ok(preg_match($regex, $exp), $message))
  221. {
  222. $this->set_last_test_errors(array(sprintf(" '%s'", $exp), sprintf(" doesn't match '%s'", $regex)));
  223. }
  224. return $result;
  225. }
  226. /**
  227. * Checks that a string doesn't match a regular expression
  228. *
  229. * @param string $exp value to test
  230. * @param string $regex the pattern to search for, as a string
  231. * @param string $message display output message when the test passes
  232. *
  233. * @return boolean
  234. */
  235. public function unlike($exp, $regex, $message = '')
  236. {
  237. if (!$result = $this->ok(!preg_match($regex, $exp), $message))
  238. {
  239. $this->set_last_test_errors(array(sprintf(" '%s'", $exp), sprintf(" matches '%s'", $regex)));
  240. }
  241. return $result;
  242. }
  243. /**
  244. * Compares two arguments with an operator
  245. *
  246. * @param mixed $exp1 left value
  247. * @param string $op operator
  248. * @param mixed $exp2 right value
  249. * @param string $message display output message when the test passes
  250. *
  251. * @return boolean
  252. */
  253. public function cmp_ok($exp1, $op, $exp2, $message = '')
  254. {
  255. $php = sprintf("\$result = \$exp1 $op \$exp2;");
  256. // under some unknown conditions the sprintf() call causes a segmentation fault
  257. // when placed directly in the eval() call
  258. eval($php);
  259. if (!$this->ok($result, $message))
  260. {
  261. $this->set_last_test_errors(array(sprintf(" %s", str_replace("\n", '', var_export($exp1, true))), sprintf(" %s", $op), sprintf(" %s", str_replace("\n", '', var_export($exp2, true)))));
  262. }
  263. return $result;
  264. }
  265. /**
  266. * Checks the availability of a method for an object or a class
  267. *
  268. * @param mixed $object an object instance or a class name
  269. * @param string|array $methods one or more method names
  270. * @param string $message display output message when the test passes
  271. *
  272. * @return boolean
  273. */
  274. public function can_ok($object, $methods, $message = '')
  275. {
  276. $result = true;
  277. $failed_messages = array();
  278. foreach ((array) $methods as $method)
  279. {
  280. if (!method_exists($object, $method))
  281. {
  282. $failed_messages[] = sprintf(" method '%s' does not exist", $method);
  283. $result = false;
  284. }
  285. }
  286. !$this->ok($result, $message);
  287. !$result and $this->set_last_test_errors($failed_messages);
  288. return $result;
  289. }
  290. /**
  291. * Checks the type of an argument
  292. *
  293. * @param mixed $var variable instance
  294. * @param string $class class or type name
  295. * @param string $message display output message when the test passes
  296. *
  297. * @return boolean
  298. */
  299. public function isa_ok($var, $class, $message = '')
  300. {
  301. $type = is_object($var) ? get_class($var) : gettype($var);
  302. if (!$result = $this->ok($type == $class, $message))
  303. {
  304. $this->set_last_test_errors(array(sprintf(" variable isn't a '%s' it's a '%s'", $class, $type)));
  305. }
  306. return $result;
  307. }
  308. /**
  309. * Checks that two arrays have the same values
  310. *
  311. * @param mixed $exp1 first variable
  312. * @param mixed $exp2 second variable
  313. * @param string $message display output message when the test passes
  314. *
  315. * @return boolean
  316. */
  317. public function is_deeply($exp1, $exp2, $message = '')
  318. {
  319. if (!$result = $this->ok($this->test_is_deeply($exp1, $exp2), $message))
  320. {
  321. $this->set_last_test_errors(array(sprintf(" got: %s", str_replace("\n", '', var_export($exp1, true))), sprintf(" expected: %s", str_replace("\n", '', var_export($exp2, true)))));
  322. }
  323. return $result;
  324. }
  325. /**
  326. * Always passes--useful for testing exceptions
  327. *
  328. * @param string $message display output message
  329. *
  330. * @return true
  331. */
  332. public function pass($message = '')
  333. {
  334. return $this->ok(true, $message);
  335. }
  336. /**
  337. * Always fails--useful for testing exceptions
  338. *
  339. * @param string $message display output message
  340. *
  341. * @return false
  342. */
  343. public function fail($message = '')
  344. {
  345. return $this->ok(false, $message);
  346. }
  347. /**
  348. * Outputs a diag message but runs no test
  349. *
  350. * @param string $message display output message
  351. *
  352. * @return void
  353. */
  354. public function diag($message)
  355. {
  356. $this->output->diag($message);
  357. }
  358. /**
  359. * Counts as $nb_tests tests--useful for conditional tests
  360. *
  361. * @param string $message display output message
  362. * @param integer $nb_tests number of tests to skip
  363. *
  364. * @return void
  365. */
  366. public function skip($message = '', $nb_tests = 1)
  367. {
  368. for ($i = 0; $i < $nb_tests; $i++)
  369. {
  370. $this->pass(sprintf("# SKIP%s", $message ? ' '.$message : ''));
  371. $this->results['stats']['skipped'][] = $this->test_nb;
  372. array_pop($this->results['stats']['passed']);
  373. }
  374. }
  375. /**
  376. * Counts as a test--useful for tests yet to be written
  377. *
  378. * @param string $message display output message
  379. *
  380. * @return void
  381. */
  382. public function todo($message = '')
  383. {
  384. $this->pass(sprintf("# TODO%s", $message ? ' '.$message : ''));
  385. $this->results['stats']['skipped'][] = $this->test_nb;
  386. array_pop($this->results['stats']['passed']);
  387. }
  388. /**
  389. * Validates that a file exists and that it is properly included
  390. *
  391. * @param string $file file path
  392. * @param string $message display output message when the test passes
  393. *
  394. * @return boolean
  395. */
  396. public function include_ok($file, $message = '')
  397. {
  398. if (!$result = $this->ok((@include($file)) == 1, $message))
  399. {
  400. $this->set_last_test_errors(array(sprintf(" Tried to include '%s'", $file)));
  401. }
  402. return $result;
  403. }
  404. private function test_is_deeply($var1, $var2)
  405. {
  406. if (gettype($var1) != gettype($var2))
  407. {
  408. return false;
  409. }
  410. if (is_array($var1))
  411. {
  412. ksort($var1);
  413. ksort($var2);
  414. $keys1 = array_keys($var1);
  415. $keys2 = array_keys($var2);
  416. if (array_diff($keys1, $keys2) || array_diff($keys2, $keys1))
  417. {
  418. return false;
  419. }
  420. $is_equal = true;
  421. foreach ($var1 as $key => $value)
  422. {
  423. $is_equal = $this->test_is_deeply($var1[$key], $var2[$key]);
  424. if ($is_equal === false)
  425. {
  426. break;
  427. }
  428. }
  429. return $is_equal;
  430. }
  431. else
  432. {
  433. return $var1 === $var2;
  434. }
  435. }
  436. public function comment($message)
  437. {
  438. $this->output->comment($message);
  439. }
  440. public function info($message)
  441. {
  442. $this->output->info($message);
  443. }
  444. public function error($message, $file = null, $line = null, array $traces = array())
  445. {
  446. $this->output->error($message, $file, $line, $traces);
  447. $this->results['stats']['errors'][] = array(
  448. 'message' => $message,
  449. 'file' => $file,
  450. 'line' => $line,
  451. );
  452. }
  453. protected function update_stats()
  454. {
  455. ++$this->test_nb;
  456. ++$this->results['stats']['total'];
  457. list($this->results['tests'][$this->test_nb]['file'], $this->results['tests'][$this->test_nb]['line']) = $this->find_caller(debug_backtrace());
  458. }
  459. protected function set_last_test_errors(array $errors)
  460. {
  461. $this->output->diag($errors);
  462. $this->results['tests'][$this->test_nb]['error'] = implode("\n", $errors);
  463. }
  464. protected function find_caller($traces)
  465. {
  466. // find the first call to a method of an object that is an instance of lime_test
  467. $t = array_reverse($traces);
  468. foreach ($t as $trace)
  469. {
  470. if (isset($trace['object']) && $trace['object'] instanceof lime_test)
  471. {
  472. return array($trace['file'], $trace['line']);
  473. }
  474. }
  475. // return the first call
  476. $last = count($traces) - 1;
  477. return array($traces[$last]['file'], $traces[$last]['line']);
  478. }
  479. public function handle_error($code, $message, $file, $line, $context)
  480. {
  481. if (!$this->options['error_reporting'] || ($code & error_reporting()) == 0)
  482. {
  483. return false;
  484. }
  485. switch ($code)
  486. {
  487. case E_WARNING:
  488. $type = 'Warning';
  489. break;
  490. default:
  491. $type = 'Notice';
  492. break;
  493. }
  494. $trace = debug_backtrace();
  495. array_shift($trace); // remove the handle_error() call from the trace
  496. $this->error($type.': '.$message, $file, $line, $trace);
  497. }
  498. public function handle_exception(Exception $exception)
  499. {
  500. $this->error(get_class($exception).': '.$exception->getMessage(), $exception->getFile(), $exception->getLine(), $exception->getTrace());
  501. // exception was handled
  502. return true;
  503. }
  504. }
  505. class lime_output
  506. {
  507. public $colorizer = null;
  508. public $base_dir = null;
  509. public function __construct($force_colors = false, $base_dir = null)
  510. {
  511. $this->colorizer = new lime_colorizer($force_colors);
  512. $this->base_dir = $base_dir === null ? getcwd() : $base_dir;
  513. }
  514. public function diag()
  515. {
  516. $messages = func_get_args();
  517. foreach ($messages as $message)
  518. {
  519. echo $this->colorizer->colorize('# '.join("\n# ", (array) $message), 'COMMENT')."\n";
  520. }
  521. }
  522. public function comment($message)
  523. {
  524. echo $this->colorizer->colorize(sprintf('# %s', $message), 'COMMENT')."\n";
  525. }
  526. public function info($message)
  527. {
  528. echo $this->colorizer->colorize(sprintf('> %s', $message), 'INFO_BAR')."\n";
  529. }
  530. public function error($message, $file = null, $line = null, $traces = array())
  531. {
  532. if ($file !== null)
  533. {
  534. $message .= sprintf("\n(in %s on line %s)", $file, $line);
  535. }
  536. // some error messages contain absolute file paths
  537. $message = $this->strip_base_dir($message);
  538. $space = $this->colorizer->colorize(str_repeat(' ', 71), 'RED_BAR')."\n";
  539. $message = trim($message);
  540. $message = wordwrap($message, 66, "\n");
  541. echo "\n".$space;
  542. foreach (explode("\n", $message) as $message_line)
  543. {
  544. echo $this->colorizer->colorize(str_pad(' '.$message_line, 71, ' '), 'RED_BAR')."\n";
  545. }
  546. echo $space."\n";
  547. if (count($traces) > 0)
  548. {
  549. echo $this->colorizer->colorize('Exception trace:', 'COMMENT')."\n";
  550. $this->print_trace(null, $file, $line);
  551. foreach ($traces as $trace)
  552. {
  553. if (array_key_exists('class', $trace))
  554. {
  555. $method = sprintf('%s%s%s()', $trace['class'], $trace['type'], $trace['function']);
  556. }
  557. else
  558. {
  559. $method = sprintf('%s()', $trace['function']);
  560. }
  561. if (array_key_exists('file', $trace))
  562. {
  563. $this->print_trace($method, $trace['file'], $trace['line']);
  564. }
  565. else
  566. {
  567. $this->print_trace($method);
  568. }
  569. }
  570. echo "\n";
  571. }
  572. }
  573. protected function print_trace($method = null, $file = null, $line = null)
  574. {
  575. if (!is_null($method))
  576. {
  577. $method .= ' ';
  578. }
  579. echo ' '.$method.'at ';
  580. if (!is_null($file) && !is_null($line))
  581. {
  582. printf("%s:%s\n", $this->colorizer->colorize($this->strip_base_dir($file), 'TRACE'), $this->colorizer->colorize($line, 'TRACE'));
  583. }
  584. else
  585. {
  586. echo "[internal function]\n";
  587. }
  588. }
  589. public function echoln($message, $colorizer_parameter = null, $colorize = true)
  590. {
  591. if ($colorize)
  592. {
  593. $message = preg_replace('/(?:^|\.)((?:not ok|dubious|errors) *\d*)\b/e', '$this->colorizer->colorize(\'$1\', \'ERROR\')', $message);
  594. $message = preg_replace('/(?:^|\.)(ok *\d*)\b/e', '$this->colorizer->colorize(\'$1\', \'INFO\')', $message);
  595. $message = preg_replace('/"(.+?)"/e', '$this->colorizer->colorize(\'$1\', \'PARAMETER\')', $message);
  596. $message = preg_replace('/(\->|\:\:)?([a-zA-Z0-9_]+?)\(\)/e', '$this->colorizer->colorize(\'$1$2()\', \'PARAMETER\')', $message);
  597. }
  598. echo ($colorizer_parameter ? $this->colorizer->colorize($message, $colorizer_parameter) : $message)."\n";
  599. }
  600. public function green_bar($message)
  601. {
  602. echo $this->colorizer->colorize($message.str_repeat(' ', 71 - min(71, strlen($message))), 'GREEN_BAR')."\n";
  603. }
  604. public function red_bar($message)
  605. {
  606. echo $this->colorizer->colorize($message.str_repeat(' ', 71 - min(71, strlen($message))), 'RED_BAR')."\n";
  607. }
  608. protected function strip_base_dir($text)
  609. {
  610. return str_replace(DIRECTORY_SEPARATOR, '/', str_replace(realpath($this->base_dir).DIRECTORY_SEPARATOR, '', $text));
  611. }
  612. }
  613. class lime_output_color extends lime_output
  614. {
  615. }
  616. class lime_colorizer
  617. {
  618. static public $styles = array();
  619. protected $colors_supported = false;
  620. public function __construct($force_colors = false)
  621. {
  622. if ($force_colors)
  623. {
  624. $this->colors_supported = true;
  625. }
  626. else
  627. {
  628. // colors are supported on windows with ansicon or on tty consoles
  629. if (DIRECTORY_SEPARATOR == '\\')
  630. {
  631. $this->colors_supported = false !== getenv('ANSICON');
  632. }
  633. else
  634. {
  635. $this->colors_supported = function_exists('posix_isatty') && @posix_isatty(STDOUT);
  636. }
  637. }
  638. }
  639. public static function style($name, $options = array())
  640. {
  641. self::$styles[$name] = $options;
  642. }
  643. public function colorize($text = '', $parameters = array())
  644. {
  645. if (!$this->colors_supported)
  646. {
  647. return $text;
  648. }
  649. static $options = array('bold' => 1, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, 'conceal' => 8);
  650. static $foreground = array('black' => 30, 'red' => 31, 'green' => 32, 'yellow' => 33, 'blue' => 34, 'magenta' => 35, 'cyan' => 36, 'white' => 37);
  651. static $background = array('black' => 40, 'red' => 41, 'green' => 42, 'yellow' => 43, 'blue' => 44, 'magenta' => 45, 'cyan' => 46, 'white' => 47);
  652. !is_array($parameters) && isset(self::$styles[$parameters]) and $parameters = self::$styles[$parameters];
  653. $codes = array();
  654. isset($parameters['fg']) and $codes[] = $foreground[$parameters['fg']];
  655. isset($parameters['bg']) and $codes[] = $background[$parameters['bg']];
  656. foreach ($options as $option => $value)
  657. {
  658. isset($parameters[$option]) && $parameters[$option] and $codes[] = $value;
  659. }
  660. return "\033[".implode(';', $codes).'m'.$text."\033[0m";
  661. }
  662. }
  663. lime_colorizer::style('ERROR', array('bg' => 'red', 'fg' => 'white', 'bold' => true));
  664. lime_colorizer::style('INFO', array('fg' => 'green', 'bold' => true));
  665. lime_colorizer::style('TRACE', array('fg' => 'green', 'bold' => true));
  666. lime_colorizer::style('PARAMETER', array('fg' => 'cyan'));
  667. lime_colorizer::style('COMMENT', array('fg' => 'yellow'));
  668. lime_colorizer::style('GREEN_BAR', array('fg' => 'white', 'bg' => 'green', 'bold' => true));
  669. lime_colorizer::style('RED_BAR', array('fg' => 'white', 'bg' => 'red', 'bold' => true));
  670. lime_colorizer::style('INFO_BAR', array('fg' => 'cyan', 'bold' => true));
  671. class lime_harness extends lime_registration
  672. {
  673. public $options = array();
  674. public $php_cli = null;
  675. public $stats = array();
  676. public $output = null;
  677. public function __construct($options = array())
  678. {
  679. // for BC
  680. if (!is_array($options))
  681. {
  682. $options = array('output' => $options);
  683. }
  684. $this->options = array_merge(array(
  685. 'php_cli' => null,
  686. 'force_colors' => false,
  687. 'output' => null,
  688. 'verbose' => false,
  689. ), $options);
  690. $this->php_cli = $this->find_php_cli($this->options['php_cli']);
  691. $this->output = $this->options['output'] ? $this->options['output'] : new lime_output($this->options['force_colors']);
  692. }
  693. protected function find_php_cli($php_cli = null)
  694. {
  695. if (is_null($php_cli))
  696. {
  697. if (getenv('PHP_PATH'))
  698. {
  699. $php_cli = getenv('PHP_PATH');
  700. if (!is_executable($php_cli))
  701. {
  702. throw new Exception('The defined PHP_PATH environment variable is not a valid PHP executable.');
  703. }
  704. }
  705. else
  706. {
  707. $php_cli = PHP_BINDIR.DIRECTORY_SEPARATOR.'php';
  708. }
  709. }
  710. if (is_executable($php_cli))
  711. {
  712. return $php_cli;
  713. }
  714. $path = getenv('PATH') ? getenv('PATH') : getenv('Path');
  715. $exe_suffixes = DIRECTORY_SEPARATOR == '\\' ? (getenv('PATHEXT') ? explode(PATH_SEPARATOR, getenv('PATHEXT')) : array('.exe', '.bat', '.cmd', '.com')) : array('');
  716. foreach (array('php5', 'php') as $php_cli)
  717. {
  718. foreach ($exe_suffixes as $suffix)
  719. {
  720. foreach (explode(PATH_SEPARATOR, $path) as $dir)
  721. {
  722. $file = $dir.DIRECTORY_SEPARATOR.$php_cli.$suffix;
  723. if (is_executable($file))
  724. {
  725. return $file;
  726. }
  727. }
  728. }
  729. }
  730. throw new Exception("Unable to find PHP executable.");
  731. }
  732. public function to_array()
  733. {
  734. $results = array();
  735. foreach ($this->stats['files'] as $file => $stat)
  736. {
  737. $results = array_merge($results, $stat['output']);
  738. }
  739. return $results;
  740. }
  741. public function to_xml()
  742. {
  743. return lime_test::to_xml($this->to_array());
  744. }
  745. public function run()
  746. {
  747. if (!count($this->files))
  748. {
  749. throw new Exception('You must register some test files before running them!');
  750. }
  751. // sort the files to be able to predict the order
  752. sort($this->files);
  753. $this->stats = array(
  754. 'files' => array(),
  755. 'failed_files' => array(),
  756. 'failed_tests' => 0,
  757. 'total' => 0,
  758. );
  759. foreach ($this->files as $file)
  760. {
  761. $this->stats['files'][$file] = array();
  762. $stats = &$this->stats['files'][$file];
  763. $relative_file = $this->get_relative_file($file);
  764. $test_file = tempnam(sys_get_temp_dir(), 'lime');
  765. $result_file = tempnam(sys_get_temp_dir(), 'lime');
  766. file_put_contents($test_file, <<<EOF
  767. <?php
  768. function lime_shutdown()
  769. {
  770. file_put_contents('$result_file', serialize(lime_test::to_array()));
  771. }
  772. register_shutdown_function('lime_shutdown');
  773. include('$file');
  774. EOF
  775. );
  776. ob_start();
  777. // see http://trac.symfony-project.org/ticket/5437 for the explanation on the weird "cd" thing
  778. passthru(sprintf('cd & %s %s 2>&1', escapeshellarg($this->php_cli), escapeshellarg($test_file)), $return);
  779. ob_end_clean();
  780. unlink($test_file);
  781. $output = file_get_contents($result_file);
  782. $stats['output'] = $output ? unserialize($output) : '';
  783. if (!$stats['output'])
  784. {
  785. $stats['output'] = array(array('file' => $file, 'tests' => array(), 'stats' => array('plan' => 1, 'total' => 1, 'failed' => array(0), 'passed' => array(), 'skipped' => array(), 'errors' => array())));
  786. }
  787. unlink($result_file);
  788. $file_stats = &$stats['output'][0]['stats'];
  789. $delta = 0;
  790. if ($return > 0)
  791. {
  792. $stats['status'] = $file_stats['errors'] ? 'errors' : 'dubious';
  793. $stats['status_code'] = $return;
  794. }
  795. else
  796. {
  797. $this->stats['total'] += $file_stats['total'];
  798. if (!$file_stats['plan'])
  799. {
  800. $file_stats['plan'] = $file_stats['total'];
  801. }
  802. $delta = $file_stats['plan'] - $file_stats['total'];
  803. if (0 != $delta)
  804. {
  805. $stats['status'] = $file_stats['errors'] ? 'errors' : 'dubious';
  806. $stats['status_code'] = 255;
  807. }
  808. else
  809. {
  810. $stats['status'] = $file_stats['failed'] ? 'not ok' : ($file_stats['errors'] ? 'errors' : 'ok');
  811. $stats['status_code'] = 0;
  812. }
  813. }
  814. $this->output->echoln(sprintf('%s%s%s', substr($relative_file, -min(67, strlen($relative_file))), str_repeat('.', 70 - min(67, strlen($relative_file))), $stats['status']));
  815. if ('dubious' == $stats['status'])
  816. {
  817. $this->output->echoln(sprintf(' Test returned status %s', $stats['status_code']));
  818. }
  819. if ('ok' != $stats['status'])
  820. {
  821. $this->stats['failed_files'][] = $file;
  822. }
  823. if ($delta > 0)
  824. {
  825. $this->output->echoln(sprintf(' Looks like you planned %d tests but only ran %d.', $file_stats['plan'], $file_stats['total']));
  826. $this->stats['failed_tests'] += $delta;
  827. $this->stats['total'] += $delta;
  828. }
  829. else if ($delta < 0)
  830. {
  831. $this->output->echoln(sprintf(' Looks like you planned %s test but ran %s extra.', $file_stats['plan'], $file_stats['total'] - $file_stats['plan']));
  832. }
  833. if (false !== $file_stats && $file_stats['failed'])
  834. {
  835. $this->stats['failed_tests'] += count($file_stats['failed']);
  836. $this->output->echoln(sprintf(" Failed tests: %s", implode(', ', $file_stats['failed'])));
  837. }
  838. if (false !== $file_stats && $file_stats['errors'])
  839. {
  840. $this->output->echoln(' Errors:');
  841. $error_count = count($file_stats['errors']);
  842. for ($i = 0; $i < 3 && $i < $error_count; ++$i)
  843. {
  844. $this->output->echoln(' - ' . $file_stats['errors'][$i]['message'], null, false);
  845. }
  846. if ($error_count > 3)
  847. {
  848. $this->output->echoln(sprintf(' ... and %s more', $error_count-3));
  849. }
  850. }
  851. }
  852. if (count($this->stats['failed_files']))
  853. {
  854. $format = "%-30s %4s %5s %5s %5s %s";
  855. $this->output->echoln(sprintf($format, 'Failed Test', 'Stat', 'Total', 'Fail', 'Errors', 'List of Failed'));
  856. $this->output->echoln("--------------------------------------------------------------------------");
  857. foreach ($this->stats['files'] as $file => $stat)
  858. {
  859. if (!in_array($file, $this->stats['failed_files']))
  860. {
  861. continue;
  862. }
  863. $relative_file = $this->get_relative_file($file);
  864. if (isset($stat['output'][0]))
  865. {
  866. $this->output->echoln(sprintf($format, substr($relative_file, -min(30, strlen($relative_file))), $stat['status_code'], count($stat['output'][0]['stats']['failed']) + count($stat['output'][0]['stats']['passed']), count($stat['output'][0]['stats']['failed']), count($stat['output'][0]['stats']['errors']), implode(' ', $stat['output'][0]['stats']['failed'])));
  867. }
  868. else
  869. {
  870. $this->output->echoln(sprintf($format, substr($relative_file, -min(30, strlen($relative_file))), $stat['status_code'], '', '', ''));
  871. }
  872. }
  873. $this->output->red_bar(sprintf('Failed %d/%d test scripts, %.2f%% okay. %d/%d subtests failed, %.2f%% okay.',
  874. $nb_failed_files = count($this->stats['failed_files']),
  875. $nb_files = count($this->files),
  876. ($nb_files - $nb_failed_files) * 100 / $nb_files,
  877. $nb_failed_tests = $this->stats['failed_tests'],
  878. $nb_tests = $this->stats['total'],
  879. $nb_tests > 0 ? ($nb_tests - $nb_failed_tests) * 100 / $nb_tests : 0
  880. ));
  881. if ($this->options['verbose'])
  882. {
  883. foreach ($this->to_array() as $testsuite)
  884. {
  885. $first = true;
  886. foreach ($testsuite['stats']['failed'] as $testcase)
  887. {
  888. if (!isset($testsuite['tests'][$testcase]['file']))
  889. {
  890. continue;
  891. }
  892. if ($first)
  893. {
  894. $this->output->echoln('');
  895. $this->output->error($this->get_relative_file($testsuite['file']).$this->extension);
  896. $first = false;
  897. }
  898. $this->output->comment(sprintf(' at %s line %s', $this->get_relative_file($testsuite['tests'][$testcase]['file']).$this->extension, $testsuite['tests'][$testcase]['line']));
  899. $this->output->info(' '.$testsuite['tests'][$testcase]['message']);
  900. $this->output->echoln($testsuite['tests'][$testcase]['error'], null, false);
  901. }
  902. }
  903. }
  904. }
  905. else
  906. {
  907. $this->output->green_bar(' All tests successful.');
  908. $this->output->green_bar(sprintf(' Files=%d, Tests=%d', count($this->files), $this->stats['total']));
  909. }
  910. return $this->stats['failed_files'] ? false : true;
  911. }
  912. public function get_failed_files()
  913. {
  914. return isset($this->stats['failed_files']) ? $this->stats['failed_files'] : array();
  915. }
  916. }
  917. class lime_coverage extends lime_registration
  918. {
  919. public $files = array();
  920. public $extension = '.php';
  921. public $base_dir = '';
  922. public $harness = null;
  923. public $verbose = false;
  924. protected $coverage = array();
  925. public function __construct($harness)
  926. {
  927. $this->harness = $harness;
  928. if (!function_exists('xdebug_start_code_coverage'))
  929. {
  930. throw new Exception('You must install and enable xdebug before using lime coverage.');
  931. }
  932. if (!ini_get('xdebug.extended_info'))
  933. {
  934. throw new Exception('You must set xdebug.extended_info to 1 in your php.ini to use lime coverage.');
  935. }
  936. }
  937. public function run()
  938. {
  939. if (!count($this->harness->files))
  940. {
  941. throw new Exception('You must register some test files before running coverage!');
  942. }
  943. if (!count($this->files))
  944. {
  945. throw new Exception('You must register some files to cover!');
  946. }
  947. $this->coverage = array();
  948. $this->process($this->harness->files);
  949. $this->output($this->files);
  950. }
  951. public function process($files)
  952. {
  953. if (!is_array($files))
  954. {
  955. $files = array($files);
  956. }
  957. $tmp_file = sys_get_temp_dir().DIRECTORY_SEPARATOR.'test.php';
  958. foreach ($files as $file)
  959. {
  960. $tmp = <<<EOF
  961. <?php
  962. xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
  963. include('$file');
  964. echo '<PHP_SER>'.serialize(xdebug_get_code_coverage()).'</PHP_SER>';
  965. EOF;
  966. file_put_contents($tmp_file, $tmp);
  967. ob_start();
  968. // see http://trac.symfony-project.org/ticket/5437 for the explanation on the weird "cd" thing
  969. passthru(sprintf('cd & %s %s 2>&1', escapeshellarg($this->harness->php_cli), escapeshellarg($tmp_file)), $return);
  970. $retval = ob_get_clean();
  971. if (0 != $return) // test exited without success
  972. {
  973. // something may have gone wrong, we should warn the user so they know
  974. // it's a bug in their code and not symfony's
  975. $this->harness->output->echoln(sprintf('Warning: %s returned status %d, results may be inaccurate', $file, $return), 'ERROR');
  976. }
  977. if (false === $cov = @unserialize(substr($retval, strpos($retval, '<PHP_SER>') + 9, strpos($retval, '</PHP_SER>') - 9)))
  978. {
  979. if (0 == $return)
  980. {
  981. // failed to serialize, but PHP said it should of worked.
  982. // something is seriously wrong, so abort with exception
  983. throw new Exception(sprintf('Unable to unserialize coverage for file "%s"', $file));
  984. }
  985. else
  986. {
  987. // failed to serialize, but PHP warned us that this might have happened.
  988. // so we should ignore and move on
  989. continue; // continue foreach loop through $this->harness->files
  990. }
  991. }
  992. foreach ($cov as $file => $lines)
  993. {
  994. if (!isset($this->coverage[$file]))
  995. {
  996. $this->coverage[$file] = $lines;
  997. continue;
  998. }
  999. foreach ($lines as $line => $flag)
  1000. {
  1001. if ($flag == 1)
  1002. {
  1003. $this->coverage[$file][$line] = 1;
  1004. }
  1005. }
  1006. }
  1007. }
  1008. if (file_exists($tmp_file))
  1009. {
  1010. unlink($tmp_file);
  1011. }
  1012. }
  1013. public function output($files)
  1014. {
  1015. ksort($this->coverage);
  1016. $total_php_lines = 0;
  1017. $total_covered_lines = 0;
  1018. foreach ($files as $file)
  1019. {
  1020. $file = realpath($file);
  1021. $is_covered = isset($this->coverage[$file]);
  1022. $cov = isset($this->coverage[$file]) ? $this->coverage[$file] : array();
  1023. $covered_lines = array();
  1024. $missing_lines = array();
  1025. foreach ($cov as $line => $flag)
  1026. {
  1027. switch ($flag)
  1028. {
  1029. case 1:
  1030. $covered_lines[] = $line;
  1031. break;
  1032. case -1:
  1033. $missing_lines[] = $line;
  1034. break;
  1035. }
  1036. }
  1037. $total_lines = count($covered_lines) + count($missing_lines);
  1038. if (!$total_lines)
  1039. {
  1040. // probably means that the file is not covered at all!
  1041. $total_lines = count($this->get_php_lines(file_get_contents($file)));
  1042. }
  1043. $output = $this->harness->output;
  1044. $percent = $total_lines ? count($covered_lines) * 100 / $total_lines : 0;
  1045. $total_php_lines += $total_lines;
  1046. $total_covered_lines += count($covered_lines);
  1047. $relative_file = $this->get_relative_file($file);
  1048. $output->echoln(sprintf("%-70s %3.0f%%", substr($relative_file, -min(70, strlen($relative_file))), $percent), $percent == 100 ? 'INFO' : ($percent > 90 ? 'PARAMETER' : ($percent < 20 ? 'ERROR' : '')));
  1049. if ($this->verbose && $is_covered && $percent != 100)
  1050. {
  1051. $output->comment(sprintf("missing: %s", $this->format_range($missing_lines)));
  1052. }
  1053. }
  1054. $output->echoln(sprintf("TOTAL COVERAGE: %3.0f%%", $total_php_lines ? $total_covered_lines * 100 / $total_php_lines : 0));
  1055. }
  1056. public static function get_php_lines($content)
  1057. {
  1058. if (is_readable($content))
  1059. {
  1060. $content = file_get_contents($content);
  1061. }
  1062. $tokens = token_get_all($content);
  1063. $php_lines = array();
  1064. $current_line = 1;
  1065. $in_class = false;
  1066. $in_function = false;
  1067. $in_function_declaration = false;
  1068. $end_of_current_expr = true;
  1069. $open_braces = 0;
  1070. foreach ($tokens as $token)
  1071. {
  1072. if (is_string($token))
  1073. {
  1074. switch ($token)
  1075. {
  1076. case '=':
  1077. if (false === $in_class || (false !== $in_function && !$in_function_declaration))
  1078. {
  1079. $php_lines[$current_line] = true;
  1080. }
  1081. break;
  1082. case '{':
  1083. ++$open_braces;
  1084. $in_function_declaration = false;
  1085. break;
  1086. case ';':
  1087. $in_function_declaration = false;
  1088. $end_of_current_expr = true;
  1089. break;
  1090. case '}':
  1091. $end_of_current_expr = true;
  1092. --$open_braces;
  1093. if ($open_braces == $in_class)
  1094. {
  1095. $in_class = false;
  1096. }
  1097. if ($open_braces == $in_function)
  1098. {
  1099. $in_function = false;
  1100. }
  1101. break;
  1102. }
  1103. continue;
  1104. }
  1105. list($id, $text) = $token;
  1106. switch ($id)
  1107. {
  1108. case T_CURLY_OPEN:
  1109. case T_DOLLAR_OPEN_CURLY_BRACES:
  1110. ++$open_braces;
  1111. break;
  1112. case T_WHITESPACE:
  1113. case T_OPEN_TAG:
  1114. case T_CLOSE_TAG:
  1115. $end_of_current_expr = true;
  1116. $current_line += count(explode("\n", $text)) - 1;
  1117. break;
  1118. case T_COMMENT:
  1119. case T_DOC_COMMENT:
  1120. $current_line += count(explode("\n", $text)) - 1;
  1121. break;
  1122. case T_CLASS:
  1123. $in_class = $open_braces;
  1124. break;
  1125. case T_FUNCTION:
  1126. $in_function = $open_braces;
  1127. $in_function_declaration = true;
  1128. break;
  1129. case T_AND_EQUAL:
  1130. case T_BREAK:
  1131. case T_CASE:
  1132. case T_CATCH:
  1133. case T_CLONE:
  1134. case T_CONCAT_EQUAL:
  1135. case T_CONTINUE:
  1136. case T_DEC:
  1137. case T_DECLARE:
  1138. case T_DEFAULT:
  1139. case T_DIV_EQUAL:
  1140. case T_DO:
  1141. case T_ECHO:
  1142. case T_ELSEIF:
  1143. case T_EMPTY:
  1144. case T_ENDDECLARE:
  1145. case T_ENDFOR:
  1146. case T_ENDFOREACH:
  1147. case T_ENDIF:
  1148. case T_ENDSWITCH:
  1149. case T_ENDWHILE:
  1150. case T_EVAL:
  1151. case T_EXIT:
  1152. case T_FOR:
  1153. case T_FOREACH:
  1154. case T_GLOBAL:
  1155. case T_IF:
  1156. case T_INC:
  1157. case T_INCLUDE:
  1158. case T_INCLUDE_ONCE:
  1159. case T_INSTANCEOF:
  1160. case T_ISSET:
  1161. case T_IS_EQUAL:
  1162. case T_IS_GREATER_OR_EQUAL:
  1163. case T_IS_IDENTICAL:
  1164. case T_IS_NOT_EQUAL:
  1165. case T_IS_NOT_IDENTICAL:
  1166. case T_IS_SMALLER_OR_EQUAL:
  1167. case T_LIST:
  1168. case T_LOGICAL_AND:
  1169. case T_LOGICAL_OR:
  1170. case T_LOGICAL_XOR:
  1171. case T_MINUS_EQUAL:
  1172. case T_MOD_EQUAL:
  1173. case T_MUL_EQUAL:
  1174. case T_NEW:
  1175. case T_OBJECT_OPERATOR:
  1176. case T_OR_EQUAL:
  1177. case T_PLUS_EQUAL:
  1178. case T_PRINT:
  1179. case T_REQUIRE:
  1180. case T_REQUIRE_ONCE:
  1181. case T_RETURN:
  1182. case T_SL:
  1183. case T_SL_EQUAL:
  1184. case T_SR:
  1185. case T_SR_EQUAL:
  1186. case T_SWITCH:
  1187. case T_THROW:
  1188. case T_TRY:
  1189. case T_UNSET:
  1190. case T_UNSET_CAST:
  1191. case T_USE:
  1192. case T_WHILE:
  1193. case T_XOR_EQUAL:
  1194. $php_lines[$current_line] = true;
  1195. $end_of_current_expr = false;
  1196. break;
  1197. default:
  1198. if (false === $end_of_current_expr)
  1199. {
  1200. $php_lines[$current_line] = true;
  1201. }
  1202. }
  1203. }
  1204. return $php_lines;
  1205. }
  1206. public function compute($content, $cov)
  1207. {
  1208. $php_lines = self::get_php_lines($content);
  1209. // we remove from $cov non php lines
  1210. foreach (array_diff_key($cov, $php_lines) as $line => $tmp)
  1211. {
  1212. unset($cov[$line]);
  1213. }
  1214. return array($cov, $php_lines);
  1215. }
  1216. public function format_range($lines)
  1217. {
  1218. sort($lines);
  1219. $formatted = '';
  1220. $first = -1;
  1221. $last = -1;
  1222. foreach ($lines as $line)
  1223. {
  1224. if ($last + 1 != $line)
  1225. {
  1226. if ($first != -1)
  1227. {
  1228. $formatted .= $first == $last ? "$first " : "[$first - $last] ";
  1229. }
  1230. $first = $line;
  1231. $last = $line;
  1232. }
  1233. else
  1234. {
  1235. $last = $line;
  1236. }
  1237. }
  1238. if ($first != -1)
  1239. {
  1240. $formatted .= $first == $last ? "$first " : "[$first - $last] ";
  1241. }
  1242. return $formatted;
  1243. }
  1244. }
  1245. class lime_registration
  1246. {
  1247. public $files = array();
  1248. public $extension = '.php';
  1249. public $base_dir = '';
  1250. public function register($files_or_directories)
  1251. {
  1252. foreach ((array) $files_or_directories as $f_or_d)
  1253. {
  1254. if (is_file($f_or_d))
  1255. {
  1256. $this->files[] = realpath($f_or_d);
  1257. }
  1258. elseif (is_dir($f_or_d))
  1259. {
  1260. $this->register_dir($f_or_d);
  1261. }
  1262. else
  1263. {
  1264. throw new Exception(sprintf('The file or directory "%s" does not exist.', $f_or_d));
  1265. }
  1266. }
  1267. }
  1268. public function register_glob($glob)
  1269. {
  1270. if ($dirs = glob($glob))
  1271. {
  1272. foreach ($dirs as $file)
  1273. {
  1274. $this->files[] = realpath($file);
  1275. }
  1276. }
  1277. }
  1278. public function register_dir($directory)
  1279. {
  1280. if (!is_dir($directory))
  1281. {
  1282. throw new Exception(sprintf('The directory "%s" does not exist.', $directory));
  1283. }
  1284. $files = array();
  1285. $current_dir = opendir($directory);
  1286. while ($entry = readdir($current_dir))
  1287. {
  1288. if ($entry == '.' || $entry == '..') continue;
  1289. if (is_dir($entry))
  1290. {
  1291. $this->register_dir($entry);
  1292. }
  1293. elseif (preg_match('#'.$this->extension.'$#', $entry))
  1294. {
  1295. $files[] = realpath($directory.DIRECTORY_SEPARATOR.$entry);
  1296. }
  1297. }
  1298. $this->files = array_merge($this->files, $files);
  1299. }
  1300. protected function get_relative_file($file)
  1301. {
  1302. return str_replace(DIRECTORY_SEPARATOR, '/', str_replace(array(realpath($this->base_dir).DIRECTORY_SEPARATOR, $this->extension), '', $file));
  1303. }
  1304. }