RunTest.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. <?php
  2. /**
  3. * PEAR_RunTest
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * @category pear
  8. * @package PEAR
  9. * @author Tomas V.V.Cox <cox@idecnet.com>
  10. * @author Greg Beaver <cellog@php.net>
  11. * @copyright 1997-2009 The Authors
  12. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  13. * @link http://pear.php.net/package/PEAR
  14. * @since File available since Release 1.3.3
  15. */
  16. /**
  17. * for error handling
  18. */
  19. require_once 'PEAR.php';
  20. require_once 'PEAR/Config.php';
  21. define('DETAILED', 1);
  22. putenv("PHP_PEAR_RUNTESTS=1");
  23. /**
  24. * Simplified version of PHP's test suite
  25. *
  26. * Try it with:
  27. *
  28. * $ php -r 'include "../PEAR/RunTest.php"; $t=new PEAR_RunTest; $o=$t->run("./pear_system.phpt");print_r($o);'
  29. *
  30. *
  31. * @category pear
  32. * @package PEAR
  33. * @author Tomas V.V.Cox <cox@idecnet.com>
  34. * @author Greg Beaver <cellog@php.net>
  35. * @copyright 1997-2009 The Authors
  36. * @license http://opensource.org/licenses/bsd-license.php New BSD License
  37. * @version Release: 1.10.10
  38. * @link http://pear.php.net/package/PEAR
  39. * @since Class available since Release 1.3.3
  40. */
  41. class PEAR_RunTest
  42. {
  43. var $_headers = array();
  44. var $_logger;
  45. var $_options;
  46. var $_php;
  47. var $tests_count;
  48. var $xdebug_loaded;
  49. /**
  50. * Saved value of php executable, used to reset $_php when we
  51. * have a test that uses cgi
  52. *
  53. * @var unknown_type
  54. */
  55. var $_savephp;
  56. var $ini_overwrites = array(
  57. 'output_handler=',
  58. 'open_basedir=',
  59. 'disable_functions=',
  60. 'output_buffering=Off',
  61. 'display_errors=1',
  62. 'log_errors=0',
  63. 'html_errors=0',
  64. 'report_memleaks=0',
  65. 'report_zend_debug=0',
  66. 'docref_root=',
  67. 'docref_ext=.html',
  68. 'error_prepend_string=',
  69. 'error_append_string=',
  70. 'auto_prepend_file=',
  71. 'auto_append_file=',
  72. 'xdebug.default_enable=0',
  73. 'allow_url_fopen=1',
  74. );
  75. /**
  76. * An object that supports the PEAR_Common->log() signature, or null
  77. * @param PEAR_Common|null
  78. */
  79. function __construct($logger = null, $options = array())
  80. {
  81. if (!defined('E_DEPRECATED')) {
  82. define('E_DEPRECATED', 0);
  83. }
  84. if (!defined('E_STRICT')) {
  85. define('E_STRICT', 0);
  86. }
  87. $this->ini_overwrites[] = 'error_reporting=' . (E_ALL & ~(E_DEPRECATED | E_STRICT));
  88. if (is_null($logger)) {
  89. require_once 'PEAR/Common.php';
  90. $logger = new PEAR_Common;
  91. }
  92. $this->_logger = $logger;
  93. $this->_options = $options;
  94. $conf = &PEAR_Config::singleton();
  95. $this->_php = $conf->get('php_bin');
  96. }
  97. /**
  98. * Taken from php-src/run-tests.php
  99. *
  100. * @param string $commandline command name
  101. * @param array $env
  102. * @param string $stdin standard input to pass to the command
  103. * @return unknown
  104. */
  105. function system_with_timeout($commandline, $env = null, $stdin = null)
  106. {
  107. $data = '';
  108. $proc = proc_open($commandline, array(
  109. 0 => array('pipe', 'r'),
  110. 1 => array('pipe', 'w'),
  111. 2 => array('pipe', 'w')
  112. ), $pipes, null, $env, array('suppress_errors' => true));
  113. if (!$proc) {
  114. return false;
  115. }
  116. if (is_string($stdin)) {
  117. fwrite($pipes[0], $stdin);
  118. }
  119. fclose($pipes[0]);
  120. while (true) {
  121. /* hide errors from interrupted syscalls */
  122. $r = $pipes;
  123. $e = $w = null;
  124. $n = @stream_select($r, $w, $e, 60);
  125. if ($n === 0) {
  126. /* timed out */
  127. $data .= "\n ** ERROR: process timed out **\n";
  128. proc_terminate($proc);
  129. return array(1234567890, $data);
  130. } else if ($n > 0) {
  131. $line = fread($pipes[1], 8192);
  132. if (strlen($line) == 0) {
  133. /* EOF */
  134. break;
  135. }
  136. $data .= $line;
  137. }
  138. }
  139. if (function_exists('proc_get_status')) {
  140. $stat = proc_get_status($proc);
  141. if ($stat['signaled']) {
  142. $data .= "\nTermsig=".$stat['stopsig'];
  143. }
  144. }
  145. $code = proc_close($proc);
  146. if (function_exists('proc_get_status')) {
  147. $code = $stat['exitcode'];
  148. }
  149. return array($code, $data);
  150. }
  151. /**
  152. * Turns a PHP INI string into an array
  153. *
  154. * Turns -d "include_path=/foo/bar" into this:
  155. * array(
  156. * 'include_path' => array(
  157. * 'operator' => '-d',
  158. * 'value' => '/foo/bar',
  159. * )
  160. * )
  161. * Works both with quotes and without
  162. *
  163. * @param string an PHP INI string, -d "include_path=/foo/bar"
  164. * @return array
  165. */
  166. function iniString2array($ini_string)
  167. {
  168. if (!$ini_string) {
  169. return array();
  170. }
  171. $split = preg_split('/[\s]|=/', $ini_string, -1, PREG_SPLIT_NO_EMPTY);
  172. $key = $split[1][0] == '"' ? substr($split[1], 1) : $split[1];
  173. $value = $split[2][strlen($split[2]) - 1] == '"' ? substr($split[2], 0, -1) : $split[2];
  174. // FIXME review if this is really the struct to go with
  175. $array = array($key => array('operator' => $split[0], 'value' => $value));
  176. return $array;
  177. }
  178. function settings2array($settings, $ini_settings)
  179. {
  180. foreach ($settings as $setting) {
  181. if (strpos($setting, '=') !== false) {
  182. $setting = explode('=', $setting, 2);
  183. $name = trim(strtolower($setting[0]));
  184. $value = trim($setting[1]);
  185. $ini_settings[$name] = $value;
  186. }
  187. }
  188. return $ini_settings;
  189. }
  190. function settings2params($ini_settings)
  191. {
  192. $settings = '';
  193. foreach ($ini_settings as $name => $value) {
  194. if (is_array($value)) {
  195. $operator = $value['operator'];
  196. $value = $value['value'];
  197. } else {
  198. $operator = '-d';
  199. }
  200. $value = addslashes($value);
  201. $settings .= " $operator \"$name=$value\"";
  202. }
  203. return $settings;
  204. }
  205. function _preparePhpBin($php, $file, $ini_settings)
  206. {
  207. $file = escapeshellarg($file);
  208. $cmd = $php . $ini_settings . ' -f ' . $file;
  209. return $cmd;
  210. }
  211. function runPHPUnit($file, $ini_settings = '')
  212. {
  213. if (!file_exists($file) && file_exists(getcwd() . DIRECTORY_SEPARATOR . $file)) {
  214. $file = realpath(getcwd() . DIRECTORY_SEPARATOR . $file);
  215. } elseif (file_exists($file)) {
  216. $file = realpath($file);
  217. }
  218. $cmd = $this->_preparePhpBin($this->_php, $file, $ini_settings);
  219. if (isset($this->_logger)) {
  220. $this->_logger->log(2, 'Running command "' . $cmd . '"');
  221. }
  222. $savedir = getcwd(); // in case the test moves us around
  223. chdir(dirname($file));
  224. echo `$cmd`;
  225. chdir($savedir);
  226. return 'PASSED'; // we have no way of knowing this information so assume passing
  227. }
  228. /**
  229. * Runs an individual test case.
  230. *
  231. * @param string The filename of the test
  232. * @param array|string INI settings to be applied to the test run
  233. * @param integer Number what the current running test is of the
  234. * whole test suite being runned.
  235. *
  236. * @return string|object Returns PASSED, WARNED, FAILED depending on how the
  237. * test came out.
  238. * PEAR Error when the tester it self fails
  239. */
  240. function run($file, $ini_settings = array(), $test_number = 1)
  241. {
  242. $this->_restorePHPBinary();
  243. if (empty($this->_options['cgi'])) {
  244. // try to see if php-cgi is in the path
  245. $res = $this->system_with_timeout('php-cgi -v');
  246. if (false !== $res && !(is_array($res) && in_array($res[0], array(-1, 127)))) {
  247. $this->_options['cgi'] = 'php-cgi';
  248. }
  249. }
  250. if (1 < $len = strlen($this->tests_count)) {
  251. $test_number = str_pad($test_number, $len, ' ', STR_PAD_LEFT);
  252. $test_nr = "[$test_number/$this->tests_count] ";
  253. } else {
  254. $test_nr = '';
  255. }
  256. $file = realpath($file);
  257. $section_text = $this->_readFile($file);
  258. if (PEAR::isError($section_text)) {
  259. return $section_text;
  260. }
  261. if (isset($section_text['POST_RAW']) && isset($section_text['UPLOAD'])) {
  262. return PEAR::raiseError("Cannot contain both POST_RAW and UPLOAD in test file: $file");
  263. }
  264. $cwd = getcwd();
  265. $pass_options = '';
  266. if (!empty($this->_options['ini'])) {
  267. $pass_options = $this->_options['ini'];
  268. }
  269. if (is_string($ini_settings)) {
  270. $ini_settings = $this->iniString2array($ini_settings);
  271. }
  272. $ini_settings = $this->settings2array($this->ini_overwrites, $ini_settings);
  273. if ($section_text['INI']) {
  274. if (strpos($section_text['INI'], '{PWD}') !== false) {
  275. $section_text['INI'] = str_replace('{PWD}', dirname($file), $section_text['INI']);
  276. }
  277. $ini = preg_split( "/[\n\r]+/", $section_text['INI']);
  278. $ini_settings = $this->settings2array($ini, $ini_settings);
  279. }
  280. $ini_settings = $this->settings2params($ini_settings);
  281. $shortname = str_replace($cwd . DIRECTORY_SEPARATOR, '', $file);
  282. $tested = trim($section_text['TEST']);
  283. $tested.= !isset($this->_options['simple']) ? "[$shortname]" : ' ';
  284. if (!empty($section_text['POST']) || !empty($section_text['POST_RAW']) ||
  285. !empty($section_text['UPLOAD']) || !empty($section_text['GET']) ||
  286. !empty($section_text['COOKIE']) || !empty($section_text['EXPECTHEADERS'])) {
  287. if (empty($this->_options['cgi'])) {
  288. if (!isset($this->_options['quiet'])) {
  289. $this->_logger->log(0, "SKIP $test_nr$tested (reason: --cgi option needed for this test, type 'pear help run-tests')");
  290. }
  291. if (isset($this->_options['tapoutput'])) {
  292. return array('ok', ' # skip --cgi option needed for this test, "pear help run-tests" for info');
  293. }
  294. return 'SKIPPED';
  295. }
  296. $this->_savePHPBinary();
  297. $this->_php = $this->_options['cgi'];
  298. }
  299. $temp_dir = realpath(dirname($file));
  300. $main_file_name = basename($file, 'phpt');
  301. $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'diff';
  302. $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'log';
  303. $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'exp';
  304. $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'out';
  305. $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'mem';
  306. $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'php';
  307. $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'skip.php';
  308. $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'clean.php';
  309. $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('phpt.');
  310. // unlink old test results
  311. $this->_cleanupOldFiles($file);
  312. // Check if test should be skipped.
  313. $res = $this->_runSkipIf($section_text, $temp_skipif, $tested, $ini_settings);
  314. if ($res == 'SKIPPED' || count($res) != 2) {
  315. return $res;
  316. }
  317. $info = $res['info'];
  318. $warn = $res['warn'];
  319. // We've satisfied the preconditions - run the test!
  320. if (isset($this->_options['coverage']) && $this->xdebug_loaded) {
  321. $xdebug_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'xdebug';
  322. $text = "\n" . 'function coverage_shutdown() {' .
  323. "\n" . ' $xdebug = var_export(xdebug_get_code_coverage(), true);';
  324. if (!function_exists('file_put_contents')) {
  325. $text .= "\n" . ' $fh = fopen(\'' . $xdebug_file . '\', "wb");' .
  326. "\n" . ' if ($fh !== false) {' .
  327. "\n" . ' fwrite($fh, $xdebug);' .
  328. "\n" . ' fclose($fh);' .
  329. "\n" . ' }';
  330. } else {
  331. $text .= "\n" . ' file_put_contents(\'' . $xdebug_file . '\', $xdebug);';
  332. }
  333. // Workaround for http://pear.php.net/bugs/bug.php?id=17292
  334. $lines = explode("\n", $section_text['FILE']);
  335. $numLines = count($lines);
  336. $namespace = '';
  337. $coverage_shutdown = 'coverage_shutdown';
  338. if (
  339. substr($lines[0], 0, 2) == '<?' ||
  340. substr($lines[0], 0, 5) == '<?php'
  341. ) {
  342. unset($lines[0]);
  343. }
  344. for ($i = 0; $i < $numLines; $i++) {
  345. if (isset($lines[$i]) && substr($lines[$i], 0, 9) == 'namespace') {
  346. $namespace = substr($lines[$i], 10, -1);
  347. $coverage_shutdown = $namespace . '\\coverage_shutdown';
  348. $namespace = "namespace " . $namespace . ";\n";
  349. unset($lines[$i]);
  350. break;
  351. }
  352. }
  353. $text .= "\n xdebug_stop_code_coverage();" .
  354. "\n" . '} // end coverage_shutdown()' .
  355. "\n\n" . 'register_shutdown_function("' . $coverage_shutdown . '");';
  356. $text .= "\n" . 'xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);' . "\n";
  357. $this->save_text($temp_file, "<?php\n" . $namespace . $text . "\n" . implode("\n", $lines));
  358. } else {
  359. $this->save_text($temp_file, $section_text['FILE']);
  360. }
  361. $args = $section_text['ARGS'] ? ' -- '.$section_text['ARGS'] : '';
  362. $cmd = $this->_preparePhpBin($this->_php, $temp_file, $ini_settings);
  363. $cmd.= "$args 2>&1";
  364. if (isset($this->_logger)) {
  365. $this->_logger->log(2, 'Running command "' . $cmd . '"');
  366. }
  367. // Reset environment from any previous test.
  368. $env = $this->_resetEnv($section_text, $temp_file);
  369. $section_text = $this->_processUpload($section_text, $file);
  370. if (PEAR::isError($section_text)) {
  371. return $section_text;
  372. }
  373. if (array_key_exists('POST_RAW', $section_text) && !empty($section_text['POST_RAW'])) {
  374. $post = trim($section_text['POST_RAW']);
  375. $raw_lines = explode("\n", $post);
  376. $request = '';
  377. $started = false;
  378. foreach ($raw_lines as $i => $line) {
  379. if (empty($env['CONTENT_TYPE']) &&
  380. preg_match('/^Content-Type:(.*)/i', $line, $res)) {
  381. $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
  382. continue;
  383. }
  384. if ($started) {
  385. $request .= "\n";
  386. }
  387. $started = true;
  388. $request .= $line;
  389. }
  390. $env['CONTENT_LENGTH'] = strlen($request);
  391. $env['REQUEST_METHOD'] = 'POST';
  392. $this->save_text($tmp_post, $request);
  393. $cmd = "$this->_php$pass_options$ini_settings \"$temp_file\" 2>&1 < $tmp_post";
  394. } elseif (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
  395. $post = trim($section_text['POST']);
  396. $this->save_text($tmp_post, $post);
  397. $content_length = strlen($post);
  398. $env['REQUEST_METHOD'] = 'POST';
  399. $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  400. $env['CONTENT_LENGTH'] = $content_length;
  401. $cmd = "$this->_php$pass_options$ini_settings \"$temp_file\" 2>&1 < $tmp_post";
  402. } else {
  403. $env['REQUEST_METHOD'] = 'GET';
  404. $env['CONTENT_TYPE'] = '';
  405. $env['CONTENT_LENGTH'] = '';
  406. }
  407. if (OS_WINDOWS && isset($section_text['RETURNS'])) {
  408. ob_start();
  409. system($cmd, $return_value);
  410. $out = ob_get_contents();
  411. ob_end_clean();
  412. $section_text['RETURNS'] = (int) trim($section_text['RETURNS']);
  413. $returnfail = ($return_value != $section_text['RETURNS']);
  414. } else {
  415. $returnfail = false;
  416. $stdin = isset($section_text['STDIN']) ? $section_text['STDIN'] : null;
  417. $out = $this->system_with_timeout($cmd, $env, $stdin);
  418. $return_value = $out[0];
  419. $out = $out[1];
  420. }
  421. $output = preg_replace('/\r\n/', "\n", trim($out));
  422. if (isset($tmp_post) && realpath($tmp_post) && file_exists($tmp_post)) {
  423. @unlink(realpath($tmp_post));
  424. }
  425. chdir($cwd); // in case the test moves us around
  426. /* when using CGI, strip the headers from the output */
  427. $output = $this->_stripHeadersCGI($output);
  428. if (isset($section_text['EXPECTHEADERS'])) {
  429. $testheaders = $this->_processHeaders($section_text['EXPECTHEADERS']);
  430. $missing = array_diff_assoc($testheaders, $this->_headers);
  431. $changed = '';
  432. foreach ($missing as $header => $value) {
  433. if (isset($this->_headers[$header])) {
  434. $changed .= "-$header: $value\n+$header: ";
  435. $changed .= $this->_headers[$header];
  436. } else {
  437. $changed .= "-$header: $value\n";
  438. }
  439. }
  440. if ($missing) {
  441. // tack on failed headers to output:
  442. $output .= "\n====EXPECTHEADERS FAILURE====:\n$changed";
  443. }
  444. }
  445. $this->_testCleanup($section_text, $temp_clean);
  446. // Does the output match what is expected?
  447. do {
  448. if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
  449. if (isset($section_text['EXPECTF'])) {
  450. $wanted = trim($section_text['EXPECTF']);
  451. } else {
  452. $wanted = trim($section_text['EXPECTREGEX']);
  453. }
  454. $wanted_re = preg_replace('/\r\n/', "\n", $wanted);
  455. if (isset($section_text['EXPECTF'])) {
  456. $wanted_re = preg_quote($wanted_re, '/');
  457. // Stick to basics
  458. $wanted_re = str_replace("%s", ".+?", $wanted_re); //not greedy
  459. $wanted_re = str_replace("%i", "[+\-]?[0-9]+", $wanted_re);
  460. $wanted_re = str_replace("%d", "[0-9]+", $wanted_re);
  461. $wanted_re = str_replace("%x", "[0-9a-fA-F]+", $wanted_re);
  462. $wanted_re = str_replace("%f", "[+\-]?\.?[0-9]+\.?[0-9]*(E-?[0-9]+)?", $wanted_re);
  463. $wanted_re = str_replace("%c", ".", $wanted_re);
  464. // %f allows two points "-.0.0" but that is the best *simple* expression
  465. }
  466. /* DEBUG YOUR REGEX HERE
  467. var_dump($wanted_re);
  468. print(str_repeat('=', 80) . "\n");
  469. var_dump($output);
  470. */
  471. if (!$returnfail && preg_match("/^$wanted_re\$/s", $output)) {
  472. if (file_exists($temp_file)) {
  473. unlink($temp_file);
  474. }
  475. if (array_key_exists('FAIL', $section_text)) {
  476. break;
  477. }
  478. if (!isset($this->_options['quiet'])) {
  479. $this->_logger->log(0, "PASS $test_nr$tested$info");
  480. }
  481. if (isset($this->_options['tapoutput'])) {
  482. return array('ok', ' - ' . $tested);
  483. }
  484. return 'PASSED';
  485. }
  486. } else {
  487. if (isset($section_text['EXPECTFILE'])) {
  488. $f = $temp_dir . '/' . trim($section_text['EXPECTFILE']);
  489. if (!($fp = @fopen($f, 'rb'))) {
  490. return PEAR::raiseError('--EXPECTFILE-- section file ' .
  491. $f . ' not found');
  492. }
  493. fclose($fp);
  494. $section_text['EXPECT'] = file_get_contents($f);
  495. }
  496. if (isset($section_text['EXPECT'])) {
  497. $wanted = preg_replace('/\r\n/', "\n", trim($section_text['EXPECT']));
  498. } else {
  499. $wanted = '';
  500. }
  501. // compare and leave on success
  502. if (!$returnfail && 0 == strcmp($output, $wanted)) {
  503. if (file_exists($temp_file)) {
  504. unlink($temp_file);
  505. }
  506. if (array_key_exists('FAIL', $section_text)) {
  507. break;
  508. }
  509. if (!isset($this->_options['quiet'])) {
  510. $this->_logger->log(0, "PASS $test_nr$tested$info");
  511. }
  512. if (isset($this->_options['tapoutput'])) {
  513. return array('ok', ' - ' . $tested);
  514. }
  515. return 'PASSED';
  516. }
  517. }
  518. } while (false);
  519. if (array_key_exists('FAIL', $section_text)) {
  520. // we expect a particular failure
  521. // this is only used for testing PEAR_RunTest
  522. $expectf = isset($section_text['EXPECTF']) ? $wanted_re : null;
  523. $faildiff = $this->generate_diff($wanted, $output, null, $expectf);
  524. $faildiff = preg_replace('/\r/', '', $faildiff);
  525. $wanted = preg_replace('/\r/', '', trim($section_text['FAIL']));
  526. if ($faildiff == $wanted) {
  527. if (!isset($this->_options['quiet'])) {
  528. $this->_logger->log(0, "PASS $test_nr$tested$info");
  529. }
  530. if (isset($this->_options['tapoutput'])) {
  531. return array('ok', ' - ' . $tested);
  532. }
  533. return 'PASSED';
  534. }
  535. unset($section_text['EXPECTF']);
  536. $output = $faildiff;
  537. if (isset($section_text['RETURNS'])) {
  538. return PEAR::raiseError('Cannot have both RETURNS and FAIL in the same test: ' .
  539. $file);
  540. }
  541. }
  542. // Test failed so we need to report details.
  543. $txt = $warn ? 'WARN ' : 'FAIL ';
  544. $this->_logger->log(0, $txt . $test_nr . $tested . $info);
  545. // write .exp
  546. $res = $this->_writeLog($exp_filename, $wanted);
  547. if (PEAR::isError($res)) {
  548. return $res;
  549. }
  550. // write .out
  551. $res = $this->_writeLog($output_filename, $output);
  552. if (PEAR::isError($res)) {
  553. return $res;
  554. }
  555. // write .diff
  556. $returns = isset($section_text['RETURNS']) ?
  557. array(trim($section_text['RETURNS']), $return_value) : null;
  558. $expectf = isset($section_text['EXPECTF']) ? $wanted_re : null;
  559. $data = $this->generate_diff($wanted, $output, $returns, $expectf);
  560. $res = $this->_writeLog($diff_filename, $data);
  561. if (isset($this->_options['showdiff'])) {
  562. $this->_logger->log(0, "========DIFF========");
  563. $this->_logger->log(0, $data);
  564. $this->_logger->log(0, "========DONE========");
  565. }
  566. if (PEAR::isError($res)) {
  567. return $res;
  568. }
  569. // write .log
  570. $data = "
  571. ---- EXPECTED OUTPUT
  572. $wanted
  573. ---- ACTUAL OUTPUT
  574. $output
  575. ---- FAILED
  576. ";
  577. if ($returnfail) {
  578. $data .= "
  579. ---- EXPECTED RETURN
  580. $section_text[RETURNS]
  581. ---- ACTUAL RETURN
  582. $return_value
  583. ";
  584. }
  585. $res = $this->_writeLog($log_filename, $data);
  586. if (PEAR::isError($res)) {
  587. return $res;
  588. }
  589. if (isset($this->_options['tapoutput'])) {
  590. $wanted = explode("\n", $wanted);
  591. $wanted = "# Expected output:\n#\n#" . implode("\n#", $wanted);
  592. $output = explode("\n", $output);
  593. $output = "#\n#\n# Actual output:\n#\n#" . implode("\n#", $output);
  594. return array($wanted . $output . 'not ok', ' - ' . $tested);
  595. }
  596. return $warn ? 'WARNED' : 'FAILED';
  597. }
  598. function generate_diff($wanted, $output, $rvalue, $wanted_re)
  599. {
  600. $w = explode("\n", $wanted);
  601. $o = explode("\n", $output);
  602. $wr = explode("\n", $wanted_re);
  603. $w1 = array_diff_assoc($w, $o);
  604. $o1 = array_diff_assoc($o, $w);
  605. $o2 = $w2 = array();
  606. foreach ($w1 as $idx => $val) {
  607. if (!$wanted_re || !isset($wr[$idx]) || !isset($o1[$idx]) ||
  608. !preg_match('/^' . $wr[$idx] . '\\z/', $o1[$idx])) {
  609. $w2[sprintf("%03d<", $idx)] = sprintf("%03d- ", $idx + 1) . $val;
  610. }
  611. }
  612. foreach ($o1 as $idx => $val) {
  613. if (!$wanted_re || !isset($wr[$idx]) ||
  614. !preg_match('/^' . $wr[$idx] . '\\z/', $val)) {
  615. $o2[sprintf("%03d>", $idx)] = sprintf("%03d+ ", $idx + 1) . $val;
  616. }
  617. }
  618. $diff = array_merge($w2, $o2);
  619. ksort($diff);
  620. $extra = $rvalue ? "##EXPECTED: $rvalue[0]\r\n##RETURNED: $rvalue[1]" : '';
  621. return implode("\r\n", $diff) . $extra;
  622. }
  623. // Write the given text to a temporary file, and return the filename.
  624. function save_text($filename, $text)
  625. {
  626. if (!$fp = fopen($filename, 'w')) {
  627. return PEAR::raiseError("Cannot open file '" . $filename . "' (save_text)");
  628. }
  629. fwrite($fp, $text);
  630. fclose($fp);
  631. if (1 < DETAILED) echo "
  632. FILE $filename {{{
  633. $text
  634. }}}
  635. ";
  636. }
  637. function _cleanupOldFiles($file)
  638. {
  639. $temp_dir = realpath(dirname($file));
  640. $mainFileName = basename($file, 'phpt');
  641. $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'diff';
  642. $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'log';
  643. $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'exp';
  644. $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'out';
  645. $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'mem';
  646. $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'php';
  647. $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'skip.php';
  648. $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'clean.php';
  649. $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('phpt.');
  650. // unlink old test results
  651. @unlink($diff_filename);
  652. @unlink($log_filename);
  653. @unlink($exp_filename);
  654. @unlink($output_filename);
  655. @unlink($memcheck_filename);
  656. @unlink($temp_file);
  657. @unlink($temp_skipif);
  658. @unlink($tmp_post);
  659. @unlink($temp_clean);
  660. }
  661. function _runSkipIf($section_text, $temp_skipif, $tested, $ini_settings)
  662. {
  663. $info = '';
  664. $warn = false;
  665. if (array_key_exists('SKIPIF', $section_text) && trim($section_text['SKIPIF'])) {
  666. $this->save_text($temp_skipif, $section_text['SKIPIF']);
  667. $output = $this->system_with_timeout("$this->_php$ini_settings -f \"$temp_skipif\"");
  668. $output = $output[1];
  669. $loutput = ltrim($output);
  670. unlink($temp_skipif);
  671. if (!strncasecmp('skip', $loutput, 4)) {
  672. $skipreason = "SKIP $tested";
  673. if (preg_match('/^\s*skip\s*(.+)\s*/i', $output, $m)) {
  674. $skipreason .= '(reason: ' . $m[1] . ')';
  675. }
  676. if (!isset($this->_options['quiet'])) {
  677. $this->_logger->log(0, $skipreason);
  678. }
  679. if (isset($this->_options['tapoutput'])) {
  680. return array('ok', ' # skip ' . $reason);
  681. }
  682. return 'SKIPPED';
  683. }
  684. if (!strncasecmp('info', $loutput, 4)
  685. && preg_match('/^\s*info\s*(.+)\s*/i', $output, $m)) {
  686. $info = " (info: $m[1])";
  687. }
  688. if (!strncasecmp('warn', $loutput, 4)
  689. && preg_match('/^\s*warn\s*(.+)\s*/i', $output, $m)) {
  690. $warn = true; /* only if there is a reason */
  691. $info = " (warn: $m[1])";
  692. }
  693. }
  694. return array('warn' => $warn, 'info' => $info);
  695. }
  696. function _stripHeadersCGI($output)
  697. {
  698. $this->headers = array();
  699. if (!empty($this->_options['cgi']) &&
  700. $this->_php == $this->_options['cgi'] &&
  701. preg_match("/^(.*?)(?:\n\n(.*)|\\z)/s", $output, $match)) {
  702. $output = isset($match[2]) ? trim($match[2]) : '';
  703. $this->_headers = $this->_processHeaders($match[1]);
  704. }
  705. return $output;
  706. }
  707. /**
  708. * Return an array that can be used with array_diff() to compare headers
  709. *
  710. * @param string $text
  711. */
  712. function _processHeaders($text)
  713. {
  714. $headers = array();
  715. $rh = preg_split("/[\n\r]+/", $text);
  716. foreach ($rh as $line) {
  717. if (strpos($line, ':')!== false) {
  718. $line = explode(':', $line, 2);
  719. $headers[trim($line[0])] = trim($line[1]);
  720. }
  721. }
  722. return $headers;
  723. }
  724. function _readFile($file)
  725. {
  726. // Load the sections of the test file.
  727. $section_text = array(
  728. 'TEST' => '(unnamed test)',
  729. 'SKIPIF' => '',
  730. 'GET' => '',
  731. 'COOKIE' => '',
  732. 'POST' => '',
  733. 'ARGS' => '',
  734. 'INI' => '',
  735. 'CLEAN' => '',
  736. );
  737. if (!is_file($file) || !$fp = fopen($file, "r")) {
  738. return PEAR::raiseError("Cannot open test file: $file");
  739. }
  740. $section = '';
  741. while (!feof($fp)) {
  742. $line = fgets($fp);
  743. // Match the beginning of a section.
  744. if (preg_match('/^--([_A-Z]+)--/', $line, $r)) {
  745. $section = $r[1];
  746. $section_text[$section] = '';
  747. continue;
  748. } elseif (empty($section)) {
  749. fclose($fp);
  750. return PEAR::raiseError("Invalid sections formats in test file: $file");
  751. }
  752. // Add to the section text.
  753. $section_text[$section] .= $line;
  754. }
  755. fclose($fp);
  756. return $section_text;
  757. }
  758. function _writeLog($logname, $data)
  759. {
  760. if (!$log = fopen($logname, 'w')) {
  761. return PEAR::raiseError("Cannot create test log - $logname");
  762. }
  763. fwrite($log, $data);
  764. fclose($log);
  765. }
  766. function _resetEnv($section_text, $temp_file)
  767. {
  768. $env = $_ENV;
  769. $env['REDIRECT_STATUS'] = '';
  770. $env['QUERY_STRING'] = '';
  771. $env['PATH_TRANSLATED'] = '';
  772. $env['SCRIPT_FILENAME'] = '';
  773. $env['REQUEST_METHOD'] = '';
  774. $env['CONTENT_TYPE'] = '';
  775. $env['CONTENT_LENGTH'] = '';
  776. if (!empty($section_text['ENV'])) {
  777. if (strpos($section_text['ENV'], '{PWD}') !== false) {
  778. $section_text['ENV'] = str_replace('{PWD}', dirname($temp_file), $section_text['ENV']);
  779. }
  780. foreach (explode("\n", trim($section_text['ENV'])) as $e) {
  781. $e = explode('=', trim($e), 2);
  782. if (!empty($e[0]) && isset($e[1])) {
  783. $env[$e[0]] = $e[1];
  784. }
  785. }
  786. }
  787. if (array_key_exists('GET', $section_text)) {
  788. $env['QUERY_STRING'] = trim($section_text['GET']);
  789. } else {
  790. $env['QUERY_STRING'] = '';
  791. }
  792. if (array_key_exists('COOKIE', $section_text)) {
  793. $env['HTTP_COOKIE'] = trim($section_text['COOKIE']);
  794. } else {
  795. $env['HTTP_COOKIE'] = '';
  796. }
  797. $env['REDIRECT_STATUS'] = '1';
  798. $env['PATH_TRANSLATED'] = $temp_file;
  799. $env['SCRIPT_FILENAME'] = $temp_file;
  800. return $env;
  801. }
  802. function _processUpload($section_text, $file)
  803. {
  804. if (array_key_exists('UPLOAD', $section_text) && !empty($section_text['UPLOAD'])) {
  805. $upload_files = trim($section_text['UPLOAD']);
  806. $upload_files = explode("\n", $upload_files);
  807. $request = "Content-Type: multipart/form-data; boundary=---------------------------20896060251896012921717172737\n" .
  808. "-----------------------------20896060251896012921717172737\n";
  809. foreach ($upload_files as $fileinfo) {
  810. $fileinfo = explode('=', $fileinfo);
  811. if (count($fileinfo) != 2) {
  812. return PEAR::raiseError("Invalid UPLOAD section in test file: $file");
  813. }
  814. if (!realpath(dirname($file) . '/' . $fileinfo[1])) {
  815. return PEAR::raiseError("File for upload does not exist: $fileinfo[1] " .
  816. "in test file: $file");
  817. }
  818. $file_contents = file_get_contents(dirname($file) . '/' . $fileinfo[1]);
  819. $fileinfo[1] = basename($fileinfo[1]);
  820. $request .= "Content-Disposition: form-data; name=\"$fileinfo[0]\"; filename=\"$fileinfo[1]\"\n";
  821. $request .= "Content-Type: text/plain\n\n";
  822. $request .= $file_contents . "\n" .
  823. "-----------------------------20896060251896012921717172737\n";
  824. }
  825. if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
  826. // encode POST raw
  827. $post = trim($section_text['POST']);
  828. $post = explode('&', $post);
  829. foreach ($post as $i => $post_info) {
  830. $post_info = explode('=', $post_info);
  831. if (count($post_info) != 2) {
  832. return PEAR::raiseError("Invalid POST data in test file: $file");
  833. }
  834. $post_info[0] = rawurldecode($post_info[0]);
  835. $post_info[1] = rawurldecode($post_info[1]);
  836. $post[$i] = $post_info;
  837. }
  838. foreach ($post as $post_info) {
  839. $request .= "Content-Disposition: form-data; name=\"$post_info[0]\"\n\n";
  840. $request .= $post_info[1] . "\n" .
  841. "-----------------------------20896060251896012921717172737\n";
  842. }
  843. unset($section_text['POST']);
  844. }
  845. $section_text['POST_RAW'] = $request;
  846. }
  847. return $section_text;
  848. }
  849. function _testCleanup($section_text, $temp_clean)
  850. {
  851. if ($section_text['CLEAN']) {
  852. $this->_restorePHPBinary();
  853. // perform test cleanup
  854. $this->save_text($temp_clean, $section_text['CLEAN']);
  855. $output = $this->system_with_timeout("$this->_php $temp_clean 2>&1");
  856. if (strlen($output[1])) {
  857. echo "BORKED --CLEAN-- section! output:\n", $output[1];
  858. }
  859. if (file_exists($temp_clean)) {
  860. unlink($temp_clean);
  861. }
  862. }
  863. }
  864. function _savePHPBinary()
  865. {
  866. $this->_savephp = $this->_php;
  867. }
  868. function _restorePHPBinary()
  869. {
  870. if (isset($this->_savephp))
  871. {
  872. $this->_php = $this->_savephp;
  873. unset($this->_savephp);
  874. }
  875. }
  876. }