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