PageRenderTime 534ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/php/PEAR/RunTest.php

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