test_case.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. <?php
  2. /**
  3. * Base include file for SimpleTest
  4. * @package SimpleTest
  5. * @subpackage UnitTester
  6. * @version $Id: test_case.php 1786 2008-04-26 17:32:20Z pp11 $
  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. if (! defined('SIMPLE_TEST')) {
  22. /**
  23. * @ignore
  24. */
  25. define('SIMPLE_TEST', dirname(__FILE__) . DIRECTORY_SEPARATOR);
  26. }
  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 SimpleExceptionTrappingInvoker(
  106. new SimpleErrorTrappingInvoker(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. */
  339. class SimpleFileLoader {
  340. /**
  341. * Builds a test suite from a library of test cases.
  342. * The new suite is composed into this one.
  343. * @param string $test_file File name of library with
  344. * test case classes.
  345. * @return TestSuite The new test suite.
  346. * @access public
  347. */
  348. function load($test_file) {
  349. $existing_classes = get_declared_classes();
  350. $existing_globals = get_defined_vars();
  351. include_once($test_file);
  352. $new_globals = get_defined_vars();
  353. $this->makeFileVariablesGlobal($existing_globals, $new_globals);
  354. $new_classes = array_diff(get_declared_classes(), $existing_classes);
  355. if (empty($new_classes)) {
  356. $new_classes = $this->scrapeClassesFromFile($test_file);
  357. }
  358. $classes = $this->selectRunnableTests($new_classes);
  359. return $this->createSuiteFromClasses($test_file, $classes);
  360. }
  361. /**
  362. * Imports new variables into the global namespace.
  363. * @param hash $existing Variables before the file was loaded.
  364. * @param hash $new Variables after the file was loaded.
  365. * @access private
  366. */
  367. protected function makeFileVariablesGlobal($existing, $new) {
  368. $globals = array_diff(array_keys($new), array_keys($existing));
  369. foreach ($globals as $global) {
  370. $_GLOBALS[$global] = $new[$global];
  371. }
  372. }
  373. /**
  374. * Lookup classnames from file contents, in case the
  375. * file may have been included before.
  376. * Note: This is probably too clever by half. Figuring this
  377. * out after a failed test case is going to be tricky for us,
  378. * never mind the user. A test case should not be included
  379. * twice anyway.
  380. * @param string $test_file File name with classes.
  381. * @access private
  382. */
  383. protected function scrapeClassesFromFile($test_file) {
  384. preg_match_all('~^\s*class\s+(\w+)(\s+(extends|implements)\s+\w+)*\s*\{~mi',
  385. file_get_contents($test_file),
  386. $matches );
  387. return $matches[1];
  388. }
  389. /**
  390. * Calculates the incoming test cases. Skips abstract
  391. * and ignored classes.
  392. * @param array $candidates Candidate classes.
  393. * @return array New classes which are test
  394. * cases that shouldn't be ignored.
  395. * @access public
  396. */
  397. function selectRunnableTests($candidates) {
  398. $classes = array();
  399. foreach ($candidates as $class) {
  400. if (TestSuite::getBaseTestCase($class)) {
  401. $reflection = new SimpleReflection($class);
  402. if ($reflection->isAbstract()) {
  403. SimpleTest::ignore($class);
  404. } else {
  405. $classes[] = $class;
  406. }
  407. }
  408. }
  409. return $classes;
  410. }
  411. /**
  412. * Builds a test suite from a class list.
  413. * @param string $title Title of new group.
  414. * @param array $classes Test classes.
  415. * @return TestSuite Group loaded with the new
  416. * test cases.
  417. * @access public
  418. */
  419. function createSuiteFromClasses($title, $classes) {
  420. if (count($classes) == 0) {
  421. $suite = new BadTestSuite($title, "No runnable test cases in [$title]");
  422. return $suite;
  423. }
  424. SimpleTest::ignoreParentsIfIgnored($classes);
  425. $suite = new TestSuite($title);
  426. foreach ($classes as $class) {
  427. if (! SimpleTest::isIgnored($class)) {
  428. $suite->add($class);
  429. }
  430. }
  431. return $suite;
  432. }
  433. }
  434. /**
  435. * This is a composite test class for combining
  436. * test cases and other RunnableTest classes into
  437. * a group test.
  438. * @package SimpleTest
  439. * @subpackage UnitTester
  440. */
  441. class TestSuite {
  442. private $label;
  443. private $test_cases;
  444. /**
  445. * Sets the name of the test suite.
  446. * @param string $label Name sent at the start and end
  447. * of the test.
  448. * @access public
  449. */
  450. function TestSuite($label = false) {
  451. $this->label = $label;
  452. $this->test_cases = array();
  453. }
  454. /**
  455. * Accessor for the test name for subclasses. If the suite
  456. * wraps a single test case the label defaults to the name of that test.
  457. * @return string Name of the test.
  458. * @access public
  459. */
  460. function getLabel() {
  461. if (! $this->label) {
  462. return ($this->getSize() == 1) ?
  463. get_class($this->test_cases[0]) : get_class($this);
  464. } else {
  465. return $this->label;
  466. }
  467. }
  468. /**
  469. * Adds a test into the suite by instance or class. The class will
  470. * be instantiated if it's a test suite.
  471. * @param SimpleTestCase $test_case Suite or individual test
  472. * case implementing the
  473. * runnable test interface.
  474. * @access public
  475. */
  476. function add($test_case) {
  477. if (! is_string($test_case)) {
  478. $this->test_cases[] = $test_case;
  479. } elseif (TestSuite::getBaseTestCase($test_case) == 'testsuite') {
  480. $this->test_cases[] = new $test_case();
  481. } else {
  482. $this->test_cases[] = $test_case;
  483. }
  484. }
  485. /**
  486. * Builds a test suite from a library of test cases.
  487. * The new suite is composed into this one.
  488. * @param string $test_file File name of library with
  489. * test case classes.
  490. * @access public
  491. */
  492. function addFile($test_file) {
  493. $extractor = new SimpleFileLoader();
  494. $this->add($extractor->load($test_file));
  495. }
  496. /**
  497. * Delegates to a visiting collector to add test
  498. * files.
  499. * @param string $path Path to scan from.
  500. * @param SimpleCollector $collector Directory scanner.
  501. * @access public
  502. */
  503. function collect($path, $collector) {
  504. $collector->collect($this, $path);
  505. }
  506. /**
  507. * Invokes run() on all of the held test cases, instantiating
  508. * them if necessary.
  509. * @param SimpleReporter $reporter Current test reporter.
  510. * @access public
  511. */
  512. function run($reporter) {
  513. $reporter->paintGroupStart($this->getLabel(), $this->getSize());
  514. for ($i = 0, $count = count($this->test_cases); $i < $count; $i++) {
  515. if (is_string($this->test_cases[$i])) {
  516. $class = $this->test_cases[$i];
  517. $test = new $class();
  518. $test->run($reporter);
  519. unset($test);
  520. } else {
  521. $this->test_cases[$i]->run($reporter);
  522. }
  523. }
  524. $reporter->paintGroupEnd($this->getLabel());
  525. return $reporter->getStatus();
  526. }
  527. /**
  528. * Number of contained test cases.
  529. * @return integer Total count of cases in the group.
  530. * @access public
  531. */
  532. function getSize() {
  533. $count = 0;
  534. foreach ($this->test_cases as $case) {
  535. if (is_string($case)) {
  536. if (! SimpleTest::isIgnored($case)) {
  537. $count++;
  538. }
  539. } else {
  540. $count += $case->getSize();
  541. }
  542. }
  543. return $count;
  544. }
  545. /**
  546. * Test to see if a class is derived from the
  547. * SimpleTestCase class.
  548. * @param string $class Class name.
  549. * @access public
  550. */
  551. static function getBaseTestCase($class) {
  552. while ($class = get_parent_class($class)) {
  553. $class = strtolower($class);
  554. if ($class == 'simpletestcase' || $class == 'testsuite') {
  555. return $class;
  556. }
  557. }
  558. return false;
  559. }
  560. }
  561. /**
  562. * This is a failing group test for when a test suite hasn't
  563. * loaded properly.
  564. * @package SimpleTest
  565. * @subpackage UnitTester
  566. */
  567. class BadTestSuite {
  568. private $label;
  569. private $error;
  570. /**
  571. * Sets the name of the test suite and error message.
  572. * @param string $label Name sent at the start and end
  573. * of the test.
  574. * @access public
  575. */
  576. function BadTestSuite($label, $error) {
  577. $this->label = $label;
  578. $this->error = $error;
  579. }
  580. /**
  581. * Accessor for the test name for subclasses.
  582. * @return string Name of the test.
  583. * @access public
  584. */
  585. function getLabel() {
  586. return $this->label;
  587. }
  588. /**
  589. * Sends a single error to the reporter.
  590. * @param SimpleReporter $reporter Current test reporter.
  591. * @access public
  592. */
  593. function run($reporter) {
  594. $reporter->paintGroupStart($this->getLabel(), $this->getSize());
  595. $reporter->paintFail('Bad TestSuite [' . $this->getLabel() .
  596. '] with error [' . $this->error . ']');
  597. $reporter->paintGroupEnd($this->getLabel());
  598. return $reporter->getStatus();
  599. }
  600. /**
  601. * Number of contained test cases. Always zero.
  602. * @return integer Total count of cases in the group.
  603. * @access public
  604. */
  605. function getSize() {
  606. return 0;
  607. }
  608. }
  609. ?>