PageRenderTime 54ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/libraries/phpunit/phpunit.php

https://github.com/guzzisto/retrospect-gds
PHP | 622 lines | 429 code | 85 blank | 108 comment | 83 complexity | e1a816f62a4d3b7ced155fdec4e1a2e6 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1
  1. <?php
  2. //
  3. // PHP framework for testing, based on the design of "JUnit".
  4. //
  5. // Written by Fred Yankowski <fred@ontosys.com>
  6. // OntoSys, Inc <http://www.OntoSys.com>
  7. //
  8. // $Id: phpunit.php,v 1.11 2002/10/31 18:44:12 fredy Exp $
  9. // Copyright (c) 2000 Fred Yankowski
  10. // Permission is hereby granted, free of charge, to any person
  11. // obtaining a copy of this software and associated documentation
  12. // files (the "Software"), to deal in the Software without
  13. // restriction, including without limitation the rights to use, copy,
  14. // modify, merge, publish, distribute, sublicense, and/or sell copies
  15. // of the Software, and to permit persons to whom the Software is
  16. // furnished to do so, subject to the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  25. // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  26. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  27. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  28. // SOFTWARE.
  29. //
  30. error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE |
  31. E_CORE_ERROR | E_CORE_WARNING);
  32. /*
  33. interface Test {
  34. function run(&$aTestResult);
  35. function countTestCases();
  36. }
  37. */
  38. function trace($msg) {
  39. return;
  40. print($msg);
  41. flush();
  42. }
  43. if (phpversion() >= '4') {
  44. function PHPUnit_error_handler($errno, $errstr, $errfile, $errline) {
  45. global $PHPUnit_testRunning;
  46. $PHPUnit_testRunning[0]->fail("<B>PHP ERROR:</B> ".$errstr." <B>in</B> ".$errfile." <B>at line</B> ".$errline);
  47. }
  48. }
  49. class Exception {
  50. /* Emulate a Java exception, sort of... */
  51. var $message;
  52. var $type;
  53. function Exception($message, $type = 'FAILURE') {
  54. $this->message = $message;
  55. $this->type = $type;
  56. }
  57. function getMessage() {
  58. return $this->message;
  59. }
  60. function getType() {
  61. return $this->type;
  62. }
  63. }
  64. class Assert {
  65. function assert($boolean, $message=0) {
  66. if (! $boolean)
  67. $this->fail($message);
  68. }
  69. function assertEquals($expected, $actual, $message=0) {
  70. if (gettype($expected) != gettype($actual)) {
  71. $this->failNotEquals($expected, $actual, "expected", $message);
  72. return;
  73. }
  74. if (phpversion() < '4') {
  75. if (is_object($expected) or is_object($actual)
  76. or is_array($expected) or is_array($actual)) {
  77. $this->error("INVALID TEST: cannot compare arrays or objects in PHP3");
  78. return;
  79. }
  80. }
  81. if (phpversion() >= '4' && is_object($expected)) {
  82. if (get_class($expected) != get_class($actual)) {
  83. $this->failNotEquals($expected, $actual, "expected", $message);
  84. return;
  85. }
  86. if (method_exists($expected, "equals")) {
  87. if (! $expected->equals($actual)) {
  88. $this->failNotEquals($expected, $actual, "expected", $message);
  89. }
  90. return; // no further tests after equals()
  91. }
  92. }
  93. if (phpversion() >= '4.0.4') {
  94. if (is_null($expected) != is_null($actual)) {
  95. $this->failNotEquals($expected, $actual, "expected", $message);
  96. return;
  97. }
  98. }
  99. if ($expected != $actual) {
  100. $this->failNotEquals($expected, $actual, "expected", $message);
  101. }
  102. }
  103. function assertRegexp($regexp, $actual, $message=false) {
  104. if (! preg_match($regexp, $actual)) {
  105. $this->failNotEquals($regexp, $actual, "pattern", $message);
  106. }
  107. }
  108. function assertEqualsMultilineStrings($string0, $string1,
  109. $message="") {
  110. $lines0 = split("\n",$string0);
  111. $lines1 = split("\n",$string1);
  112. if (sizeof($lines0) != sizeof($lines1)) {
  113. $this->failNotEquals(sizeof($lines0)." line(s)",
  114. sizeof($lines1)." line(s)", "expected", $message);
  115. }
  116. for($i=0; $i< sizeof($lines0); $i++) {
  117. $this->assertEquals(trim($lines0[$i]),
  118. trim($lines1[$i]),
  119. "line ".($i+1)." of multiline strings differ. ".$message);
  120. }
  121. }
  122. function _formatValue($value, $class="") {
  123. $translateValue = $value;
  124. if (phpversion() >= '4.0.0') {
  125. if (is_object($value)) {
  126. if (method_exists($value, "toString") ) {
  127. $translateValue = $value->toString();
  128. }
  129. else {
  130. $translateValue = serialize($value);
  131. }
  132. }
  133. else if (is_array($value)) {
  134. $translateValue = serialize($value);
  135. }
  136. }
  137. $htmlValue = "$class: ".htmlspecialchars($translateValue);
  138. if (phpversion() >= '4.0.0') {
  139. if (is_bool($value)) {
  140. $htmlValue = $value ? "<i>true</i>" : "<i>false</i>";
  141. }
  142. elseif (phpversion() >= '4.0.4' && is_null($value)) {
  143. $htmlValue = "<i>null</i>";
  144. }
  145. $htmlValue .= " (" . gettype($value);
  146. $htmlValue .= is_object($value) ? ", class:" . get_class($value) : ")";
  147. }
  148. return $htmlValue;
  149. }
  150. function failNotEquals($expected, $actual, $expected_label, $message=0) {
  151. // Private function for reporting failure to match.
  152. $str = $message ? ($message . ' ') : '';
  153. $str .= sprintf("%s\r\n\t%s",
  154. $this->_formatValue($expected, "expected"),
  155. $this->_formatValue($actual, "actual"));
  156. $this->fail($str);
  157. }
  158. }
  159. class TestCase extends Assert /* implements Test */ {
  160. /* Defines context for running tests. Specific context -- such as
  161. instance variables, global variables, global state -- is defined
  162. by creating a subclass that specializes the setUp() and
  163. tearDown() methods. A specific test is defined by a subclass
  164. that specializes the runTest() method. */
  165. var $fName;
  166. var $fClassName;
  167. var $fResult;
  168. var $fExceptions = array();
  169. function TestCase($name) {
  170. $this->fName = $name;
  171. }
  172. function run($testResult=0) {
  173. /* Run this single test, by calling the run() method of the
  174. TestResult object which will in turn call the runBare() method
  175. of this object. That complication allows the TestResult object
  176. to do various kinds of progress reporting as it invokes each
  177. test. Create/obtain a TestResult object if none was passed in.
  178. Note that if a TestResult object was passed in, it must be by
  179. reference. */
  180. if (! $testResult)
  181. $testResult = $this->_createResult();
  182. $this->fResult = $testResult;
  183. $testResult->run(&$this);
  184. $this->fResult = 0;
  185. return $testResult;
  186. }
  187. function classname() {
  188. if (isset($this->fClassName)) {
  189. return $this->fClassName;
  190. } else {
  191. return get_class($this);
  192. }
  193. }
  194. function countTestCases() {
  195. return 1;
  196. }
  197. function runTest() {
  198. if (phpversion() >= '4') {
  199. global $PHPUnit_testRunning;
  200. eval('$PHPUnit_testRunning[0] = & $this;');
  201. // Saved ref to current TestCase, so that the error handler
  202. // can access it. This code won't even parse in PHP3, so we
  203. // hide it in an eval.
  204. $old_handler = set_error_handler("PHPUnit_error_handler");
  205. // errors will now be handled by our error handler
  206. }
  207. $name = $this->name();
  208. if (phpversion() >= '4' && ! method_exists($this, $name)) {
  209. $this->error("Method '$name' does not exist");
  210. }
  211. else
  212. $this->$name();
  213. if (phpversion() >= '4') {
  214. #set_error_handler($old_handler); // revert to prior error handler
  215. $PHPUnit_testRunning = null;
  216. }
  217. }
  218. function setUp() /* expect override */ {
  219. //print("TestCase::setUp()<br>\n");
  220. }
  221. function tearDown() /* possible override */ {
  222. //print("TestCase::tearDown()<br>\n");
  223. }
  224. ////////////////////////////////////////////////////////////////
  225. function _createResult() /* protected */ {
  226. /* override this to use specialized subclass of TestResult */
  227. return new TestResult;
  228. }
  229. function fail($message=0) {
  230. //printf("TestCase::fail(%s)<br>\n", ($message) ? $message : '');
  231. /* JUnit throws AssertionFailedError here. We just record the
  232. failure and carry on */
  233. $this->fExceptions[] = new Exception(&$message, 'FAILURE');
  234. }
  235. function error($message) {
  236. /* report error that requires correction in the test script
  237. itself, or (heaven forbid) in this testing infrastructure */
  238. $this->fExceptions[] = new Exception(&$message, 'ERROR');
  239. $this->fResult->stop(); // [does not work]
  240. }
  241. function failed() {
  242. reset($this->fExceptions);
  243. while (list($key, $exception) = each($this->fExceptions)) {
  244. if ($exception->type == 'FAILURE')
  245. return true;
  246. }
  247. return false;
  248. }
  249. function errored() {
  250. reset($this->fExceptions);
  251. while (list($key, $exception) = each($this->fExceptions)) {
  252. if ($exception->type == 'ERROR')
  253. return true;
  254. }
  255. return false;
  256. }
  257. function getExceptions() {
  258. return $this->fExceptions;
  259. }
  260. function name() {
  261. return $this->fName;
  262. }
  263. function runBare() {
  264. $this->setup();
  265. $this->runTest();
  266. $this->tearDown();
  267. }
  268. }
  269. class TestSuite /* implements Test */ {
  270. /* Compose a set of Tests (instances of TestCase or TestSuite), and
  271. run them all. */
  272. var $fTests = array();
  273. var $fClassname;
  274. function TestSuite($classname=false) {
  275. // Find all methods of the given class whose name starts with
  276. // "test" and add them to the test suite.
  277. // PHP3: We are just _barely_ able to do this with PHP's limited
  278. // introspection... Note that PHP seems to store method names in
  279. // lower case, and we have to avoid the constructor function for
  280. // the TestCase class superclass. Names of subclasses of TestCase
  281. // must not start with "Test" since such a class will have a
  282. // constructor method name also starting with "test" and we can't
  283. // distinquish such a construtor from the real test method names.
  284. // So don't name any TestCase subclasses as "Test..."!
  285. // PHP4: Never mind all that. We can now ignore constructor
  286. // methods, so a test class may be named "Test...".
  287. if (empty($classname))
  288. return;
  289. $this->fClassname = $classname;
  290. if (floor(phpversion()) >= 4) {
  291. // PHP4 introspection, submitted by Dylan Kuhn
  292. $names = get_class_methods($classname);
  293. while (list($key, $method) = each($names)) {
  294. if (preg_match('/^test/', $method)) {
  295. $test = new $classname($method);
  296. if (strcasecmp($method, $classname) == 0 || is_subclass_of($test, $method)) {
  297. // Ignore the given method name since it is a constructor:
  298. // it's the name of our test class or it is the name of a
  299. // superclass of our test class. (This code smells funny.
  300. // Anyone got a better way?)
  301. //print "skipping $method<br>";
  302. }
  303. else {
  304. $this->addTest($test);
  305. }
  306. }
  307. }
  308. }
  309. else { // PHP3
  310. $dummy = new $classname("dummy");
  311. $names = (array) $dummy;
  312. while (list($key, $value) = each($names)) {
  313. $type = gettype($value);
  314. if ($type == "user function" && preg_match('/^test/', $key)
  315. && $key != "testcase") {
  316. $this->addTest(new $classname($key));
  317. }
  318. }
  319. }
  320. }
  321. function addTest($test) {
  322. /* Add TestCase or TestSuite to this TestSuite */
  323. $this->fTests[] = $test;
  324. }
  325. function run(&$testResult) {
  326. /* Run all TestCases and TestSuites comprising this TestSuite,
  327. accumulating results in the given TestResult object. */
  328. reset($this->fTests);
  329. while (list($na, $test) = each($this->fTests)) {
  330. if ($testResult->shouldStop())
  331. break;
  332. $test->run(&$testResult);
  333. }
  334. }
  335. function countTestCases() {
  336. /* Number of TestCases comprising this TestSuite (including those
  337. in any constituent TestSuites) */
  338. $count = 0;
  339. reset($fTests);
  340. while (list($na, $test_case) = each($this->fTests)) {
  341. $count += $test_case->countTestCases();
  342. }
  343. return $count;
  344. }
  345. }
  346. class TestFailure {
  347. /* Record failure of a single TestCase, associating it with the
  348. exception that occurred */
  349. var $fFailedTestName;
  350. var $fException;
  351. function TestFailure(&$test, &$exception) {
  352. $this->fFailedTestName = $test->name();
  353. $this->fException = $exception;
  354. }
  355. function getExceptions() {
  356. // deprecated
  357. return array($this->fException);
  358. }
  359. function getException() {
  360. return $this->fException;
  361. }
  362. function getTestName() {
  363. return $this->fFailedTestName;
  364. }
  365. }
  366. class TestResult {
  367. /* Collect the results of running a set of TestCases. */
  368. var $fFailures = array();
  369. var $fErrors = array();
  370. var $fRunTests = 0;
  371. var $fStop = false;
  372. function TestResult() { }
  373. function _endTest($test) /* protected */ {
  374. /* specialize this for end-of-test action, such as progress
  375. reports */
  376. }
  377. function addError($test, $exception) {
  378. $this->fErrors[] = new TestFailure(&$test, &$exception);
  379. }
  380. function addFailure($test, $exception) {
  381. $this->fFailures[] = new TestFailure(&$test, &$exception);
  382. }
  383. function getFailures() {
  384. return $this->fFailures;
  385. }
  386. function run($test) {
  387. /* Run a single TestCase in the context of this TestResult */
  388. $this->_startTest($test);
  389. $this->fRunTests++;
  390. $test->runBare();
  391. /* this is where JUnit would catch AssertionFailedError */
  392. $exceptions = $test->getExceptions();
  393. reset($exceptions);
  394. while (list($key, $exception) = each($exceptions)) {
  395. if ($exception->type == 'ERROR')
  396. $this->addError($test, $exception);
  397. else if ($exception->type == 'FAILURE')
  398. $this->addFailure($test, $exception);
  399. }
  400. // if ($exceptions)
  401. // $this->fFailures[] = new TestFailure(&$test, &$exceptions);
  402. $this->_endTest($test);
  403. }
  404. function countTests() {
  405. return $this->fRunTests;
  406. }
  407. function shouldStop() {
  408. return $this->fStop;
  409. }
  410. function _startTest($test) /* protected */ {
  411. /* specialize this for start-of-test actions */
  412. }
  413. function stop() {
  414. /* set indication that the test sequence should halt */
  415. $fStop = true;
  416. }
  417. function errorCount() {
  418. return count($this->fErrors);
  419. }
  420. function failureCount() {
  421. return count($this->fFailures);
  422. }
  423. function countFailures() {
  424. // deprecated
  425. return $this->failureCount();
  426. }
  427. }
  428. class TextTestResult extends TestResult {
  429. /* Specialize TestResult to produce text/html report */
  430. function TextTestResult() {
  431. $this->TestResult(); // call superclass constructor
  432. }
  433. function report() {
  434. /* report result of test run */
  435. $nRun = $this->countTests();
  436. $nFailures = $this->failureCount();
  437. $nErrors = $this->errorCount();
  438. printf("%s test%s run\r\n", $nRun, ($nRun == 1) ? '' : 's');
  439. printf("%s failure%s\r", $nFailures, ($nFailures == 1) ? '' : 's');
  440. printf("%s error%s.\r", $nErrors, ($nErrors == 1) ? '' : 's');
  441. if ($nFailures > 0) {
  442. print("\r\n\r\nFailures\r\n");
  443. print("--------\r\n\r\n");
  444. $failures = $this->getFailures();
  445. while (list($i, $failure) = each($failures)) {
  446. $failedTestName = $failure->getTestName();
  447. printf("%s:\r\n", $failedTestName);
  448. $exceptions = $failure->getExceptions();
  449. while (list($na, $exception) = each($exceptions))
  450. printf("\t%s\r\n", $exception->getMessage());
  451. }
  452. }
  453. if ($nErrors > 0) {
  454. print("<h2>Errors</h2>");
  455. print("<ol>\n");
  456. reset($this->fErrors);
  457. while (list($i, $error) = each($this->fErrors)) {
  458. $erroredTestName = $error->getTestName();
  459. printf("<li>%s\n", $failedTestName);
  460. $exception = $error->getException();
  461. print("<ul>");
  462. printf("<li>%s\n", $exception->getMessage());
  463. print("</ul>");
  464. }
  465. print("</ol>\n");
  466. }
  467. }
  468. function _startTest($test) {
  469. if (phpversion() > '4') {
  470. printf("%s - %s ", get_class($test), $test->name());
  471. } else {
  472. printf("%s ", $test->name());
  473. }
  474. flush();
  475. }
  476. function _endTest($test) {
  477. $outcome = $test->failed() ? "FAIL": "OK";
  478. printf("$outcome\r\n");
  479. flush();
  480. }
  481. }
  482. // PrettyTestResult created by BJG 17/11/01
  483. // beacuse the standard test result provided looks
  484. // rubbish.
  485. class PrettyTestResult extends TestResult {
  486. /* Specialize TestResult to produce text/html report */
  487. function PrettyTestResult() {
  488. $this->TestResult(); // call superclass constructor
  489. echo "<h2>Tests</h2>";
  490. echo "<TABLE CELLSPACING=\"1\" CELLPADDING=\"1\" BORDER=\"0\" WIDTH=\"90%\" ALIGN=\"CENTER\" class=\"details\">";
  491. echo "<TR><TH>Class</TH><TH>Function</TH><TH>Success?</TH></TR>";
  492. }
  493. function report() {
  494. echo "</TABLE>";
  495. /* report result of test run */
  496. $nRun = $this->countTests();
  497. $nFailures = $this->countFailures();
  498. echo "<h2>Summary</h2>";
  499. printf("<p>%s test%s run<br>", $nRun, ($nRun == 1) ? '' : 's');
  500. printf("%s failure%s.<br>\n", $nFailures, ($nFailures == 1) ? '' : 's');
  501. if ($nFailures == 0)
  502. return;
  503. echo "<h2>Failure Details</h2>";
  504. print("<ol>\n");
  505. $failures = $this->getFailures();
  506. while (list($i, $failure) = each($failures)) {
  507. $failedTestName = $failure->getTestName();
  508. printf("<li>%s\n", $failedTestName);
  509. $exceptions = $failure->getExceptions();
  510. print("<ul>");
  511. while (list($na, $exception) = each($exceptions))
  512. printf("<li>%s\n", $exception->getMessage());
  513. print("</ul>");
  514. }
  515. print("</ol>\n");
  516. }
  517. function _startTest($test) {
  518. printf("<TR><TD>%s </TD><TD>%s </TD>", $test->classname(),$test->name());
  519. flush();
  520. }
  521. function _endTest($test) {
  522. $outcome = $test->failed()
  523. ? " class=\"Failure\">FAIL"
  524. : " class=\"Pass\">OK";
  525. printf("<TD$outcome</TD></TR>");
  526. flush();
  527. }
  528. }
  529. class TestRunner {
  530. /* Run a suite of tests and report results. */
  531. function run($suite) {
  532. $result = new TextTestResult;
  533. $suite->run($result);
  534. $result->report();
  535. }
  536. }
  537. ?>