PageRenderTime 162ms CodeModel.GetById 6ms RepoModel.GetById 1ms app.codeStats 0ms

/penyaskito/php/simpletest/test_case.php

http://github.com/12meses12katas/Enero-String-Calculator
PHP | 657 lines | 311 code | 46 blank | 300 comment | 43 complexity | 35a8370ef56d7eff22bd442b938dc700 MD5 | raw file
Possible License(s): LGPL-2.1
  1. <?php
  2. /**
  3. * Base include file for SimpleTest
  4. * @package SimpleTest
  5. * @subpackage UnitTester
  6. * @version $Id: test_case.php 1968 2009-10-19 18:24:23Z maetl_ $
  7. */
  8. /**#@+
  9. * Includes SimpleTest files and defined the root constant
  10. * for dependent libraries.
  11. */
  12. require_once(dirname(__FILE__) . '/invoker.php');
  13. require_once(dirname(__FILE__) . '/errors.php');
  14. require_once(dirname(__FILE__) . '/compatibility.php');
  15. require_once(dirname(__FILE__) . '/scorer.php');
  16. require_once(dirname(__FILE__) . '/expectation.php');
  17. require_once(dirname(__FILE__) . '/dumper.php');
  18. require_once(dirname(__FILE__) . '/simpletest.php');
  19. require_once(dirname(__FILE__) . '/exceptions.php');
  20. require_once(dirname(__FILE__) . '/reflection_php5.php');
  21. /**#@-*/
  22. if (! defined('SIMPLE_TEST')) {
  23. /**
  24. * @ignore
  25. */
  26. define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR);
  27. }
  28. /**
  29. * Basic test case. This is the smallest unit of a test
  30. * suite. It searches for
  31. * all methods that start with the the string "test" and
  32. * runs them. Working test cases extend this class.
  33. * @package SimpleTest
  34. * @subpackage UnitTester
  35. */
  36. class SimpleTestCase {
  37. private $label = false;
  38. protected $reporter;
  39. private $observers;
  40. private $should_skip = false;
  41. /**
  42. * Sets up the test with no display.
  43. * @param string $label If no test name is given then
  44. * the class name is used.
  45. * @access public
  46. */
  47. function __construct($label = false) {
  48. if ($label) {
  49. $this->label = $label;
  50. }
  51. }
  52. /**
  53. * Accessor for the test name for subclasses.
  54. * @return string Name of the test.
  55. * @access public
  56. */
  57. function getLabel() {
  58. return $this->label ? $this->label : get_class($this);
  59. }
  60. /**
  61. * This is a placeholder for skipping tests. In this
  62. * method you place skipIf() and skipUnless() calls to
  63. * set the skipping state.
  64. * @access public
  65. */
  66. function skip() {
  67. }
  68. /**
  69. * Will issue a message to the reporter and tell the test
  70. * case to skip if the incoming flag is true.
  71. * @param string $should_skip Condition causing the tests to be skipped.
  72. * @param string $message Text of skip condition.
  73. * @access public
  74. */
  75. function skipIf($should_skip, $message = '%s') {
  76. if ($should_skip && ! $this->should_skip) {
  77. $this->should_skip = true;
  78. $message = sprintf($message, 'Skipping [' . get_class($this) . ']');
  79. $this->reporter->paintSkip($message . $this->getAssertionLine());
  80. }
  81. }
  82. /**
  83. * Accessor for the private variable $_shoud_skip
  84. * @access public
  85. */
  86. function shouldSkip() {
  87. return $this->should_skip;
  88. }
  89. /**
  90. * Will issue a message to the reporter and tell the test
  91. * case to skip if the incoming flag is false.
  92. * @param string $shouldnt_skip Condition causing the tests to be run.
  93. * @param string $message Text of skip condition.
  94. * @access public
  95. */
  96. function skipUnless($shouldnt_skip, $message = false) {
  97. $this->skipIf(! $shouldnt_skip, $message);
  98. }
  99. /**
  100. * Used to invoke the single tests.
  101. * @return SimpleInvoker Individual test runner.
  102. * @access public
  103. */
  104. function createInvoker() {
  105. return new SimpleErrorTrappingInvoker(
  106. new SimpleExceptionTrappingInvoker(new SimpleInvoker($this)));
  107. }
  108. /**
  109. * Uses reflection to run every method within itself
  110. * starting with the string "test" unless a method
  111. * is specified.
  112. * @param SimpleReporter $reporter Current test reporter.
  113. * @return boolean True if all tests passed.
  114. * @access public
  115. */
  116. function run($reporter) {
  117. $context = SimpleTest::getContext();
  118. $context->setTest($this);
  119. $context->setReporter($reporter);
  120. $this->reporter = $reporter;
  121. $started = false;
  122. foreach ($this->getTests() as $method) {
  123. if ($reporter->shouldInvoke($this->getLabel(), $method)) {
  124. $this->skip();
  125. if ($this->should_skip) {
  126. break;
  127. }
  128. if (! $started) {
  129. $reporter->paintCaseStart($this->getLabel());
  130. $started = true;
  131. }
  132. $invoker = $this->reporter->createInvoker($this->createInvoker());
  133. $invoker->before($method);
  134. $invoker->invoke($method);
  135. $invoker->after($method);
  136. }
  137. }
  138. if ($started) {
  139. $reporter->paintCaseEnd($this->getLabel());
  140. }
  141. unset($this->reporter);
  142. return $reporter->getStatus();
  143. }
  144. /**
  145. * Gets a list of test names. Normally that will
  146. * be all internal methods that start with the
  147. * name "test". This method should be overridden
  148. * if you want a different rule.
  149. * @return array List of test names.
  150. * @access public
  151. */
  152. function getTests() {
  153. $methods = array();
  154. foreach (get_class_methods(get_class($this)) as $method) {
  155. if ($this->isTest($method)) {
  156. $methods[] = $method;
  157. }
  158. }
  159. return $methods;
  160. }
  161. /**
  162. * Tests to see if the method is a test that should
  163. * be run. Currently any method that starts with 'test'
  164. * is a candidate unless it is the constructor.
  165. * @param string $method Method name to try.
  166. * @return boolean True if test method.
  167. * @access protected
  168. */
  169. protected function isTest($method) {
  170. if (strtolower(substr($method, 0, 4)) == 'test') {
  171. return ! SimpleTestCompatibility::isA($this, strtolower($method));
  172. }
  173. return false;
  174. }
  175. /**
  176. * Announces the start of the test.
  177. * @param string $method Test method just started.
  178. * @access public
  179. */
  180. function before($method) {
  181. $this->reporter->paintMethodStart($method);
  182. $this->observers = array();
  183. }
  184. /**
  185. * Sets up unit test wide variables at the start
  186. * of each test method. To be overridden in
  187. * actual user test cases.
  188. * @access public
  189. */
  190. function setUp() {
  191. }
  192. /**
  193. * Clears the data set in the setUp() method call.
  194. * To be overridden by the user in actual user test cases.
  195. * @access public
  196. */
  197. function tearDown() {
  198. }
  199. /**
  200. * Announces the end of the test. Includes private clean up.
  201. * @param string $method Test method just finished.
  202. * @access public
  203. */
  204. function after($method) {
  205. for ($i = 0; $i < count($this->observers); $i++) {
  206. $this->observers[$i]->atTestEnd($method, $this);
  207. }
  208. $this->reporter->paintMethodEnd($method);
  209. }
  210. /**
  211. * Sets up an observer for the test end.
  212. * @param object $observer Must have atTestEnd()
  213. * method.
  214. * @access public
  215. */
  216. function tell($observer) {
  217. $this->observers[] = &$observer;
  218. }
  219. /**
  220. * @deprecated
  221. */
  222. function pass($message = "Pass") {
  223. if (! isset($this->reporter)) {
  224. trigger_error('Can only make assertions within test methods');
  225. }
  226. $this->reporter->paintPass(
  227. $message . $this->getAssertionLine());
  228. return true;
  229. }
  230. /**
  231. * Sends a fail event with a message.
  232. * @param string $message Message to send.
  233. * @access public
  234. */
  235. function fail($message = "Fail") {
  236. if (! isset($this->reporter)) {
  237. trigger_error('Can only make assertions within test methods');
  238. }
  239. $this->reporter->paintFail(
  240. $message . $this->getAssertionLine());
  241. return false;
  242. }
  243. /**
  244. * Formats a PHP error and dispatches it to the
  245. * reporter.
  246. * @param integer $severity PHP error code.
  247. * @param string $message Text of error.
  248. * @param string $file File error occoured in.
  249. * @param integer $line Line number of error.
  250. * @access public
  251. */
  252. function error($severity, $message, $file, $line) {
  253. if (! isset($this->reporter)) {
  254. trigger_error('Can only make assertions within test methods');
  255. }
  256. $this->reporter->paintError(
  257. "Unexpected PHP error [$message] severity [$severity] in [$file line $line]");
  258. }
  259. /**
  260. * Formats an exception and dispatches it to the
  261. * reporter.
  262. * @param Exception $exception Object thrown.
  263. * @access public
  264. */
  265. function exception($exception) {
  266. $this->reporter->paintException($exception);
  267. }
  268. /**
  269. * For user defined expansion of the available messages.
  270. * @param string $type Tag for sorting the signals.
  271. * @param mixed $payload Extra user specific information.
  272. */
  273. function signal($type, $payload) {
  274. if (! isset($this->reporter)) {
  275. trigger_error('Can only make assertions within test methods');
  276. }
  277. $this->reporter->paintSignal($type, $payload);
  278. }
  279. /**
  280. * Runs an expectation directly, for extending the
  281. * tests with new expectation classes.
  282. * @param SimpleExpectation $expectation Expectation subclass.
  283. * @param mixed $compare Value to compare.
  284. * @param string $message Message to display.
  285. * @return boolean True on pass
  286. * @access public
  287. */
  288. function assert($expectation, $compare, $message = '%s') {
  289. if ($expectation->test($compare)) {
  290. return $this->pass(sprintf(
  291. $message,
  292. $expectation->overlayMessage($compare, $this->reporter->getDumper())));
  293. } else {
  294. return $this->fail(sprintf(
  295. $message,
  296. $expectation->overlayMessage($compare, $this->reporter->getDumper())));
  297. }
  298. }
  299. /**
  300. * Uses a stack trace to find the line of an assertion.
  301. * @return string Line number of first assert*
  302. * method embedded in format string.
  303. * @access public
  304. */
  305. function getAssertionLine() {
  306. $trace = new SimpleStackTrace(array('assert', 'expect', 'pass', 'fail', 'skip'));
  307. return $trace->traceMethod();
  308. }
  309. /**
  310. * Sends a formatted dump of a variable to the
  311. * test suite for those emergency debugging
  312. * situations.
  313. * @param mixed $variable Variable to display.
  314. * @param string $message Message to display.
  315. * @return mixed The original variable.
  316. * @access public
  317. */
  318. function dump($variable, $message = false) {
  319. $dumper = $this->reporter->getDumper();
  320. $formatted = $dumper->dump($variable);
  321. if ($message) {
  322. $formatted = $message . "\n" . $formatted;
  323. }
  324. $this->reporter->paintFormattedMessage($formatted);
  325. return $variable;
  326. }
  327. /**
  328. * Accessor for the number of subtests including myelf.
  329. * @return integer Number of test cases.
  330. * @access public
  331. */
  332. function getSize() {
  333. return 1;
  334. }
  335. }
  336. /**
  337. * Helps to extract test cases automatically from a file.
  338. * @package SimpleTest
  339. * @subpackage UnitTester
  340. */
  341. class SimpleFileLoader {
  342. /**
  343. * Builds a test suite from a library of test cases.
  344. * The new suite is composed into this one.
  345. * @param string $test_file File name of library with
  346. * test case classes.
  347. * @return TestSuite The new test suite.
  348. * @access public
  349. */
  350. function load($test_file) {
  351. $existing_classes = get_declared_classes();
  352. $existing_globals = get_defined_vars();
  353. include_once($test_file);
  354. $new_globals = get_defined_vars();
  355. $this->makeFileVariablesGlobal($existing_globals, $new_globals);
  356. $new_classes = array_diff(get_declared_classes(), $existing_classes);
  357. if (empty($new_classes)) {
  358. $new_classes = $this->scrapeClassesFromFile($test_file);
  359. }
  360. $classes = $this->selectRunnableTests($new_classes);
  361. return $this->createSuiteFromClasses($test_file, $classes);
  362. }
  363. /**
  364. * Imports new variables into the global namespace.
  365. * @param hash $existing Variables before the file was loaded.
  366. * @param hash $new Variables after the file was loaded.
  367. * @access private
  368. */
  369. protected function makeFileVariablesGlobal($existing, $new) {
  370. $globals = array_diff(array_keys($new), array_keys($existing));
  371. foreach ($globals as $global) {
  372. $GLOBALS[$global] = $new[$global];
  373. }
  374. }
  375. /**
  376. * Lookup classnames from file contents, in case the
  377. * file may have been included before.
  378. * Note: This is probably too clever by half. Figuring this
  379. * out after a failed test case is going to be tricky for us,
  380. * never mind the user. A test case should not be included
  381. * twice anyway.
  382. * @param string $test_file File name with classes.
  383. * @access private
  384. */
  385. protected function scrapeClassesFromFile($test_file) {
  386. preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi',
  387. file_get_contents($test_file),
  388. $matches );
  389. return $matches[1];
  390. }
  391. /**
  392. * Calculates the incoming test cases. Skips abstract
  393. * and ignored classes.
  394. * @param array $candidates Candidate classes.
  395. * @return array New classes which are test
  396. * cases that shouldn't be ignored.
  397. * @access public
  398. */
  399. function selectRunnableTests($candidates) {
  400. $classes = array();
  401. foreach ($candidates as $class) {
  402. if (TestSuite::getBaseTestCase($class)) {
  403. $reflection = new SimpleReflection($class);
  404. if ($reflection->isAbstract()) {
  405. SimpleTest::ignore($class);
  406. } else {
  407. $classes[] = $class;
  408. }
  409. }
  410. }
  411. return $classes;
  412. }
  413. /**
  414. * Builds a test suite from a class list.
  415. * @param string $title Title of new group.
  416. * @param array $classes Test classes.
  417. * @return TestSuite Group loaded with the new
  418. * test cases.
  419. * @access public
  420. */
  421. function createSuiteFromClasses($title, $classes) {
  422. if (count($classes) == 0) {
  423. $suite = new BadTestSuite($title, "No runnable test cases in [$title]");
  424. return $suite;
  425. }
  426. SimpleTest::ignoreParentsIfIgnored($classes);
  427. $suite = new TestSuite($title);
  428. foreach ($classes as $class) {
  429. if (! SimpleTest::isIgnored($class)) {
  430. $suite->add($class);
  431. }
  432. }
  433. return $suite;
  434. }
  435. }
  436. /**
  437. * This is a composite test class for combining
  438. * test cases and other RunnableTest classes into
  439. * a group test.
  440. * @package SimpleTest
  441. * @subpackage UnitTester
  442. */
  443. class TestSuite {
  444. private $label;
  445. private $test_cases;
  446. /**
  447. * Sets the name of the test suite.
  448. * @param string $label Name sent at the start and end
  449. * of the test.
  450. * @access public
  451. */
  452. function TestSuite($label = false) {
  453. $this->label = $label;
  454. $this->test_cases = array();
  455. }
  456. /**
  457. * Accessor for the test name for subclasses. If the suite
  458. * wraps a single test case the label defaults to the name of that test.
  459. * @return string Name of the test.
  460. * @access public
  461. */
  462. function getLabel() {
  463. if (! $this->label) {
  464. return ($this->getSize() == 1) ?
  465. get_class($this->test_cases[0]) : get_class($this);
  466. } else {
  467. return $this->label;
  468. }
  469. }
  470. /**
  471. * Adds a test into the suite by instance or class. The class will
  472. * be instantiated if it's a test suite.
  473. * @param SimpleTestCase $test_case Suite or individual test
  474. * case implementing the
  475. * runnable test interface.
  476. * @access public
  477. */
  478. function add($test_case) {
  479. if (! is_string($test_case)) {
  480. $this->test_cases[] = $test_case;
  481. } elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') {
  482. $this->test_cases[] = new $test_case();
  483. } else {
  484. $this->test_cases[] = $test_case;
  485. }
  486. }
  487. /**
  488. * Builds a test suite from a library of test cases.
  489. * The new suite is composed into this one.
  490. * @param string $test_file File name of library with
  491. * test case classes.
  492. * @access public
  493. */
  494. function addFile($test_file) {
  495. $extractor = new SimpleFileLoader();
  496. $this->add($extractor->load($test_file));
  497. }
  498. /**
  499. * Delegates to a visiting collector to add test
  500. * files.
  501. * @param string $path Path to scan from.
  502. * @param SimpleCollector $collector Directory scanner.
  503. * @access public
  504. */
  505. function collect($path, $collector) {
  506. $collector->collect($this, $path);
  507. }
  508. /**
  509. * Invokes run() on all of the held test cases, instantiating
  510. * them if necessary.
  511. * @param SimpleReporter $reporter Current test reporter.
  512. * @access public
  513. */
  514. function run($reporter) {
  515. $reporter->paintGroupStart($this->getLabel(), $this->getSize());
  516. for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) {
  517. if (is_string($this->test_cases[$i])) {
  518. $class = $this->test_cases[$i];
  519. $test = new $class();
  520. $test->run($reporter);
  521. unset($test);
  522. } else {
  523. $this->test_cases[$i]->run($reporter);
  524. }
  525. }
  526. $reporter->paintGroupEnd($this->getLabel());
  527. return $reporter->getStatus();
  528. }
  529. /**
  530. * Number of contained test cases.
  531. * @return integer Total count of cases in the group.
  532. * @access public
  533. */
  534. function getSize() {
  535. $count = 0;
  536. foreach ($this->test_cases as $case) {
  537. if (is_string($case)) {
  538. if (! SimpleTest::isIgnored($case)) {
  539. $count++;
  540. }
  541. } else {
  542. $count += $case->getSize();
  543. }
  544. }
  545. return $count;
  546. }
  547. /**
  548. * Test to see if a class is derived from the
  549. * SimpleTestCase class.
  550. * @param string $class Class name.
  551. * @access public
  552. */
  553. static function getBaseTestCase($class) {
  554. while ($class = get_parent_class($class)) {
  555. $class = strtolower($class);
  556. if ($class == 'simpletestcase' || $class == 'testsuite') {
  557. return $class;
  558. }
  559. }
  560. return false;
  561. }
  562. }
  563. /**
  564. * This is a failing group test for when a test suite hasn't
  565. * loaded properly.
  566. * @package SimpleTest
  567. * @subpackage UnitTester
  568. */
  569. class BadTestSuite {
  570. private $label;
  571. private $error;
  572. /**
  573. * Sets the name of the test suite and error message.
  574. * @param string $label Name sent at the start and end
  575. * of the test.
  576. * @access public
  577. */
  578. function BadTestSuite($label, $error) {
  579. $this->label = $label;
  580. $this->error = $error;
  581. }
  582. /**
  583. * Accessor for the test name for subclasses.
  584. * @return string Name of the test.
  585. * @access public
  586. */
  587. function getLabel() {
  588. return $this->label;
  589. }
  590. /**
  591. * Sends a single error to the reporter.
  592. * @param SimpleReporter $reporter Current test reporter.
  593. * @access public
  594. */
  595. function run($reporter) {
  596. $reporter->paintGroupStart($this->getLabel(), $this->getSize());
  597. $reporter->paintFail('Bad TestSuite [' . $this->getLabel() .
  598. '] with error [' . $this->error . ']');
  599. $reporter->paintGroupEnd($this->getLabel());
  600. return $reporter->getStatus();
  601. }
  602. /**
  603. * Number of contained test cases. Always zero.
  604. * @return integer Total count of cases in the group.
  605. * @access public
  606. */
  607. function getSize() {
  608. return 0;
  609. }
  610. }
  611. ?>