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
21 require_once 'PEAR.php';
22 require_once 'PEAR/Config.php';
24 define('DETAILED', 1);
25 putenv("PHP_PEAR_RUNTESTS=1");
28 * Simplified version of PHP's test suite
32 * $ php -r 'include "../PEAR/RunTest.php"; $t=new PEAR_RunTest; $o=$t->run("./pear_system.phpt");print_r($o);'
37 * @author Tomas V.V.Cox <cox@idecnet.com>
38 * @author Greg Beaver <cellog@php.net>
39 * @copyright 1997-2009 The Authors
40 * @license http://opensource.org/licenses/bsd-license.php New BSD License
41 * @version Release: 1.9.4
42 * @link http://pear.php.net/package/PEAR
43 * @since Class available since Release 1.3.3
47 var $_headers = array();
54 * Saved value of php executable, used to reset $_php when we
55 * have a test that uses cgi
60 var $ini_overwrites = array(
65 'output_buffering=Off',
71 'report_zend_debug=0',
74 'error_prepend_string=',
75 'error_append_string=',
78 'magic_quotes_runtime=0',
79 'xdebug.default_enable=0',
84 * An object that supports the PEAR_Common->log() signature, or null
85 * @param PEAR_Common|null
87 function PEAR_RunTest($logger = null, $options = array())
89 if (!defined('E_DEPRECATED')) {
90 define('E_DEPRECATED', 0);
92 if (!defined('E_STRICT')) {
93 define('E_STRICT', 0);
95 $this->ini_overwrites[] = 'error_reporting=' . (E_ALL & ~(E_DEPRECATED | E_STRICT));
96 if (is_null($logger)) {
97 require_once 'PEAR/Common.php';
98 $logger = new PEAR_Common;
100 $this->_logger = $logger;
101 $this->_options = $options;
103 $conf = &PEAR_Config::singleton();
104 $this->_php = $conf->get('php_bin');
108 * Taken from php-src/run-tests.php
110 * @param string $commandline command name
112 * @param string $stdin standard input to pass to the command
115 function system_with_timeout($commandline, $env = null, $stdin = null)
118 if (version_compare(phpversion(), '5.0.0', '<')) {
119 $proc = proc_open($commandline, array(
120 0 => array('pipe', 'r'),
121 1 => array('pipe', 'w'),
122 2 => array('pipe', 'w')
125 $proc = proc_open($commandline, array(
126 0 => array('pipe', 'r'),
127 1 => array('pipe', 'w'),
128 2 => array('pipe', 'w')
129 ), $pipes, null, $env, array('suppress_errors' => true));
136 if (is_string($stdin)) {
137 fwrite($pipes[0], $stdin);
142 /* hide errors from interrupted syscalls */
145 $n = @stream_select($r, $w, $e, 60);
149 $data .= "\n ** ERROR: process timed out **\n";
150 proc_terminate($proc);
151 return array(1234567890, $data);
153 $line = fread($pipes[1], 8192);
154 if (strlen($line) == 0) {
161 if (function_exists('proc_get_status')) {
162 $stat = proc_get_status($proc);
163 if ($stat['signaled']) {
164 $data .= "\nTermsig=".$stat['stopsig'];
167 $code = proc_close($proc);
168 if (function_exists('proc_get_status')) {
169 $code = $stat['exitcode'];
171 return array($code, $data);
175 * Turns a PHP INI string into an array
177 * Turns -d "include_path=/foo/bar" into this:
179 * 'include_path' => array(
180 * 'operator' => '-d',
181 * 'value' => '/foo/bar',
184 * Works both with quotes and without
186 * @param string an PHP INI string, -d "include_path=/foo/bar"
189 function iniString2array($ini_string)
194 $split = preg_split('/[\s]|=/', $ini_string, -1, PREG_SPLIT_NO_EMPTY);
195 $key = $split[1][0] == '"' ? substr($split[1], 1) : $split[1];
196 $value = $split[2][strlen($split[2]) - 1] == '"' ? substr($split[2], 0, -1) : $split[2];
197 // FIXME review if this is really the struct to go with
198 $array = array($key => array('operator' => $split[0], 'value' => $value));
202 function settings2array($settings, $ini_settings)
204 foreach ($settings as $setting) {
205 if (strpos($setting, '=') !== false) {
206 $setting = explode('=', $setting, 2);
207 $name = trim(strtolower($setting[0]));
208 $value = trim($setting[1]);
209 $ini_settings[$name] = $value;
212 return $ini_settings;
215 function settings2params($ini_settings)
218 foreach ($ini_settings as $name => $value) {
219 if (is_array($value)) {
220 $operator = $value['operator'];
221 $value = $value['value'];
225 $value = addslashes($value);
226 $settings .= " $operator \"$name=$value\"";
231 function _preparePhpBin($php, $file, $ini_settings)
233 $file = escapeshellarg($file);
234 // This was fixed in php 5.3 and is not needed after that
235 if (OS_WINDOWS && version_compare(PHP_VERSION, '5.3', '<')) {
236 $cmd = '"'.escapeshellarg($php).' '.$ini_settings.' -f ' . $file .'"';
238 $cmd = $php . $ini_settings . ' -f ' . $file;
244 function runPHPUnit($file, $ini_settings = '')
246 if (!file_exists($file) && file_exists(getcwd() . DIRECTORY_SEPARATOR . $file)) {
247 $file = realpath(getcwd() . DIRECTORY_SEPARATOR . $file);
248 } elseif (file_exists($file)) {
249 $file = realpath($file);
252 $cmd = $this->_preparePhpBin($this->_php, $file, $ini_settings);
253 if (isset($this->_logger)) {
254 $this->_logger->log(2, 'Running command "' . $cmd . '"');
257 $savedir = getcwd(); // in case the test moves us around
258 chdir(dirname($file));
261 return 'PASSED'; // we have no way of knowing this information so assume passing
265 * Runs an individual test case.
267 * @param string The filename of the test
268 * @param array|string INI settings to be applied to the test run
269 * @param integer Number what the current running test is of the
270 * whole test suite being runned.
272 * @return string|object Returns PASSED, WARNED, FAILED depending on how the
274 * PEAR Error when the tester it self fails
276 function run($file, $ini_settings = array(), $test_number = 1)
278 if (isset($this->_savephp)) {
279 $this->_php = $this->_savephp;
280 unset($this->_savephp);
282 if (empty($this->_options['cgi'])) {
283 // try to see if php-cgi is in the path
284 $res = $this->system_with_timeout('php-cgi -v');
285 if (false !== $res && !(is_array($res) && in_array($res[0], array(-1, 127)))) {
286 $this->_options['cgi'] = 'php-cgi';
289 if (1 < $len = strlen($this->tests_count)) {
290 $test_number = str_pad($test_number, $len, ' ', STR_PAD_LEFT);
291 $test_nr = "[$test_number/$this->tests_count] ";
296 $file = realpath($file);
297 $section_text = $this->_readFile($file);
298 if (PEAR::isError($section_text)) {
299 return $section_text;
302 if (isset($section_text['POST_RAW']) && isset($section_text['UPLOAD'])) {
303 return PEAR::raiseError("Cannot contain both POST_RAW and UPLOAD in test file: $file");
309 if (!empty($this->_options['ini'])) {
310 $pass_options = $this->_options['ini'];
313 if (is_string($ini_settings)) {
314 $ini_settings = $this->iniString2array($ini_settings);
317 $ini_settings = $this->settings2array($this->ini_overwrites, $ini_settings);
318 if ($section_text['INI']) {
319 if (strpos($section_text['INI'], '{PWD}') !== false) {
320 $section_text['INI'] = str_replace('{PWD}', dirname($file), $section_text['INI']);
322 $ini = preg_split( "/[\n\r]+/", $section_text['INI']);
323 $ini_settings = $this->settings2array($ini, $ini_settings);
325 $ini_settings = $this->settings2params($ini_settings);
326 $shortname = str_replace($cwd . DIRECTORY_SEPARATOR, '', $file);
328 $tested = trim($section_text['TEST']);
329 $tested.= !isset($this->_options['simple']) ? "[$shortname]" : ' ';
331 if (!empty($section_text['POST']) || !empty($section_text['POST_RAW']) ||
332 !empty($section_text['UPLOAD']) || !empty($section_text['GET']) ||
333 !empty($section_text['COOKIE']) || !empty($section_text['EXPECTHEADERS'])) {
334 if (empty($this->_options['cgi'])) {
335 if (!isset($this->_options['quiet'])) {
336 $this->_logger->log(0, "SKIP $test_nr$tested (reason: --cgi option needed for this test, type 'pear help run-tests')");
338 if (isset($this->_options['tapoutput'])) {
339 return array('ok', ' # skip --cgi option needed for this test, "pear help run-tests" for info');
343 $this->_savephp = $this->_php;
344 $this->_php = $this->_options['cgi'];
347 $temp_dir = realpath(dirname($file));
348 $main_file_name = basename($file, 'phpt');
349 $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'diff';
350 $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'log';
351 $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'exp';
352 $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'out';
353 $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'mem';
354 $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'php';
355 $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'skip.php';
356 $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name.'clean.php';
357 $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('phpt.');
359 // unlink old test results
360 $this->_cleanupOldFiles($file);
362 // Check if test should be skipped.
363 $res = $this->_runSkipIf($section_text, $temp_skipif, $tested, $ini_settings);
364 if (count($res) != 2) {
367 $info = $res['info'];
368 $warn = $res['warn'];
370 // We've satisfied the preconditions - run the test!
371 if (isset($this->_options['coverage']) && $this->xdebug_loaded) {
372 $xdebug_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'xdebug';
373 $text = "\n" . 'function coverage_shutdown() {' .
374 "\n" . ' $xdebug = var_export(xdebug_get_code_coverage(), true);';
375 if (!function_exists('file_put_contents')) {
376 $text .= "\n" . ' $fh = fopen(\'' . $xdebug_file . '\', "wb");' .
377 "\n" . ' if ($fh !== false) {' .
378 "\n" . ' fwrite($fh, $xdebug);' .
379 "\n" . ' fclose($fh);' .
382 $text .= "\n" . ' file_put_contents(\'' . $xdebug_file . '\', $xdebug);';
385 // Workaround for http://pear.php.net/bugs/bug.php?id=17292
386 $lines = explode("\n", $section_text['FILE']);
387 $numLines = count($lines);
389 $coverage_shutdown = 'coverage_shutdown';
392 substr($lines[0], 0, 2) == '<?' ||
393 substr($lines[0], 0, 5) == '<?php'
399 for ($i = 0; $i < $numLines; $i++) {
400 if (isset($lines[$i]) && substr($lines[$i], 0, 9) == 'namespace') {
401 $namespace = substr($lines[$i], 10, -1);
402 $coverage_shutdown = $namespace . '\\coverage_shutdown';
403 $namespace = "namespace " . $namespace . ";\n";
410 $text .= "\n xdebug_stop_code_coverage();" .
411 "\n" . '} // end coverage_shutdown()' .
412 "\n\n" . 'register_shutdown_function("' . $coverage_shutdown . '");';
413 $text .= "\n" . 'xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);' . "\n";
415 $this->save_text($temp_file, "<?php\n" . $namespace . $text . "\n" . implode("\n", $lines));
417 $this->save_text($temp_file, $section_text['FILE']);
420 $args = $section_text['ARGS'] ? ' -- '.$section_text['ARGS'] : '';
421 $cmd = $this->_preparePhpBin($this->_php, $temp_file, $ini_settings);
423 if (isset($this->_logger)) {
424 $this->_logger->log(2, 'Running command "' . $cmd . '"');
427 // Reset environment from any previous test.
428 $env = $this->_resetEnv($section_text, $temp_file);
430 $section_text = $this->_processUpload($section_text, $file);
431 if (PEAR::isError($section_text)) {
432 return $section_text;
435 if (array_key_exists('POST_RAW', $section_text) && !empty($section_text['POST_RAW'])) {
436 $post = trim($section_text['POST_RAW']);
437 $raw_lines = explode("\n", $post);
441 foreach ($raw_lines as $i => $line) {
442 if (empty($env['CONTENT_TYPE']) &&
443 preg_match('/^Content-Type:(.*)/i', $line, $res)) {
444 $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
454 $env['CONTENT_LENGTH'] = strlen($request);
455 $env['REQUEST_METHOD'] = 'POST';
457 $this->save_text($tmp_post, $request);
458 $cmd = "$this->_php$pass_options$ini_settings \"$temp_file\" 2>&1 < $tmp_post";
459 } elseif (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
460 $post = trim($section_text['POST']);
461 $this->save_text($tmp_post, $post);
462 $content_length = strlen($post);
464 $env['REQUEST_METHOD'] = 'POST';
465 $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
466 $env['CONTENT_LENGTH'] = $content_length;
468 $cmd = "$this->_php$pass_options$ini_settings \"$temp_file\" 2>&1 < $tmp_post";
470 $env['REQUEST_METHOD'] = 'GET';
471 $env['CONTENT_TYPE'] = '';
472 $env['CONTENT_LENGTH'] = '';
475 if (OS_WINDOWS && isset($section_text['RETURNS'])) {
477 system($cmd, $return_value);
478 $out = ob_get_contents();
480 $section_text['RETURNS'] = (int) trim($section_text['RETURNS']);
481 $returnfail = ($return_value != $section_text['RETURNS']);
484 $stdin = isset($section_text['STDIN']) ? $section_text['STDIN'] : null;
485 $out = $this->system_with_timeout($cmd, $env, $stdin);
486 $return_value = $out[0];
490 $output = preg_replace('/\r\n/', "\n", trim($out));
492 if (isset($tmp_post) && realpath($tmp_post) && file_exists($tmp_post)) {
493 @unlink(realpath($tmp_post));
495 chdir($cwd); // in case the test moves us around
497 $this->_testCleanup($section_text, $temp_clean);
499 /* when using CGI, strip the headers from the output */
500 $output = $this->_stripHeadersCGI($output);
502 if (isset($section_text['EXPECTHEADERS'])) {
503 $testheaders = $this->_processHeaders($section_text['EXPECTHEADERS']);
504 $missing = array_diff_assoc($testheaders, $this->_headers);
506 foreach ($missing as $header => $value) {
507 if (isset($this->_headers[$header])) {
508 $changed .= "-$header: $value\n+$header: ";
509 $changed .= $this->_headers[$header];
511 $changed .= "-$header: $value\n";
515 // tack on failed headers to output:
516 $output .= "\n====EXPECTHEADERS FAILURE====:\n$changed";
519 // Does the output match what is expected?
521 if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
522 if (isset($section_text['EXPECTF'])) {
523 $wanted = trim($section_text['EXPECTF']);
525 $wanted = trim($section_text['EXPECTREGEX']);
527 $wanted_re = preg_replace('/\r\n/', "\n", $wanted);
528 if (isset($section_text['EXPECTF'])) {
529 $wanted_re = preg_quote($wanted_re, '/');
531 $wanted_re = str_replace("%s", ".+?", $wanted_re); //not greedy
532 $wanted_re = str_replace("%i", "[+\-]?[0-9]+", $wanted_re);
533 $wanted_re = str_replace("%d", "[0-9]+", $wanted_re);
534 $wanted_re = str_replace("%x", "[0-9a-fA-F]+", $wanted_re);
535 $wanted_re = str_replace("%f", "[+\-]?\.?[0-9]+\.?[0-9]*(E-?[0-9]+)?", $wanted_re);
536 $wanted_re = str_replace("%c", ".", $wanted_re);
537 // %f allows two points "-.0.0" but that is the best *simple* expression
540 /* DEBUG YOUR REGEX HERE
541 var_dump($wanted_re);
542 print(str_repeat('=', 80) . "\n");
545 if (!$returnfail && preg_match("/^$wanted_re\$/s", $output)) {
546 if (file_exists($temp_file)) {
549 if (array_key_exists('FAIL', $section_text)) {
552 if (!isset($this->_options['quiet'])) {
553 $this->_logger->log(0, "PASS $test_nr$tested$info");
555 if (isset($this->_options['tapoutput'])) {
556 return array('ok', ' - ' . $tested);
561 if (isset($section_text['EXPECTFILE'])) {
562 $f = $temp_dir . '/' . trim($section_text['EXPECTFILE']);
563 if (!($fp = @fopen($f, 'rb'))) {
564 return PEAR::raiseError('--EXPECTFILE-- section file ' .
568 $section_text['EXPECT'] = file_get_contents($f);
571 if (isset($section_text['EXPECT'])) {
572 $wanted = preg_replace('/\r\n/', "\n", trim($section_text['EXPECT']));
577 // compare and leave on success
578 if (!$returnfail && 0 == strcmp($output, $wanted)) {
579 if (file_exists($temp_file)) {
582 if (array_key_exists('FAIL', $section_text)) {
585 if (!isset($this->_options['quiet'])) {
586 $this->_logger->log(0, "PASS $test_nr$tested$info");
588 if (isset($this->_options['tapoutput'])) {
589 return array('ok', ' - ' . $tested);
596 if (array_key_exists('FAIL', $section_text)) {
597 // we expect a particular failure
598 // this is only used for testing PEAR_RunTest
599 $expectf = isset($section_text['EXPECTF']) ? $wanted_re : null;
600 $faildiff = $this->generate_diff($wanted, $output, null, $expectf);
601 $faildiff = preg_replace('/\r/', '', $faildiff);
602 $wanted = preg_replace('/\r/', '', trim($section_text['FAIL']));
603 if ($faildiff == $wanted) {
604 if (!isset($this->_options['quiet'])) {
605 $this->_logger->log(0, "PASS $test_nr$tested$info");
607 if (isset($this->_options['tapoutput'])) {
608 return array('ok', ' - ' . $tested);
612 unset($section_text['EXPECTF']);
614 if (isset($section_text['RETURNS'])) {
615 return PEAR::raiseError('Cannot have both RETURNS and FAIL in the same test: ' .
620 // Test failed so we need to report details.
621 $txt = $warn ? 'WARN ' : 'FAIL ';
622 $this->_logger->log(0, $txt . $test_nr . $tested . $info);
625 $res = $this->_writeLog($exp_filename, $wanted);
626 if (PEAR::isError($res)) {
631 $res = $this->_writeLog($output_filename, $output);
632 if (PEAR::isError($res)) {
637 $returns = isset($section_text['RETURNS']) ?
638 array(trim($section_text['RETURNS']), $return_value) : null;
639 $expectf = isset($section_text['EXPECTF']) ? $wanted_re : null;
640 $data = $this->generate_diff($wanted, $output, $returns, $expectf);
641 $res = $this->_writeLog($diff_filename, $data);
642 if (PEAR::isError($res)) {
658 $section_text[RETURNS]
664 $res = $this->_writeLog($log_filename, $data);
665 if (PEAR::isError($res)) {
669 if (isset($this->_options['tapoutput'])) {
670 $wanted = explode("\n", $wanted);
671 $wanted = "# Expected output:\n#\n#" . implode("\n#", $wanted);
672 $output = explode("\n", $output);
673 $output = "#\n#\n# Actual output:\n#\n#" . implode("\n#", $output);
674 return array($wanted . $output . 'not ok', ' - ' . $tested);
676 return $warn ? 'WARNED' : 'FAILED';
679 function generate_diff($wanted, $output, $rvalue, $wanted_re)
681 $w = explode("\n", $wanted);
682 $o = explode("\n", $output);
683 $wr = explode("\n", $wanted_re);
684 $w1 = array_diff_assoc($w, $o);
685 $o1 = array_diff_assoc($o, $w);
687 foreach ($w1 as $idx => $val) {
688 if (!$wanted_re || !isset($wr[$idx]) || !isset($o1[$idx]) ||
689 !preg_match('/^' . $wr[$idx] . '\\z/', $o1[$idx])) {
690 $w2[sprintf("%03d<", $idx)] = sprintf("%03d- ", $idx + 1) . $val;
693 foreach ($o1 as $idx => $val) {
694 if (!$wanted_re || !isset($wr[$idx]) ||
695 !preg_match('/^' . $wr[$idx] . '\\z/', $val)) {
696 $o2[sprintf("%03d>", $idx)] = sprintf("%03d+ ", $idx + 1) . $val;
699 $diff = array_merge($w2, $o2);
701 $extra = $rvalue ? "##EXPECTED: $rvalue[0]\r\n##RETURNED: $rvalue[1]" : '';
702 return implode("\r\n", $diff) . $extra;
705 // Write the given text to a temporary file, and return the filename.
706 function save_text($filename, $text)
708 if (!$fp = fopen($filename, 'w')) {
709 return PEAR::raiseError("Cannot open file '" . $filename . "' (save_text)");
713 if (1 < DETAILED) echo "
720 function _cleanupOldFiles($file)
722 $temp_dir = realpath(dirname($file));
723 $mainFileName = basename($file, 'phpt');
724 $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'diff';
725 $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'log';
726 $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'exp';
727 $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'out';
728 $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'mem';
729 $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'php';
730 $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'skip.php';
731 $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $mainFileName.'clean.php';
732 $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('phpt.');
734 // unlink old test results
735 @unlink($diff_filename);
736 @unlink($log_filename);
737 @unlink($exp_filename);
738 @unlink($output_filename);
739 @unlink($memcheck_filename);
741 @unlink($temp_skipif);
743 @unlink($temp_clean);
746 function _runSkipIf($section_text, $temp_skipif, $tested, $ini_settings)
750 if (array_key_exists('SKIPIF', $section_text) && trim($section_text['SKIPIF'])) {
751 $this->save_text($temp_skipif, $section_text['SKIPIF']);
752 $output = $this->system_with_timeout("$this->_php$ini_settings -f \"$temp_skipif\"");
753 $output = $output[1];
754 $loutput = ltrim($output);
755 unlink($temp_skipif);
756 if (!strncasecmp('skip', $loutput, 4)) {
757 $skipreason = "SKIP $tested";
758 if (preg_match('/^\s*skip\s*(.+)\s*/i', $output, $m)) {
759 $skipreason .= '(reason: ' . $m[1] . ')';
761 if (!isset($this->_options['quiet'])) {
762 $this->_logger->log(0, $skipreason);
764 if (isset($this->_options['tapoutput'])) {
765 return array('ok', ' # skip ' . $reason);
770 if (!strncasecmp('info', $loutput, 4)
771 && preg_match('/^\s*info\s*(.+)\s*/i', $output, $m)) {
772 $info = " (info: $m[1])";
775 if (!strncasecmp('warn', $loutput, 4)
776 && preg_match('/^\s*warn\s*(.+)\s*/i', $output, $m)) {
777 $warn = true; /* only if there is a reason */
778 $info = " (warn: $m[1])";
782 return array('warn' => $warn, 'info' => $info);
785 function _stripHeadersCGI($output)
787 $this->headers = array();
788 if (!empty($this->_options['cgi']) &&
789 $this->_php == $this->_options['cgi'] &&
790 preg_match("/^(.*?)(?:\n\n(.*)|\\z)/s", $output, $match)) {
791 $output = isset($match[2]) ? trim($match[2]) : '';
792 $this->_headers = $this->_processHeaders($match[1]);
799 * Return an array that can be used with array_diff() to compare headers
801 * @param string $text
803 function _processHeaders($text)
806 $rh = preg_split("/[\n\r]+/", $text);
807 foreach ($rh as $line) {
808 if (strpos($line, ':')!== false) {
809 $line = explode(':', $line, 2);
810 $headers[trim($line[0])] = trim($line[1]);
816 function _readFile($file)
818 // Load the sections of the test file.
819 $section_text = array(
820 'TEST' => '(unnamed test)',
830 if (!is_file($file) || !$fp = fopen($file, "r")) {
831 return PEAR::raiseError("Cannot open test file: $file");
838 // Match the beginning of a section.
839 if (preg_match('/^--([_A-Z]+)--/', $line, $r)) {
841 $section_text[$section] = '';
843 } elseif (empty($section)) {
845 return PEAR::raiseError("Invalid sections formats in test file: $file");
848 // Add to the section text.
849 $section_text[$section] .= $line;
853 return $section_text;
856 function _writeLog($logname, $data)
858 if (!$log = fopen($logname, 'w')) {
859 return PEAR::raiseError("Cannot create test log - $logname");
865 function _resetEnv($section_text, $temp_file)
868 $env['REDIRECT_STATUS'] = '';
869 $env['QUERY_STRING'] = '';
870 $env['PATH_TRANSLATED'] = '';
871 $env['SCRIPT_FILENAME'] = '';
872 $env['REQUEST_METHOD'] = '';
873 $env['CONTENT_TYPE'] = '';
874 $env['CONTENT_LENGTH'] = '';
875 if (!empty($section_text['ENV'])) {
876 if (strpos($section_text['ENV'], '{PWD}') !== false) {
877 $section_text['ENV'] = str_replace('{PWD}', dirname($temp_file), $section_text['ENV']);
879 foreach (explode("\n", trim($section_text['ENV'])) as $e) {
880 $e = explode('=', trim($e), 2);
881 if (!empty($e[0]) && isset($e[1])) {
886 if (array_key_exists('GET', $section_text)) {
887 $env['QUERY_STRING'] = trim($section_text['GET']);
889 $env['QUERY_STRING'] = '';
891 if (array_key_exists('COOKIE', $section_text)) {
892 $env['HTTP_COOKIE'] = trim($section_text['COOKIE']);
894 $env['HTTP_COOKIE'] = '';
896 $env['REDIRECT_STATUS'] = '1';
897 $env['PATH_TRANSLATED'] = $temp_file;
898 $env['SCRIPT_FILENAME'] = $temp_file;
903 function _processUpload($section_text, $file)
905 if (array_key_exists('UPLOAD', $section_text) && !empty($section_text['UPLOAD'])) {
906 $upload_files = trim($section_text['UPLOAD']);
907 $upload_files = explode("\n", $upload_files);
909 $request = "Content-Type: multipart/form-data; boundary=---------------------------20896060251896012921717172737\n" .
910 "-----------------------------20896060251896012921717172737\n";
911 foreach ($upload_files as $fileinfo) {
912 $fileinfo = explode('=', $fileinfo);
913 if (count($fileinfo) != 2) {
914 return PEAR::raiseError("Invalid UPLOAD section in test file: $file");
916 if (!realpath(dirname($file) . '/' . $fileinfo[1])) {
917 return PEAR::raiseError("File for upload does not exist: $fileinfo[1] " .
918 "in test file: $file");
920 $file_contents = file_get_contents(dirname($file) . '/' . $fileinfo[1]);
921 $fileinfo[1] = basename($fileinfo[1]);
922 $request .= "Content-Disposition: form-data; name=\"$fileinfo[0]\"; filename=\"$fileinfo[1]\"\n";
923 $request .= "Content-Type: text/plain\n\n";
924 $request .= $file_contents . "\n" .
925 "-----------------------------20896060251896012921717172737\n";
928 if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
930 $post = trim($section_text['POST']);
931 $post = explode('&', $post);
932 foreach ($post as $i => $post_info) {
933 $post_info = explode('=', $post_info);
934 if (count($post_info) != 2) {
935 return PEAR::raiseError("Invalid POST data in test file: $file");
937 $post_info[0] = rawurldecode($post_info[0]);
938 $post_info[1] = rawurldecode($post_info[1]);
939 $post[$i] = $post_info;
941 foreach ($post as $post_info) {
942 $request .= "Content-Disposition: form-data; name=\"$post_info[0]\"\n\n";
943 $request .= $post_info[1] . "\n" .
944 "-----------------------------20896060251896012921717172737\n";
946 unset($section_text['POST']);
948 $section_text['POST_RAW'] = $request;
951 return $section_text;
954 function _testCleanup($section_text, $temp_clean)
956 if ($section_text['CLEAN']) {
957 // perform test cleanup
958 $this->save_text($temp_clean, $section_text['CLEAN']);
959 $output = $this->system_with_timeout("$this->_php $temp_clean 2>&1");
960 if (strlen($output[1])) {
961 echo "BORKED --CLEAN-- section! output:\n", $output[1];
963 if (file_exists($temp_clean)) {