PageRenderTime 37ms CodeModel.GetById 40ms RepoModel.GetById 0ms app.codeStats 1ms

/nntpgrab-0.7.2/client/web/module/run-tests.php

#
PHP | 2767 lines | 2329 code | 328 blank | 110 comment | 336 complexity | d9674fb847ba56749e8a7278cb3844c1 MD5 | raw file
  1. #!/usr/bin/php
  2. <?php
  3. /*
  4. +----------------------------------------------------------------------+
  5. | PHP Version 5 |
  6. +----------------------------------------------------------------------+
  7. | Copyright (c) 1997-2010 The PHP Group |
  8. +----------------------------------------------------------------------+
  9. | This source file is subject to version 3.01 of the PHP license, |
  10. | that is bundled with this package in the file LICENSE, and is |
  11. | available through the world-wide-web at the following url: |
  12. | http://www.php.net/license/3_01.txt |
  13. | If you did not receive a copy of the PHP license and are unable to |
  14. | obtain it through the world-wide-web, please send a note to |
  15. | license@php.net so we can mail you a copy immediately. |
  16. +----------------------------------------------------------------------+
  17. | Authors: Ilia Alshanetsky <iliaa@php.net> |
  18. | Preston L. Bannister <pbannister@php.net> |
  19. | Marcus Boerger <helly@php.net> |
  20. | Derick Rethans <derick@php.net> |
  21. | Sander Roobol <sander@php.net> |
  22. | (based on version by: Stig Bakken <ssb@php.net>) |
  23. | (based on the PHP 3 test framework by Rasmus Lerdorf) |
  24. +----------------------------------------------------------------------+
  25. */
  26. /* $Id: cc193e56bc041c69b0b1de4eca51cd6d9ca21977 $ */
  27. /* Sanity check to ensure that pcre extension needed by this script is available.
  28. * In the event it is not, print a nice error message indicating that this script will
  29. * not run without it.
  30. */
  31. if (!extension_loaded('pcre')) {
  32. echo <<<NO_PCRE_ERROR
  33. +-----------------------------------------------------------+
  34. | ! ERROR ! |
  35. | The test-suite requires that you have pcre extension |
  36. | enabled. To enable this extension either compile your PHP |
  37. | with --with-pcre-regex or if you've compiled pcre as a |
  38. | shared module load it via php.ini. |
  39. +-----------------------------------------------------------+
  40. NO_PCRE_ERROR;
  41. exit;
  42. }
  43. if (!function_exists('proc_open')) {
  44. echo <<<NO_PROC_OPEN_ERROR
  45. +-----------------------------------------------------------+
  46. | ! ERROR ! |
  47. | The test-suite requires that proc_open() is available. |
  48. | Please check if you disabled it in php.ini. |
  49. +-----------------------------------------------------------+
  50. NO_PROC_OPEN_ERROR;
  51. exit;
  52. }
  53. // Version constants only available as of 5.2.8
  54. if (!defined("PHP_VERSION_ID")) {
  55. list($major, $minor, $bug) = explode(".", phpversion(), 3);
  56. $bug = (int)$bug; // Many distros make up their own versions
  57. if ($bug < 10) {
  58. $bug = "0$bug";
  59. }
  60. define("PHP_VERSION_ID", "{$major}0{$minor}$bug");
  61. define("PHP_MAJOR_VERSION", $major);
  62. }
  63. // __DIR__ is available from 5.3.0
  64. if (PHP_VERSION_ID < 50300) {
  65. define('__DIR__', realpath(dirname(__FILE__)));
  66. // FILE_BINARY is available from 5.2.7
  67. if (PHP_VERSION_ID < 50207) {
  68. define('FILE_BINARY', 0);
  69. }
  70. }
  71. // If timezone is not set, use UTC.
  72. if (ini_get('date.timezone') == '') {
  73. date_default_timezone_set('UTC');
  74. }
  75. // store current directory
  76. $CUR_DIR = getcwd();
  77. // change into the PHP source directory.
  78. if (getenv('TEST_PHP_SRCDIR')) {
  79. @chdir(getenv('TEST_PHP_SRCDIR'));
  80. }
  81. // Delete some security related environment variables
  82. putenv('SSH_CLIENT=deleted');
  83. putenv('SSH_AUTH_SOCK=deleted');
  84. putenv('SSH_TTY=deleted');
  85. putenv('SSH_CONNECTION=deleted');
  86. $cwd = getcwd();
  87. set_time_limit(0);
  88. ini_set('pcre.backtrack_limit', PHP_INT_MAX);
  89. $valgrind_version = 0;
  90. $valgrind_header = '';
  91. // delete as much output buffers as possible
  92. while(@ob_end_clean());
  93. if (ob_get_level()) echo "Not all buffers were deleted.\n";
  94. error_reporting(E_ALL);
  95. if (PHP_MAJOR_VERSION < 6) {
  96. ini_set('magic_quotes_runtime',0); // this would break tests by modifying EXPECT sections
  97. if (ini_get('safe_mode')) {
  98. echo <<< SAFE_MODE_WARNING
  99. +-----------------------------------------------------------+
  100. | ! WARNING ! |
  101. | You are running the test-suite with "safe_mode" ENABLED ! |
  102. | |
  103. | Chances are high that no test will work at all, |
  104. | depending on how you configured "safe_mode" ! |
  105. +-----------------------------------------------------------+
  106. SAFE_MODE_WARNING;
  107. }
  108. }
  109. $environment = isset($_ENV) ? $_ENV : array();
  110. if ((substr(PHP_OS, 0, 3) == "WIN") && empty($environment["SystemRoot"])) {
  111. $environment["SystemRoot"] = getenv("SystemRoot");
  112. }
  113. // Don't ever guess at the PHP executable location.
  114. // Require the explicit specification.
  115. // Otherwise we could end up testing the wrong file!
  116. $php = null;
  117. $php_cgi = null;
  118. if (getenv('TEST_PHP_EXECUTABLE')) {
  119. $php = getenv('TEST_PHP_EXECUTABLE');
  120. if ($php=='auto') {
  121. $php = $cwd . '/sapi/cli/php';
  122. putenv("TEST_PHP_EXECUTABLE=$php");
  123. if (!getenv('TEST_PHP_CGI_EXECUTABLE')) {
  124. $php_cgi = $cwd . '/sapi/cgi/php-cgi';
  125. if (file_exists($php_cgi)) {
  126. putenv("TEST_PHP_CGI_EXECUTABLE=$php_cgi");
  127. } else {
  128. $php_cgi = null;
  129. }
  130. }
  131. }
  132. $environment['TEST_PHP_EXECUTABLE'] = $php;
  133. }
  134. if (getenv('TEST_PHP_CGI_EXECUTABLE')) {
  135. $php_cgi = getenv('TEST_PHP_CGI_EXECUTABLE');
  136. if ($php_cgi=='auto') {
  137. $php_cgi = $cwd . '/sapi/cgi/php-cgi';
  138. putenv("TEST_PHP_CGI_EXECUTABLE=$php_cgi");
  139. }
  140. $environment['TEST_PHP_CGI_EXECUTABLE'] = $php_cgi;
  141. }
  142. function verify_config()
  143. {
  144. global $php;
  145. if (empty($php) || !file_exists($php)) {
  146. error('environment variable TEST_PHP_EXECUTABLE must be set to specify PHP executable!');
  147. }
  148. if (function_exists('is_executable') && !is_executable($php)) {
  149. error("invalid PHP executable specified by TEST_PHP_EXECUTABLE = $php");
  150. }
  151. }
  152. if (getenv('TEST_PHP_LOG_FORMAT')) {
  153. $log_format = strtoupper(getenv('TEST_PHP_LOG_FORMAT'));
  154. } else {
  155. $log_format = 'LEODS';
  156. }
  157. // Check whether a detailed log is wanted.
  158. if (getenv('TEST_PHP_DETAILED')) {
  159. $DETAILED = getenv('TEST_PHP_DETAILED');
  160. } else {
  161. $DETAILED = 0;
  162. }
  163. junit_init();
  164. if (getenv('SHOW_ONLY_GROUPS')) {
  165. $SHOW_ONLY_GROUPS = explode(",", getenv('SHOW_ONLY_GROUPS'));
  166. } else {
  167. $SHOW_ONLY_GROUPS = array();
  168. }
  169. // Check whether user test dirs are requested.
  170. if (getenv('TEST_PHP_USER')) {
  171. $user_tests = explode (',', getenv('TEST_PHP_USER'));
  172. } else {
  173. $user_tests = array();
  174. }
  175. $exts_to_test = array();
  176. $ini_overwrites = array(
  177. 'output_handler=',
  178. 'open_basedir=',
  179. 'safe_mode=0',
  180. 'disable_functions=',
  181. 'output_buffering=Off',
  182. 'error_reporting=' . (E_ALL | E_STRICT),
  183. 'display_errors=1',
  184. 'display_startup_errors=1',
  185. 'log_errors=0',
  186. 'html_errors=0',
  187. 'track_errors=1',
  188. 'report_memleaks=1',
  189. 'report_zend_debug=0',
  190. 'docref_root=',
  191. 'docref_ext=.html',
  192. 'error_prepend_string=',
  193. 'error_append_string=',
  194. 'auto_prepend_file=',
  195. 'auto_append_file=',
  196. 'magic_quotes_runtime=0',
  197. 'ignore_repeated_errors=0',
  198. 'precision=14',
  199. 'unicode.runtime_encoding=ISO-8859-1',
  200. 'unicode.script_encoding=UTF-8',
  201. 'unicode.output_encoding=UTF-8',
  202. 'unicode.from_error_mode=U_INVALID_SUBSTITUTE',
  203. );
  204. function write_information($show_html)
  205. {
  206. global $cwd, $php, $php_cgi, $php_info, $user_tests, $ini_overwrites, $pass_options, $exts_to_test, $leak_check, $valgrind_header;
  207. // Get info from php
  208. $info_file = __DIR__ . '/run-test-info.php';
  209. @unlink($info_file);
  210. $php_info = '<?php echo "
  211. PHP_SAPI : " , PHP_SAPI , "
  212. PHP_VERSION : " , phpversion() , "
  213. ZEND_VERSION: " , zend_version() , "
  214. PHP_OS : " , PHP_OS , " - " , php_uname() , "
  215. INI actual : " , realpath(get_cfg_var("cfg_file_path")) , "
  216. More .INIs : " , (function_exists(\'php_ini_scanned_files\') ? str_replace("\n","", php_ini_scanned_files()) : "** not determined **"); ?>';
  217. save_text($info_file, $php_info);
  218. $info_params = array();
  219. settings2array($ini_overwrites, $info_params);
  220. settings2params($info_params);
  221. $php_info = `$php $pass_options $info_params "$info_file"`;
  222. define('TESTED_PHP_VERSION', `$php -n -r "echo PHP_VERSION;"`);
  223. if ($php_cgi && $php != $php_cgi) {
  224. $php_info_cgi = `$php_cgi $pass_options $info_params -q "$info_file"`;
  225. $php_info_sep = "\n---------------------------------------------------------------------";
  226. $php_cgi_info = "$php_info_sep\nPHP : $php_cgi $php_info_cgi$php_info_sep";
  227. } else {
  228. $php_cgi_info = '';
  229. }
  230. @unlink($info_file);
  231. // load list of enabled extensions
  232. save_text($info_file, '<?php echo join(",", get_loaded_extensions()); ?>');
  233. $exts_to_test = explode(',',`$php $pass_options $info_params "$info_file"`);
  234. // check for extensions that need special handling and regenerate
  235. $info_params_ex = array(
  236. 'session' => array('session.auto_start=0'),
  237. 'tidy' => array('tidy.clean_output=0'),
  238. 'zlib' => array('zlib.output_compression=Off'),
  239. 'xdebug' => array('xdebug.default_enable=0'),
  240. 'mbstring' => array('mbstring.func_overload=0'),
  241. );
  242. foreach($info_params_ex as $ext => $ini_overwrites_ex) {
  243. if (in_array($ext, $exts_to_test)) {
  244. $ini_overwrites = array_merge($ini_overwrites, $ini_overwrites_ex);
  245. }
  246. }
  247. @unlink($info_file);
  248. // Write test context information.
  249. echo "
  250. =====================================================================
  251. PHP : $php $php_info $php_cgi_info
  252. CWD : $cwd
  253. Extra dirs : ";
  254. foreach ($user_tests as $test_dir) {
  255. echo "{$test_dir}\n ";
  256. }
  257. echo "
  258. VALGRIND : " . ($leak_check ? $valgrind_header : 'Not used') . "
  259. =====================================================================
  260. ";
  261. }
  262. define('PHP_QA_EMAIL', 'qa-reports@lists.php.net');
  263. define('QA_SUBMISSION_PAGE', 'http://qa.php.net/buildtest-process.php');
  264. define('QA_REPORTS_PAGE', 'http://qa.php.net/reports');
  265. function save_or_mail_results()
  266. {
  267. global $sum_results, $just_save_results, $failed_test_summary,
  268. $PHP_FAILED_TESTS, $CUR_DIR, $php, $output_file, $compression;
  269. /* We got failed Tests, offer the user to send an e-mail to QA team, unless NO_INTERACTION is set */
  270. if (!getenv('NO_INTERACTION')) {
  271. $fp = fopen("php://stdin", "r+");
  272. if ($sum_results['FAILED'] || $sum_results['BORKED'] || $sum_results['WARNED'] || $sum_results['LEAKED'] || $sum_results['XFAILED']) {
  273. echo "\nYou may have found a problem in PHP.";
  274. }
  275. echo "\nThis report can be automatically sent to the PHP QA team at\n";
  276. echo QA_REPORTS_PAGE . " and http://news.php.net/php.qa.reports\n";
  277. echo "This gives us a better understanding of PHP's behavior.\n";
  278. echo "If you don't want to send the report immediately you can choose\n";
  279. echo "option \"s\" to save it. You can then email it to ". PHP_QA_EMAIL . " later.\n";
  280. echo "Do you want to send this report now? [Yns]: ";
  281. flush();
  282. $user_input = fgets($fp, 10);
  283. $just_save_results = (strtolower($user_input[0]) == 's');
  284. }
  285. if ($just_save_results || !getenv('NO_INTERACTION')) {
  286. if ($just_save_results || strlen(trim($user_input)) == 0 || strtolower($user_input[0]) == 'y') {
  287. /*
  288. * Collect information about the host system for our report
  289. * Fetch phpinfo() output so that we can see the PHP enviroment
  290. * Make an archive of all the failed tests
  291. * Send an email
  292. */
  293. if ($just_save_results) {
  294. $user_input = 's';
  295. }
  296. /* Ask the user to provide an email address, so that QA team can contact the user */
  297. if (!strncasecmp($user_input, 'y', 1) || strlen(trim($user_input)) == 0) {
  298. echo "\nPlease enter your email address.\n(Your address will be mangled so that it will not go out on any\nmailinglist in plain text): ";
  299. flush();
  300. $user_email = trim(fgets($fp, 1024));
  301. $user_email = str_replace("@", " at ", str_replace(".", " dot ", $user_email));
  302. }
  303. $failed_tests_data = '';
  304. $sep = "\n" . str_repeat('=', 80) . "\n";
  305. $failed_tests_data .= $failed_test_summary . "\n";
  306. $failed_tests_data .= get_summary(true, false) . "\n";
  307. if ($sum_results['FAILED']) {
  308. foreach ($PHP_FAILED_TESTS['FAILED'] as $test_info) {
  309. $failed_tests_data .= $sep . $test_info['name'] . $test_info['info'];
  310. $failed_tests_data .= $sep . file_get_contents(realpath($test_info['output']), FILE_BINARY);
  311. $failed_tests_data .= $sep . file_get_contents(realpath($test_info['diff']), FILE_BINARY);
  312. $failed_tests_data .= $sep . "\n\n";
  313. }
  314. $status = "failed";
  315. } else {
  316. $status = "success";
  317. }
  318. $failed_tests_data .= "\n" . $sep . 'BUILD ENVIRONMENT' . $sep;
  319. $failed_tests_data .= "OS:\n" . PHP_OS . " - " . php_uname() . "\n\n";
  320. $ldd = $autoconf = $sys_libtool = $libtool = $compiler = 'N/A';
  321. if (substr(PHP_OS, 0, 3) != "WIN") {
  322. /* If PHP_AUTOCONF is set, use it; otherwise, use 'autoconf'. */
  323. if (getenv('PHP_AUTOCONF')) {
  324. $autoconf = shell_exec(getenv('PHP_AUTOCONF') . ' --version');
  325. } else {
  326. $autoconf = shell_exec('autoconf --version');
  327. }
  328. /* Always use the generated libtool - Mac OSX uses 'glibtool' */
  329. $libtool = shell_exec($CUR_DIR . '/libtool --version');
  330. /* Use shtool to find out if there is glibtool present (MacOSX) */
  331. $sys_libtool_path = shell_exec(__DIR__ . '/build/shtool path glibtool libtool');
  332. if ($sys_libtool_path) {
  333. $sys_libtool = shell_exec(str_replace("\n", "", $sys_libtool_path) . ' --version');
  334. }
  335. /* Try the most common flags for 'version' */
  336. $flags = array('-v', '-V', '--version');
  337. $cc_status = 0;
  338. foreach($flags AS $flag) {
  339. system(getenv('CC') . " $flag >/dev/null 2>&1", $cc_status);
  340. if ($cc_status == 0) {
  341. $compiler = shell_exec(getenv('CC') . " $flag 2>&1");
  342. break;
  343. }
  344. }
  345. $ldd = shell_exec("ldd $php 2>/dev/null");
  346. }
  347. $failed_tests_data .= "Autoconf:\n$autoconf\n";
  348. $failed_tests_data .= "Bundled Libtool:\n$libtool\n";
  349. $failed_tests_data .= "System Libtool:\n$sys_libtool\n";
  350. $failed_tests_data .= "Compiler:\n$compiler\n";
  351. $failed_tests_data .= "Bison:\n". shell_exec('bison --version 2>/dev/null') . "\n";
  352. $failed_tests_data .= "Libraries:\n$ldd\n";
  353. $failed_tests_data .= "\n";
  354. if (isset($user_email)) {
  355. $failed_tests_data .= "User's E-mail: " . $user_email . "\n\n";
  356. }
  357. $failed_tests_data .= $sep . "PHPINFO" . $sep;
  358. $failed_tests_data .= shell_exec($php . ' -ddisplay_errors=stderr -dhtml_errors=0 -i 2> /dev/null');
  359. if ($just_save_results || !mail_qa_team($failed_tests_data, $compression, $status)) {
  360. file_put_contents($output_file, $failed_tests_data);
  361. if (!$just_save_results) {
  362. echo "\nThe test script was unable to automatically send the report to PHP's QA Team\n";
  363. }
  364. echo "Please send " . $output_file . " to " . PHP_QA_EMAIL . " manually, thank you.\n";
  365. } else {
  366. fwrite($fp, "\nThank you for helping to make PHP better.\n");
  367. fclose($fp);
  368. }
  369. }
  370. }
  371. }
  372. // Determine the tests to be run.
  373. $test_files = array();
  374. $redir_tests = array();
  375. $test_results = array();
  376. $PHP_FAILED_TESTS = array('BORKED' => array(), 'FAILED' => array(), 'WARNED' => array(), 'LEAKED' => array(), 'XFAILED' => array());
  377. // If parameters given assume they represent selected tests to run.
  378. $failed_tests_file= false;
  379. $pass_option_n = false;
  380. $pass_options = '';
  381. $compression = 0;
  382. $output_file = $CUR_DIR . '/php_test_results_' . date('Ymd_Hi') . '.txt';
  383. if ($compression) {
  384. $output_file = 'compress.zlib://' . $output_file . '.gz';
  385. }
  386. $just_save_results = false;
  387. $leak_check = false;
  388. $html_output = false;
  389. $html_file = null;
  390. $temp_source = null;
  391. $temp_target = null;
  392. $temp_urlbase = null;
  393. $conf_passed = null;
  394. $no_clean = false;
  395. $cfgtypes = array('show', 'keep');
  396. $cfgfiles = array('skip', 'php', 'clean', 'out', 'diff', 'exp');
  397. $cfg = array();
  398. foreach($cfgtypes as $type) {
  399. $cfg[$type] = array();
  400. foreach($cfgfiles as $file) {
  401. $cfg[$type][$file] = false;
  402. }
  403. }
  404. if (getenv('TEST_PHP_ARGS')) {
  405. if (!isset($argc) || !$argc || !isset($argv)) {
  406. $argv = array(__FILE__);
  407. }
  408. $argv = array_merge($argv, explode(' ', getenv('TEST_PHP_ARGS')));
  409. $argc = count($argv);
  410. }
  411. if (isset($argc) && $argc > 1) {
  412. for ($i=1; $i<$argc; $i++) {
  413. $is_switch = false;
  414. $switch = substr($argv[$i],1,1);
  415. $repeat = substr($argv[$i],0,1) == '-';
  416. while ($repeat) {
  417. if (!$is_switch) {
  418. $switch = substr($argv[$i],1,1);
  419. }
  420. $is_switch = true;
  421. if ($repeat) {
  422. foreach($cfgtypes as $type) {
  423. if (strpos($switch, '--' . $type) === 0) {
  424. foreach($cfgfiles as $file) {
  425. if ($switch == '--' . $type . '-' . $file) {
  426. $cfg[$type][$file] = true;
  427. $is_switch = false;
  428. break;
  429. }
  430. }
  431. }
  432. }
  433. }
  434. if (!$is_switch) {
  435. $is_switch = true;
  436. break;
  437. }
  438. $repeat = false;
  439. switch($switch) {
  440. case 'r':
  441. case 'l':
  442. $test_list = file($argv[++$i]);
  443. if ($test_list) {
  444. foreach($test_list as $test) {
  445. $matches = array();
  446. if (preg_match('/^#.*\[(.*)\]\:\s+(.*)$/', $test, $matches)) {
  447. $redir_tests[] = array($matches[1], $matches[2]);
  448. } else if (strlen($test)) {
  449. $test_files[] = trim($test);
  450. }
  451. }
  452. }
  453. if ($switch != 'l') {
  454. break;
  455. }
  456. $i--;
  457. // break left intentionally
  458. case 'w':
  459. $failed_tests_file = fopen($argv[++$i], 'w+t');
  460. break;
  461. case 'a':
  462. $failed_tests_file = fopen($argv[++$i], 'a+t');
  463. break;
  464. case 'c':
  465. $conf_passed = $argv[++$i];
  466. break;
  467. case 'd':
  468. $ini_overwrites[] = $argv[++$i];
  469. break;
  470. case 'g':
  471. $SHOW_ONLY_GROUPS = explode(",", $argv[++$i]);;
  472. break;
  473. //case 'h'
  474. case '--keep-all':
  475. foreach($cfgfiles as $file) {
  476. $cfg['keep'][$file] = true;
  477. }
  478. break;
  479. //case 'l'
  480. case 'm':
  481. $leak_check = true;
  482. $valgrind_cmd = "valgrind --version";
  483. $valgrind_header = system_with_timeout($valgrind_cmd, $environment);
  484. $replace_count = 0;
  485. if (!$valgrind_header) {
  486. error("Valgrind returned no version info, cannot proceed.\nPlease check if Valgrind is installed.");
  487. } else {
  488. $valgrind_version = preg_replace("/valgrind-([0-9])\.([0-9])\.([0-9]+)([.-\w]+)?(\s+)/", '$1$2$3', $valgrind_header, 1, $replace_count);
  489. if ($replace_count != 1 || !is_numeric($valgrind_version)) {
  490. error("Valgrind returned invalid version info (\"$valgrind_header\"), cannot proceed.");
  491. }
  492. $valgrind_header = trim($valgrind_header);
  493. }
  494. break;
  495. case 'n':
  496. if (!$pass_option_n) {
  497. $pass_options .= ' -n';
  498. }
  499. $pass_option_n = true;
  500. break;
  501. case '--no-clean':
  502. $no_clean = true;
  503. break;
  504. case 'p':
  505. $php = $argv[++$i];
  506. putenv("TEST_PHP_EXECUTABLE=$php");
  507. $environment['TEST_PHP_EXECUTABLE'] = $php;
  508. break;
  509. case 'q':
  510. putenv('NO_INTERACTION=1');
  511. break;
  512. //case 'r'
  513. case 's':
  514. $output_file = $argv[++$i];
  515. $just_save_results = true;
  516. break;
  517. case '--set-timeout':
  518. $environment['TEST_TIMEOUT'] = $argv[++$i];
  519. break;
  520. case '--show-all':
  521. foreach($cfgfiles as $file) {
  522. $cfg['show'][$file] = true;
  523. }
  524. break;
  525. case '--temp-source':
  526. $temp_source = $argv[++$i];
  527. break;
  528. case '--temp-target':
  529. $temp_target = $argv[++$i];
  530. if ($temp_urlbase) {
  531. $temp_urlbase = $temp_target;
  532. }
  533. break;
  534. case '--temp-urlbase':
  535. $temp_urlbase = $argv[++$i];
  536. break;
  537. case 'v':
  538. case '--verbose':
  539. $DETAILED = true;
  540. break;
  541. case 'x':
  542. $environment['SKIP_SLOW_TESTS'] = 1;
  543. break;
  544. //case 'w'
  545. case '-':
  546. // repeat check with full switch
  547. $switch = $argv[$i];
  548. if ($switch != '-') {
  549. $repeat = true;
  550. }
  551. break;
  552. case '--html':
  553. $html_file = fopen($argv[++$i], 'wt');
  554. $html_output = is_resource($html_file);
  555. break;
  556. case '--version':
  557. echo '$Id: cc193e56bc041c69b0b1de4eca51cd6d9ca21977 $' . "\n";
  558. exit(1);
  559. default:
  560. echo "Illegal switch '$switch' specified!\n";
  561. case 'h':
  562. case '-help':
  563. case '--help':
  564. echo <<<HELP
  565. Synopsis:
  566. php run-tests.php [options] [files] [directories]
  567. Options:
  568. -l <file> Read the testfiles to be executed from <file>. After the test
  569. has finished all failed tests are written to the same <file>.
  570. If the list is empty and no further test is specified then
  571. all tests are executed (same as: -r <file> -w <file>).
  572. -r <file> Read the testfiles to be executed from <file>.
  573. -w <file> Write a list of all failed tests to <file>.
  574. -a <file> Same as -w but append rather then truncating <file>.
  575. -c <file> Look for php.ini in directory <file> or use <file> as ini.
  576. -n Pass -n option to the php binary (Do not use a php.ini).
  577. -d foo=bar Pass -d option to the php binary (Define INI entry foo
  578. with value 'bar').
  579. -g Comma seperated list of groups to show during test run
  580. (possible values: PASS, FAIL, XFAIL, SKIP, BORK, WARN, LEAK, REDIRECT).
  581. -m Test for memory leaks with Valgrind.
  582. -p <php> Specify PHP executable to run.
  583. -q Quiet, no user interaction (same as environment NO_INTERACTION).
  584. -s <file> Write output to <file>.
  585. -x Sets 'SKIP_SLOW_TESTS' environmental variable.
  586. --verbose
  587. -v Verbose mode.
  588. --help
  589. -h This Help.
  590. --html <file> Generate HTML output.
  591. --temp-source <sdir> --temp-target <tdir> [--temp-urlbase <url>]
  592. Write temporary files to <tdir> by replacing <sdir> from the
  593. filenames to generate with <tdir>. If --html is being used and
  594. <url> given then the generated links are relative and prefixed
  595. with the given url. In general you want to make <sdir> the path
  596. to your source files and <tdir> some pach in your web page
  597. hierarchy with <url> pointing to <tdir>.
  598. --keep-[all|php|skip|clean]
  599. Do not delete 'all' files, 'php' test file, 'skip' or 'clean'
  600. file.
  601. --set-timeout [n]
  602. Set timeout for individual tests, where [n] is the number of
  603. seconds. The default value is 60 seconds, or 300 seconds when
  604. testing for memory leaks.
  605. --show-[all|php|skip|clean|exp|diff|out]
  606. Show 'all' files, 'php' test file, 'skip' or 'clean' file. You
  607. can also use this to show the output 'out', the expected result
  608. 'exp' or the difference between them 'diff'. The result types
  609. get written independent of the log format, however 'diff' only
  610. exists when a test fails.
  611. --no-clean Do not execute clean section if any.
  612. HELP;
  613. exit(1);
  614. }
  615. }
  616. if (!$is_switch) {
  617. $testfile = realpath($argv[$i]);
  618. if (!$testfile && strpos($argv[$i], '*') !== false && function_exists('glob')) {
  619. if (preg_match("/\.phpt$/", $argv[$i])) {
  620. $pattern_match = glob($argv[$i]);
  621. } else if (preg_match("/\*$/", $argv[$i])) {
  622. $pattern_match = glob($argv[$i] . '.phpt');
  623. } else {
  624. die("bogus test name " . $argv[$i] . "\n");
  625. }
  626. if (is_array($pattern_match)) {
  627. $test_files = array_merge($test_files, $pattern_match);
  628. }
  629. } else if (is_dir($testfile)) {
  630. find_files($testfile);
  631. } else if (preg_match("/\.phpt$/", $testfile)) {
  632. $test_files[] = $testfile;
  633. } else {
  634. die("bogus test name " . $argv[$i] . "\n");
  635. }
  636. }
  637. }
  638. if (strlen($conf_passed)) {
  639. if (substr(PHP_OS, 0, 3) == "WIN") {
  640. $pass_options .= " -c " . escapeshellarg($conf_passed);
  641. } else {
  642. $pass_options .= " -c '$conf_passed'";
  643. }
  644. }
  645. $test_files = array_unique($test_files);
  646. $test_files = array_merge($test_files, $redir_tests);
  647. // Run selected tests.
  648. $test_cnt = count($test_files);
  649. if ($test_cnt) {
  650. putenv('NO_INTERACTION=1');
  651. verify_config();
  652. write_information($html_output);
  653. usort($test_files, "test_sort");
  654. $start_time = time();
  655. if (!$html_output) {
  656. echo "Running selected tests.\n";
  657. } else {
  658. show_start($start_time);
  659. }
  660. $test_idx = 0;
  661. run_all_tests($test_files, $environment);
  662. $end_time = time();
  663. if ($html_output) {
  664. show_end($end_time);
  665. }
  666. if ($failed_tests_file) {
  667. fclose($failed_tests_file);
  668. }
  669. if (count($test_files) || count($test_results)) {
  670. compute_summary();
  671. if ($html_output) {
  672. fwrite($html_file, "<hr/>\n" . get_summary(false, true));
  673. }
  674. echo "=====================================================================";
  675. echo get_summary(false, false);
  676. }
  677. if ($html_output) {
  678. fclose($html_file);
  679. }
  680. if ($output_file != '' && $just_save_results) {
  681. save_or_mail_results();
  682. }
  683. junit_save_xml();
  684. if (getenv('REPORT_EXIT_STATUS') == 1 and preg_match('/FAILED(?: |$)/', implode(' ', $test_results))) {
  685. exit(1);
  686. }
  687. exit(0);
  688. }
  689. }
  690. verify_config();
  691. write_information($html_output);
  692. // Compile a list of all test files (*.phpt).
  693. $test_files = array();
  694. $exts_tested = count($exts_to_test);
  695. $exts_skipped = 0;
  696. $ignored_by_ext = 0;
  697. sort($exts_to_test);
  698. $test_dirs = array();
  699. $optionals = array('tests', 'ext', 'Zend', 'ZendEngine2', 'sapi/cli', 'sapi/cgi');
  700. foreach($optionals as $dir) {
  701. if (@filetype($dir) == 'dir') {
  702. $test_dirs[] = $dir;
  703. }
  704. }
  705. // Convert extension names to lowercase
  706. foreach ($exts_to_test as $key => $val) {
  707. $exts_to_test[$key] = strtolower($val);
  708. }
  709. foreach ($test_dirs as $dir) {
  710. find_files("{$cwd}/{$dir}", ($dir == 'ext'));
  711. }
  712. foreach ($user_tests as $dir) {
  713. find_files($dir, ($dir == 'ext'));
  714. }
  715. function find_files($dir, $is_ext_dir = false, $ignore = false)
  716. {
  717. global $test_files, $exts_to_test, $ignored_by_ext, $exts_skipped, $exts_tested;
  718. $o = opendir($dir) or error("cannot open directory: $dir");
  719. while (($name = readdir($o)) !== false) {
  720. if (is_dir("{$dir}/{$name}") && !in_array($name, array('.', '..', '.svn'))) {
  721. $skip_ext = ($is_ext_dir && !in_array(strtolower($name), $exts_to_test));
  722. if ($skip_ext) {
  723. $exts_skipped++;
  724. }
  725. find_files("{$dir}/{$name}", false, $ignore || $skip_ext);
  726. }
  727. // Cleanup any left-over tmp files from last run.
  728. if (substr($name, -4) == '.tmp') {
  729. @unlink("$dir/$name");
  730. continue;
  731. }
  732. // Otherwise we're only interested in *.phpt files.
  733. if (substr($name, -5) == '.phpt') {
  734. if ($ignore) {
  735. $ignored_by_ext++;
  736. } else {
  737. $testfile = realpath("{$dir}/{$name}");
  738. $test_files[] = $testfile;
  739. }
  740. }
  741. }
  742. closedir($o);
  743. }
  744. function test_name($name)
  745. {
  746. if (is_array($name)) {
  747. return $name[0] . ':' . $name[1];
  748. } else {
  749. return $name;
  750. }
  751. }
  752. function test_sort($a, $b)
  753. {
  754. global $cwd;
  755. $a = test_name($a);
  756. $b = test_name($b);
  757. $ta = strpos($a, "{$cwd}/tests") === 0 ? 1 + (strpos($a, "{$cwd}/tests/run-test") === 0 ? 1 : 0) : 0;
  758. $tb = strpos($b, "{$cwd}/tests") === 0 ? 1 + (strpos($b, "{$cwd}/tests/run-test") === 0 ? 1 : 0) : 0;
  759. if ($ta == $tb) {
  760. return strcmp($a, $b);
  761. } else {
  762. return $tb - $ta;
  763. }
  764. }
  765. $test_files = array_unique($test_files);
  766. usort($test_files, "test_sort");
  767. $start_time = time();
  768. show_start($start_time);
  769. $test_cnt = count($test_files);
  770. $test_idx = 0;
  771. run_all_tests($test_files, $environment);
  772. $end_time = time();
  773. if ($failed_tests_file) {
  774. fclose($failed_tests_file);
  775. }
  776. // Summarize results
  777. if (0 == count($test_results)) {
  778. echo "No tests were run.\n";
  779. return;
  780. }
  781. compute_summary();
  782. show_end($end_time);
  783. show_summary();
  784. if ($html_output) {
  785. fclose($html_file);
  786. }
  787. save_or_mail_results();
  788. junit_save_xml();
  789. if (getenv('REPORT_EXIT_STATUS') == 1 and $sum_results['FAILED']) {
  790. exit(1);
  791. }
  792. exit(0);
  793. //
  794. // Send Email to QA Team
  795. //
  796. function mail_qa_team($data, $compression, $status = false)
  797. {
  798. $url_bits = parse_url(QA_SUBMISSION_PAGE);
  799. if (($proxy = getenv('http_proxy'))) {
  800. $proxy = parse_url($proxy);
  801. $path = $url_bits['host'].$url_bits['path'];
  802. $host = $proxy['host'];
  803. if (empty($proxy['port'])) {
  804. $proxy['port'] = 80;
  805. }
  806. $port = $proxy['port'];
  807. } else {
  808. $path = $url_bits['path'];
  809. $host = $url_bits['host'];
  810. $port = empty($url_bits['port']) ? 80 : $port = $url_bits['port'];
  811. }
  812. $data = "php_test_data=" . urlencode(base64_encode(str_replace("\00", '[0x0]', $data)));
  813. $data_length = strlen($data);
  814. $fs = fsockopen($host, $port, $errno, $errstr, 10);
  815. if (!$fs) {
  816. return false;
  817. }
  818. $php_version = urlencode(TESTED_PHP_VERSION);
  819. echo "\nPosting to ". QA_SUBMISSION_PAGE . "\n";
  820. fwrite($fs, "POST " . $path . "?status=$status&version=$php_version HTTP/1.1\r\n");
  821. fwrite($fs, "Host: " . $host . "\r\n");
  822. fwrite($fs, "User-Agent: QA Browser 0.1\r\n");
  823. fwrite($fs, "Content-Type: application/x-www-form-urlencoded\r\n");
  824. fwrite($fs, "Content-Length: " . $data_length . "\r\n\r\n");
  825. fwrite($fs, $data);
  826. fwrite($fs, "\r\n\r\n");
  827. fclose($fs);
  828. return 1;
  829. }
  830. //
  831. // Write the given text to a temporary file, and return the filename.
  832. //
  833. function save_text($filename, $text, $filename_copy = null)
  834. {
  835. global $DETAILED;
  836. if ($filename_copy && $filename_copy != $filename) {
  837. if (file_put_contents($filename_copy, $text, FILE_BINARY) === false) {
  838. error("Cannot open file '" . $filename_copy . "' (save_text)");
  839. }
  840. }
  841. if (file_put_contents($filename, $text, FILE_BINARY) === false) {
  842. error("Cannot open file '" . $filename . "' (save_text)");
  843. }
  844. if (1 < $DETAILED) echo "
  845. FILE $filename {{{
  846. $text
  847. }}}
  848. ";
  849. }
  850. //
  851. // Write an error in a format recognizable to Emacs or MSVC.
  852. //
  853. function error_report($testname, $logname, $tested)
  854. {
  855. $testname = realpath($testname);
  856. $logname = realpath($logname);
  857. switch (strtoupper(getenv('TEST_PHP_ERROR_STYLE'))) {
  858. case 'MSVC':
  859. echo $testname . "(1) : $tested\n";
  860. echo $logname . "(1) : $tested\n";
  861. break;
  862. case 'EMACS':
  863. echo $testname . ":1: $tested\n";
  864. echo $logname . ":1: $tested\n";
  865. break;
  866. }
  867. }
  868. function system_with_timeout($commandline, $env = null, $stdin = null)
  869. {
  870. global $leak_check, $cwd;
  871. $data = '';
  872. $bin_env = array();
  873. foreach((array)$env as $key => $value) {
  874. $bin_env[$key] = $value;
  875. }
  876. $proc = proc_open($commandline, array(
  877. 0 => array('pipe', 'r'),
  878. 1 => array('pipe', 'w'),
  879. 2 => array('pipe', 'w')
  880. ), $pipes, $cwd, $bin_env, array('suppress_errors' => true, 'binary_pipes' => true));
  881. if (!$proc) {
  882. return false;
  883. }
  884. if (!is_null($stdin)) {
  885. fwrite($pipes[0], $stdin);
  886. }
  887. fclose($pipes[0]);
  888. $timeout = $leak_check ? 300 : (isset($env['TEST_TIMEOUT']) ? $env['TEST_TIMEOUT'] : 60);
  889. while (true) {
  890. /* hide errors from interrupted syscalls */
  891. $r = $pipes;
  892. $w = null;
  893. $e = null;
  894. $n = @stream_select($r, $w, $e, $timeout);
  895. if ($n === false) {
  896. break;
  897. } else if ($n === 0) {
  898. /* timed out */
  899. $data .= "\n ** ERROR: process timed out **\n";
  900. proc_terminate($proc, 9);
  901. return $data;
  902. } else if ($n > 0) {
  903. $line = fread($pipes[1], 8192);
  904. if (strlen($line) == 0) {
  905. /* EOF */
  906. break;
  907. }
  908. $data .= $line;
  909. }
  910. }
  911. $stat = proc_get_status($proc);
  912. if ($stat['signaled']) {
  913. $data .= "\nTermsig=" . $stat['stopsig'];
  914. }
  915. $code = proc_close($proc);
  916. return $data;
  917. }
  918. function run_all_tests($test_files, $env, $redir_tested = null)
  919. {
  920. global $test_results, $failed_tests_file, $php, $test_cnt, $test_idx;
  921. foreach($test_files as $name) {
  922. if (is_array($name)) {
  923. $index = "# $name[1]: $name[0]";
  924. if ($redir_tested) {
  925. $name = $name[0];
  926. }
  927. } else if ($redir_tested) {
  928. $index = "# $redir_tested: $name";
  929. } else {
  930. $index = $name;
  931. }
  932. $test_idx++;
  933. $result = run_test($php, $name, $env);
  934. if (!is_array($name) && $result != 'REDIR') {
  935. $test_results[$index] = $result;
  936. if ($failed_tests_file && ($result == 'XFAILED' || $result == 'FAILED' || $result == 'WARNED' || $result == 'LEAKED')) {
  937. fwrite($failed_tests_file, "$index\n");
  938. }
  939. }
  940. }
  941. }
  942. //
  943. // Show file or result block
  944. //
  945. function show_file_block($file, $block, $section = null)
  946. {
  947. global $cfg;
  948. if ($cfg['show'][$file]) {
  949. if (is_null($section)) {
  950. $section = strtoupper($file);
  951. }
  952. echo "\n========" . $section . "========\n";
  953. echo rtrim($block);
  954. echo "\n========DONE========\n";
  955. }
  956. }
  957. //
  958. // Run an individual test case.
  959. //
  960. function run_test($php, $file, $env)
  961. {
  962. global $log_format, $info_params, $ini_overwrites, $cwd, $PHP_FAILED_TESTS;
  963. global $pass_options, $DETAILED, $IN_REDIRECT, $test_cnt, $test_idx;
  964. global $leak_check, $temp_source, $temp_target, $cfg, $environment;
  965. global $no_clean;
  966. global $valgrind_version;
  967. global $JUNIT;
  968. $temp_filenames = null;
  969. $org_file = $file;
  970. if (isset($env['TEST_PHP_CGI_EXECUTABLE'])) {
  971. $php_cgi = $env['TEST_PHP_CGI_EXECUTABLE'];
  972. }
  973. if (is_array($file)) {
  974. $file = $file[0];
  975. }
  976. if ($DETAILED) echo "
  977. =================
  978. TEST $file
  979. ";
  980. // Load the sections of the test file.
  981. $section_text = array('TEST' => '');
  982. $fp = fopen($file, "rb") or error("Cannot open test file: $file");
  983. $borked = false;
  984. $bork_info = '';
  985. if (!feof($fp)) {
  986. $line = fgets($fp);
  987. if ($line === false) {
  988. $bork_info = "cannot read test";
  989. $borked = true;
  990. }
  991. } else {
  992. $bork_info = "empty test [$file]";
  993. $borked = true;
  994. }
  995. if (!$borked && strncmp('--TEST--', $line, 8)) {
  996. $bork_info = "tests must start with --TEST-- [$file]";
  997. $borked = true;
  998. }
  999. $section = 'TEST';
  1000. $secfile = false;
  1001. $secdone = false;
  1002. while (!feof($fp)) {
  1003. $line = fgets($fp);
  1004. if ($line === false) {
  1005. break;
  1006. }
  1007. // Match the beginning of a section.
  1008. if (preg_match('/^--([_A-Z]+)--/', $line, $r)) {
  1009. $section = $r[1];
  1010. settype($section, 'string');
  1011. if (isset($section_text[$section])) {
  1012. $bork_info = "duplicated $section section";
  1013. $borked = true;
  1014. }
  1015. $section_text[$section] = '';
  1016. $secfile = $section == 'FILE' || $section == 'FILEEOF' || $section == 'FILE_EXTERNAL';
  1017. $secdone = false;
  1018. continue;
  1019. }
  1020. // Add to the section text.
  1021. if (!$secdone) {
  1022. $section_text[$section] .= $line;
  1023. }
  1024. // End of actual test?
  1025. if ($secfile && preg_match('/^===DONE===\s*$/', $line)) {
  1026. $secdone = true;
  1027. }
  1028. }
  1029. // the redirect section allows a set of tests to be reused outside of
  1030. // a given test dir
  1031. if (!$borked) {
  1032. if (@count($section_text['REDIRECTTEST']) == 1) {
  1033. if ($IN_REDIRECT) {
  1034. $borked = true;
  1035. $bork_info = "Can't redirect a test from within a redirected test";
  1036. } else {
  1037. $borked = false;
  1038. }
  1039. } else {
  1040. if (@count($section_text['FILE']) + @count($section_text['FILEEOF']) + @count($section_text['FILE_EXTERNAL']) != 1) {
  1041. $bork_info = "missing section --FILE--";
  1042. $borked = true;
  1043. }
  1044. if (@count($section_text['FILEEOF']) == 1) {
  1045. $section_text['FILE'] = preg_replace("/[\r\n]+$/", '', $section_text['FILEEOF']);
  1046. unset($section_text['FILEEOF']);
  1047. }
  1048. if (@count($section_text['FILE_EXTERNAL']) == 1) {
  1049. // don't allow tests to retrieve files from anywhere but this subdirectory
  1050. $section_text['FILE_EXTERNAL'] = dirname($file) . '/' . trim(str_replace('..', '', $section_text['FILE_EXTERNAL']));
  1051. if (file_exists($section_text['FILE_EXTERNAL'])) {
  1052. $section_text['FILE'] = file_get_contents($section_text['FILE_EXTERNAL'], FILE_BINARY);
  1053. unset($section_text['FILE_EXTERNAL']);
  1054. } else {
  1055. $bork_info = "could not load --FILE_EXTERNAL-- " . dirname($file) . '/' . trim($section_text['FILE_EXTERNAL']);
  1056. $borked = true;
  1057. }
  1058. }
  1059. if ((@count($section_text['EXPECT']) + @count($section_text['EXPECTF']) + @count($section_text['EXPECTREGEX'])) != 1) {
  1060. $bork_info = "missing section --EXPECT--, --EXPECTF-- or --EXPECTREGEX--";
  1061. $borked = true;
  1062. }
  1063. }
  1064. }
  1065. fclose($fp);
  1066. $shortname = str_replace($cwd . '/', '', $file);
  1067. $tested_file = $shortname;
  1068. if ($borked) {
  1069. show_result("BORK", $bork_info, $tested_file);
  1070. $PHP_FAILED_TESTS['BORKED'][] = array (
  1071. 'name' => $file,
  1072. 'test_name' => '',
  1073. 'output' => '',
  1074. 'diff' => '',
  1075. 'info' => "$bork_info [$file]",
  1076. );
  1077. junit_mark_test_as('BORK', $shortname, $tested_file, 0, $bork_info);
  1078. return 'BORKED';
  1079. }
  1080. $tested = trim($section_text['TEST']);
  1081. /* For GET/POST/PUT tests, check if cgi sapi is available and if it is, use it. */
  1082. if (!empty($section_text['GET']) || !empty($section_text['POST']) || !empty($section_text['POST_RAW']) || !empty($section_text['PUT']) || !empty($section_text['COOKIE']) || !empty($section_text['EXPECTHEADERS'])) {
  1083. if (isset($php_cgi)) {
  1084. $old_php = $php;
  1085. $php = $php_cgi . ' -C ';
  1086. } else if (!strncasecmp(PHP_OS, "win", 3) && file_exists(dirname($php) . "/php-cgi.exe")) {
  1087. $old_php = $php;
  1088. $php = realpath(dirname($php) . "/php-cgi.exe") . ' -C ';
  1089. } else {
  1090. if (file_exists(dirname($php) . "/../../sapi/cgi/php-cgi")) {
  1091. $old_php = $php;
  1092. $php = realpath(dirname($php) . "/../../sapi/cgi/php-cgi") . ' -C ';
  1093. } else if (file_exists("./sapi/cgi/php-cgi")) {
  1094. $old_php = $php;
  1095. $php = realpath("./sapi/cgi/php-cgi") . ' -C ';
  1096. } else if (file_exists(dirname($php) . "/php-cgi")) {
  1097. $old_php = $php;
  1098. $php = realpath(dirname($php) . "/php-cgi") . ' -C ';
  1099. } else {
  1100. show_result('SKIP', $tested, $tested_file, "reason: CGI not available");
  1101. junit_mark_test_as('SKIP', $shortname, $tested, 0, 'CGI not available');
  1102. return 'SKIPPED';
  1103. }
  1104. }
  1105. }
  1106. show_test($test_idx, $shortname);
  1107. if (is_array($IN_REDIRECT)) {
  1108. $temp_dir = $test_dir = $IN_REDIRECT['dir'];
  1109. } else {
  1110. $temp_dir = $test_dir = realpath(dirname($file));
  1111. }
  1112. if ($temp_source && $temp_target) {
  1113. $temp_dir = str_replace($temp_source, $temp_target, $temp_dir);
  1114. }
  1115. $main_file_name = basename($file,'phpt');
  1116. $diff_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'diff';
  1117. $log_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'log';
  1118. $exp_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'exp';
  1119. $output_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'out';
  1120. $memcheck_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'mem';
  1121. $sh_filename = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'sh';
  1122. $temp_file = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php';
  1123. $test_file = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'php';
  1124. $temp_skipif = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php';
  1125. $test_skipif = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'skip.php';
  1126. $temp_clean = $temp_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php';
  1127. $test_clean = $test_dir . DIRECTORY_SEPARATOR . $main_file_name . 'clean.php';
  1128. $tmp_post = $temp_dir . DIRECTORY_SEPARATOR . uniqid('/phpt.');
  1129. $tmp_relative_file = str_replace(__DIR__ . DIRECTORY_SEPARATOR, '', $test_file) . 't';
  1130. if ($temp_source && $temp_target) {
  1131. $temp_skipif .= 's';
  1132. $temp_file .= 's';
  1133. $temp_clean .= 's';
  1134. $copy_file = $temp_dir . DIRECTORY_SEPARATOR . basename(is_array($file) ? $file[1] : $file) . '.phps';
  1135. if (!is_dir(dirname($copy_file))) {
  1136. mkdir(dirname($copy_file), 0777, true) or error("Cannot create output directory - " . dirname($copy_file));
  1137. }
  1138. if (isset($section_text['FILE'])) {
  1139. save_text($copy_file, $section_text['FILE']);
  1140. }
  1141. $temp_filenames = array(
  1142. 'file' => $copy_file,
  1143. 'diff' => $diff_filename,
  1144. 'log' => $log_filename,
  1145. 'exp' => $exp_filename,
  1146. 'out' => $output_filename,
  1147. 'mem' => $memcheck_filename,
  1148. 'sh' => $sh_filename,
  1149. 'php' => $temp_file,
  1150. 'skip' => $temp_skipif,
  1151. 'clean'=> $temp_clean);
  1152. }
  1153. if (is_array($IN_REDIRECT)) {
  1154. $tested = $IN_REDIRECT['prefix'] . ' ' . trim($section_text['TEST']);
  1155. $tested_file = $tmp_relative_file;
  1156. }
  1157. // unlink old test results
  1158. @unlink($diff_filename);
  1159. @unlink($log_filename);
  1160. @unlink($exp_filename);
  1161. @unlink($output_filename);
  1162. @unlink($memcheck_filename);
  1163. @unlink($sh_filename);
  1164. @unlink($temp_file);
  1165. @unlink($test_file);
  1166. @unlink($temp_skipif);
  1167. @unlink($test_skipif);
  1168. @unlink($tmp_post);
  1169. @unlink($temp_clean);
  1170. @unlink($test_clean);
  1171. // Reset environment from any previous test.
  1172. $env['REDIRECT_STATUS'] = '';
  1173. $env['QUERY_STRING'] = '';
  1174. $env['PATH_TRANSLATED'] = '';
  1175. $env['SCRIPT_FILENAME'] = '';
  1176. $env['REQUEST_METHOD'] = '';
  1177. $env['CONTENT_TYPE'] = '';
  1178. $env['CONTENT_LENGTH'] = '';
  1179. $env['TZ'] = '';
  1180. if (!empty($section_text['ENV'])) {
  1181. foreach(explode("\n", trim($section_text['ENV'])) as $e) {
  1182. $e = explode('=', trim($e), 2);
  1183. if (!empty($e[0]) && isset($e[1])) {
  1184. $env[$e[0]] = $e[1];
  1185. }
  1186. }
  1187. }
  1188. // Default ini settings
  1189. $ini_settings = array();
  1190. // additional ini overwrites
  1191. //$ini_overwrites[] = 'setting=value';
  1192. settings2array($ini_overwrites, $ini_settings);
  1193. // Any special ini settings
  1194. // these may overwrite the test defaults...
  1195. if (array_key_exists('INI', $section_text)) {
  1196. if (strpos($section_text['INI'], '{PWD}') !== false) {
  1197. $section_text['INI'] = str_replace('{PWD}', dirname($file), $section_text['INI']);
  1198. }
  1199. settings2array(preg_split( "/[\n\r]+/", $section_text['INI']), $ini_settings);
  1200. }
  1201. // Additional required extensions
  1202. if (array_key_exists('EXTENSIONS', $section_text)) {
  1203. $ext_dir=`$php -r 'echo ini_get("extension_dir");'`;
  1204. $extensions = preg_split("/[\n\r]+/", trim($section_text['EXTENSIONS']));
  1205. $loaded = explode(",", `$php -n -r 'echo join(",", get_loaded_extensions());'`);
  1206. foreach ($extensions as $req_ext) {
  1207. if (!in_array($req_ext, $loaded)) {
  1208. $ini_settings['extension'][] = $ext_dir . DIRECTORY_SEPARATOR . $req_ext . '.' . PHP_SHLIB_SUFFIX;
  1209. }
  1210. }
  1211. }
  1212. settings2params($ini_settings);
  1213. // Check if test should be skipped.
  1214. $info = '';
  1215. $warn = false;
  1216. if (array_key_exists('SKIPIF', $section_text)) {
  1217. if (trim($section_text['SKIPIF'])) {
  1218. show_file_block('skip', $section_text['SKIPIF']);
  1219. save_text($test_skipif, $section_text['SKIPIF'], $temp_skipif);
  1220. $extra = substr(PHP_OS, 0, 3) !== "WIN" ?
  1221. "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;": "";
  1222. if ($leak_check) {
  1223. $env['USE_ZEND_ALLOC'] = '0';
  1224. } else {
  1225. $env['USE_ZEND_ALLOC'] = '1';
  1226. }
  1227. junit_start_timer($shortname);
  1228. $output = system_with_timeout("$extra $php $pass_options -q $ini_settings -d display_errors=0 \"$test_skipif\"", $env);
  1229. junit_finish_timer($shortname);
  1230. if (!$cfg['keep']['skip']) {
  1231. @unlink($test_skipif);
  1232. }
  1233. if (!strncasecmp('skip', ltrim($output), 4)) {
  1234. if (preg_match('/^\s*skip\s*(.+)\s*/i', $output, $m)) {
  1235. show_result('SKIP', $tested, $tested_file, "reason: $m[1]", $temp_filenames);
  1236. } else {
  1237. show_result('SKIP', $tested, $tested_file, '', $temp_filenames);
  1238. }
  1239. if (isset($old_php)) {
  1240. $php = $old_php;
  1241. }
  1242. if (!$cfg['keep']['skip']) {
  1243. @unlink($test_skipif);
  1244. }
  1245. $message = !empty($m[1]) ? $m[1] : '';
  1246. junit_mark_test_as('SKIP', $shortname, $tested, null, "<![CDATA[\n$message\n]]>");
  1247. return 'SKIPPED';
  1248. }
  1249. if (!strncasecmp('info', ltrim($output), 4)) {
  1250. if (preg_match('/^\s*info\s*(.+)\s*/i', $output, $m)) {
  1251. $info = " (info: $m[1])";
  1252. }
  1253. }
  1254. if (!strncasecmp('warn', ltrim($output), 4)) {
  1255. if (preg_match('/^\s*warn\s*(.+)\s*/i', $output, $m)) {
  1256. $warn = true; /* only if there is a reason */
  1257. $info = " (warn: $m[1])";
  1258. }
  1259. }
  1260. }
  1261. }
  1262. if (@count($section_text['REDIRECTTEST']) == 1) {
  1263. $test_files = array();
  1264. $IN_REDIRECT = eval($section_text['REDIRECTTEST']);
  1265. $IN_REDIRECT['via'] = "via [$shortname]\n\t";
  1266. $IN_REDIRECT['dir'] = realpath(dirname($file));
  1267. $IN_REDIRECT['prefix'] = trim($section_text['TEST']);
  1268. if (count($IN_REDIRECT['TESTS']) == 1) {
  1269. if (is_array($org_file)) {
  1270. $test_files[] = $org_file[1];
  1271. } else {
  1272. $GLOBALS['test_files'] = $test_files;
  1273. find_files($IN_REDIRECT['TESTS']);
  1274. foreach($GLOBALS['test_files'] as $f) {
  1275. $test_files[] = array($f, $file);
  1276. }
  1277. }
  1278. $test_cnt += @count($test_files) - 1;
  1279. $test_idx--;
  1280. show_redirect_start($IN_REDIRECT['TESTS'], $tested, $tested_file);
  1281. // set up environment
  1282. $redirenv = array_merge($environment, $IN_REDIRECT['ENV']);
  1283. $redirenv['REDIR_TEST_DIR'] = realpath($IN_REDIRECT['TESTS']) . DIRECTORY_SEPARATOR;
  1284. usort($test_files, "test_sort");
  1285. run_all_tests($test_files, $redirenv, $tested);
  1286. show_redirect_ends($IN_REDIRECT['TESTS'], $tested, $tested_file);
  1287. // a redirected test never fails
  1288. $IN_REDIRECT = false;
  1289. junit_mark_test_as('PASS', $shortname, $tested);
  1290. return 'REDIR';
  1291. } else {
  1292. $bork_info = "Redirect info must contain exactly one TEST string to be used as redirect directory.";
  1293. show_result("BORK", $bork_info, '', $temp_filenames);
  1294. $PHP_FAILED_TESTS['BORKED'][] = array (
  1295. 'name' => $file,
  1296. 'test_name' => '',
  1297. 'output' => '',
  1298. 'diff' => '',
  1299. 'info' => "$bork_info [$file]",
  1300. );
  1301. }
  1302. }
  1303. if (is_array($org_file) || @count($section_text['REDIRECTTEST']) == 1) {
  1304. if (is_array($org_file)) {
  1305. $file = $org_file[0];
  1306. }
  1307. $bork_info = "Redirected test did not contain redirection info";
  1308. show_result("BORK", $bork_info, '', $temp_filenames);
  1309. $PHP_FAILED_TESTS['BORKED'][] = array (
  1310. 'name' => $file,
  1311. 'test_name' => '',
  1312. 'output' => '',
  1313. 'diff' => '',
  1314. 'info' => "$bork_info [$file]",
  1315. );
  1316. junit_mark_test_as('BORK', $shortname, $tested, null, $bork_info);
  1317. return 'BORKED';
  1318. }
  1319. // We've satisfied the preconditions - run the test!
  1320. show_file_block('php', $section_text['FILE'], 'TEST');
  1321. save_text($test_file, $section_text['FILE'], $temp_file);
  1322. if (array_key_exists('GET', $section_text)) {
  1323. $query_string = trim($section_text['GET']);
  1324. } else {
  1325. $query_string = '';
  1326. }
  1327. $env['REDIRECT_STATUS'] = '1';
  1328. $env['QUERY_STRING'] = $query_string;
  1329. $env['PATH_TRANSLATED'] = $test_file;
  1330. $env['SCRIPT_FILENAME'] = $test_file;
  1331. if (array_key_exists('COOKIE', $section_text)) {
  1332. $env['HTTP_COOKIE'] = trim($section_text['COOKIE']);
  1333. } else {
  1334. $env['HTTP_COOKIE'] = '';
  1335. }
  1336. $args = isset($section_text['ARGS']) ? ' -- ' . $section_text['ARGS'] : '';
  1337. if (array_key_exists('POST_RAW', $section_text) && !empty($section_text['POST_RAW'])) {
  1338. $post = trim($section_text['POST_RAW']);
  1339. $raw_lines = explode("\n", $post);
  1340. $request = '';
  1341. $started = false;
  1342. foreach ($raw_lines as $line) {
  1343. if (empty($env['CONTENT_TYPE']) && preg_match('/^Content-Type:(.*)/i', $line, $res)) {
  1344. $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
  1345. continue;
  1346. }
  1347. if ($started) {
  1348. $request .= "\n";
  1349. }
  1350. $started = true;
  1351. $request .= $line;
  1352. }
  1353. $env['CONTENT_LENGTH'] = strlen($request);
  1354. $env['REQUEST_METHOD'] = 'POST';
  1355. if (empty($request)) {
  1356. junit_mark_test_as('BORK', $shortname, $tested, null, 'empty $request');
  1357. return 'BORKED';
  1358. }
  1359. save_text($tmp_post, $request);
  1360. $cmd = "$php $pass_options $ini_settings -f \"$test_file\" 2>&1 < \"$tmp_post\"";
  1361. } elseif (array_key_exists('PUT', $section_text) && !empty($section_text['PUT'])) {
  1362. $post = trim($section_text['PUT']);
  1363. $raw_lines = explode("\n", $post);
  1364. $request = '';
  1365. $started = false;
  1366. foreach ($raw_lines as $line) {
  1367. if (empty($env['CONTENT_TYPE']) && preg_match('/^Content-Type:(.*)/i', $line, $res)) {
  1368. $env['CONTENT_TYPE'] = trim(str_replace("\r", '', $res[1]));
  1369. continue;
  1370. }
  1371. if ($started) {
  1372. $request .= "\n";
  1373. }
  1374. $started = true;
  1375. $request .= $line;
  1376. }
  1377. $env['CONTENT_LENGTH'] = strlen($request);
  1378. $env['REQUEST_METHOD'] = 'PUT';
  1379. if (empty($request)) {
  1380. junit_mark_test_as('BORK', $shortname, $tested, null, 'empty $request');
  1381. return 'BORKED';
  1382. }
  1383. save_text($tmp_post, $request);
  1384. $cmd = "$php $pass_options $ini_settings -f \"$test_file\" 2>&1 < \"$tmp_post\"";
  1385. } else if (array_key_exists('POST', $section_text) && !empty($section_text['POST'])) {
  1386. $post = trim($section_text['POST']);
  1387. if (array_key_exists('GZIP_POST', $section_text) && function_exists('gzencode')) {
  1388. $post = gzencode($post, 9, FORCE_GZIP);
  1389. $env['HTTP_CONTENT_ENCODING'] = 'gzip';
  1390. } else if (array_key_exists('DEFLATE_POST', $section_text) && function_exists('gzcompress')) {
  1391. $post = gzcompress($post, 9);
  1392. $env['HTTP_CONTENT_ENCODING'] = 'deflate';
  1393. }
  1394. save_text($tmp_post, $post);
  1395. $content_length = strlen($post);
  1396. $env['REQUEST_METHOD'] = 'POST';
  1397. $env['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  1398. $env['CONTENT_LENGTH'] = $content_length;
  1399. $cmd = "$php $pass_options $ini_settings -f \"$test_file\" 2>&1 < \"$tmp_post\"";
  1400. } else {
  1401. $env['REQUEST_METHOD'] = 'GET';
  1402. $env['CONTENT_TYPE'] = '';
  1403. $env['CONTENT_LENGTH'] = '';
  1404. $cmd = "$php $pass_options $ini_settings -f \"$test_file\" $args 2>&1";
  1405. }
  1406. if ($leak_check) {
  1407. $env['USE_ZEND_ALLOC'] = '0';
  1408. if ($valgrind_version >= 330) {
  1409. /* valgrind 3.3.0+ doesn't have --log-file-exactly option */
  1410. $cmd = "valgrind -q --tool=memcheck --trace-children=yes --log-file=$memcheck_filename $cmd";
  1411. } else {
  1412. $cmd = "valgrind -q --tool=memcheck --trace-children=yes --log-file-exactly=$memcheck_filename $cmd";
  1413. }
  1414. } else {
  1415. $env['USE_ZEND_ALLOC'] = '1';
  1416. }
  1417. if ($DETAILED) echo "
  1418. CONTENT_LENGTH = " . $env['CONTENT_LENGTH'] . "
  1419. CONTENT_TYPE = " . $env['CONTENT_TYPE'] . "
  1420. PATH_TRANSLATED = " . $env['PATH_TRANSLATED'] . "
  1421. QUERY_STRING = " . $env['QUERY_STRING'] . "
  1422. REDIRECT_STATUS = " . $env['REDIRECT_STATUS'] . "
  1423. REQUEST_METHOD = " . $env['REQUEST_METHOD'] . "
  1424. SCRIPT_FILENAME = " . $env['SCRIPT_FILENAME'] . "
  1425. HTTP_COOKIE = " . $env['HTTP_COOKIE'] . "
  1426. COMMAND $cmd
  1427. ";
  1428. junit_start_timer($shortname);
  1429. $out = system_with_timeout($cmd, $env, isset($section_text['STDIN']) ? $section_text['STDIN'] : null);
  1430. junit_finish_timer($shortname);
  1431. if (array_key_exists('CLEAN', $section_text) && (!$no_clean || $cfg['keep']['clean'])) {
  1432. if (trim($section_text['CLEAN'])) {
  1433. show_file_block('clean', $section_text['CLEAN']);
  1434. save_text($test_clean, trim($section_text['CLEAN']), $temp_clean);
  1435. if (!$no_clean) {
  1436. $clean_params = array();
  1437. settings2array($ini_overwrites, $clean_params);
  1438. settings2params($clean_params);
  1439. $extra = substr(PHP_OS, 0, 3) !== "WIN" ?
  1440. "unset REQUEST_METHOD; unset QUERY_STRING; unset PATH_TRANSLATED; unset SCRIPT_FILENAME; unset REQUEST_METHOD;": "";
  1441. system_with_timeout("$extra $php $pass_options -q $clean_params \"$test_clean\"", $env);
  1442. }
  1443. if (!$cfg['keep']['clean']) {
  1444. @unlink($test_clean);
  1445. }
  1446. }
  1447. }
  1448. @unlink($tmp_post);
  1449. $leaked = false;
  1450. $passed = false;
  1451. if ($leak_check) { // leak check
  1452. $leaked = filesize($memcheck_filename) > 0;
  1453. if (!$leaked) {
  1454. @unlink($memcheck_filename);
  1455. }
  1456. }
  1457. // Does the output match what is expected?
  1458. $output = preg_replace("/\r\n/", "\n", trim($out));
  1459. /* when using CGI, strip the headers from the output */
  1460. $headers = "";
  1461. if (isset($old_php) && preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $out, $match)) {
  1462. $output = trim($match[2]);
  1463. $rh = preg_split("/[\n\r]+/", $match[1]);
  1464. $headers = array();
  1465. foreach ($rh as $line) {
  1466. if (strpos($line, ':') !== false) {
  1467. $line = explode(':', $line, 2);
  1468. $headers[trim($line[0])] = trim($line[1]);
  1469. }
  1470. }
  1471. }
  1472. $failed_headers = false;
  1473. if (isset($section_text['EXPECTHEADERS'])) {
  1474. $want = array();
  1475. $wanted_headers = array();
  1476. $lines = preg_split("/[\n\r]+/", $section_text['EXPECTHEADERS']);
  1477. foreach($lines as $line) {
  1478. if (strpos($line, ':') !== false) {
  1479. $line = explode(':', $line, 2);
  1480. $want[trim($line[0])] = trim($line[1]);
  1481. $wanted_headers[] = trim($line[0]) . ': ' . trim($line[1]);
  1482. }
  1483. }
  1484. $org_headers = $headers;
  1485. $headers = array();
  1486. $output_headers = array();
  1487. foreach($want as $k => $v) {
  1488. if (isset($org_headers[$k])) {
  1489. $headers = $org_headers[$k];
  1490. $output_headers[] = $k . ': ' . $org_headers[$k];
  1491. }
  1492. if (!isset($org_headers[$k]) || $org_headers[$k] != $v) {
  1493. $failed_headers = true;
  1494. }
  1495. }
  1496. ksort($wanted_headers);
  1497. $wanted_headers = join("\n", $wanted_headers);
  1498. ksort($output_headers);
  1499. $output_headers = join("\n", $output_headers);
  1500. }
  1501. show_file_block('out', $output);
  1502. if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
  1503. if (isset($section_text['EXPECTF'])) {
  1504. $wanted = trim($section_text['EXPECTF']);
  1505. } else {
  1506. $wanted = trim($section_text['EXPECTREGEX']);
  1507. }
  1508. show_file_block('exp', $wanted);
  1509. $wanted_re = preg_replace('/\r\n/', "\n", $wanted);
  1510. if (isset($section_text['EXPECTF'])) {
  1511. // do preg_quote, but miss out any %r delimited sections
  1512. $temp = "";
  1513. $r = "%r";
  1514. $startOffset = 0;
  1515. $length = strlen($wanted_re);
  1516. while($startOffset < $length) {
  1517. $start = strpos($wanted_re, $r, $startOffset);
  1518. if ($start !== false) {
  1519. // we have found a start tag
  1520. $end = strpos($wanted_re, $r, $start+2);
  1521. if ($end === false) {
  1522. // unbalanced tag, ignore it.
  1523. $end = $start = $length;
  1524. }
  1525. } else {
  1526. // no more %r sections
  1527. $start = $end = $length;
  1528. }
  1529. // quote a non re portion of the string
  1530. $temp = $temp . preg_quote(substr($wanted_re, $startOffset, ($start - $startOffset)), '/');
  1531. // add the re unquoted.
  1532. if ($end > $start) {
  1533. $temp = $temp . '(' . substr($wanted_re, $start+2, ($end - $start-2)). ')';
  1534. }
  1535. $startOffset = $end + 2;
  1536. }
  1537. $wanted_re = $temp;
  1538. $wanted_re = str_replace(
  1539. array('%binary_string_optional%'),
  1540. 'string',
  1541. $wanted_re
  1542. );
  1543. $wanted_re = str_replace(
  1544. array('%unicode_string_optional%'),
  1545. 'string',
  1546. $wanted_re
  1547. );
  1548. $wanted_re = str_replace(
  1549. array('%unicode\|string%', '%string\|unicode%'),
  1550. 'string',
  1551. $wanted_re
  1552. );
  1553. $wanted_re = str_replace(
  1554. array('%u\|b%', '%b\|u%'),
  1555. '',
  1556. $wanted_re
  1557. );
  1558. // Stick to basics
  1559. $wanted_re = str_replace('%e', '\\' . DIRECTORY_SEPARATOR, $wanted_re);
  1560. $wanted_re = str_replace('%s', '[^\r\n]+', $wanted_re);
  1561. $wanted_re = str_replace('%S', '[^\r\n]*', $wanted_re);
  1562. $wanted_re = str_replace('%a', '.+', $wanted_re);
  1563. $wanted_re = str_replace('%A', '.*', $wanted_re);
  1564. $wanted_re = str_replace('%w', '\s*', $wanted_re);
  1565. $wanted_re = str_replace('%i', '[+-]?\d+', $wanted_re);
  1566. $wanted_re = str_replace('%d', '\d+', $wanted_re);
  1567. $wanted_re = str_replace('%x', '[0-9a-fA-F]+', $wanted_re);
  1568. $wanted_re = str_replace('%f', '[+-]?\.?\d+\.?\d*(?:[Ee][+-]?\d+)?', $wanted_re);
  1569. $wanted_re = str_replace('%c', '.', $wanted_re);
  1570. // %f allows two points "-.0.0" but that is the best *simple* expression
  1571. }
  1572. /* DEBUG YOUR REGEX HERE
  1573. var_dump($wanted_re);
  1574. print(str_repeat('=', 80) . "\n");
  1575. var_dump($output);
  1576. */
  1577. if (preg_match("/^$wanted_re\$/s", $output)) {
  1578. $passed = true;
  1579. if (!$cfg['keep']['php']) {
  1580. @unlink($test_file);
  1581. }
  1582. if (isset($old_php)) {
  1583. $php = $old_php;
  1584. }
  1585. if (!$leaked && !$failed_headers) {
  1586. if (isset($section_text['XFAIL'] )) {
  1587. $warn = true;
  1588. $info = " (warn: XFAIL section but test passes)";
  1589. }else {
  1590. show_result("PASS", $tested, $tested_file, '', $temp_filenames);
  1591. junit_mark_test_as('PASS', $shortname, $tested);
  1592. return 'PASSED';
  1593. }
  1594. }
  1595. }
  1596. } else {
  1597. $wanted = trim($section_text['EXPECT']);
  1598. $wanted = preg_replace('/\r\n/',"\n", $wanted);
  1599. show_file_block('exp', $wanted);
  1600. // compare and leave on success
  1601. if (!strcmp($output, $wanted)) {
  1602. $passed = true;
  1603. if (!$cfg['keep']['php']) {
  1604. @unlink($test_file);
  1605. }
  1606. if (isset($old_php)) {
  1607. $php = $old_php;
  1608. }
  1609. if (!$leaked && !$failed_headers) {
  1610. if (isset($section_text['XFAIL'] )) {
  1611. $warn = true;
  1612. $info = " (warn: XFAIL section but test passes)";
  1613. }else {
  1614. show_result("PASS", $tested, $tested_file, '', $temp_filenames);
  1615. junit_mark_test_as('PASS', $shortname, $tested);
  1616. return 'PASSED';
  1617. }
  1618. }
  1619. }
  1620. $wanted_re = null;
  1621. }
  1622. // Test failed so we need to report details.
  1623. if ($failed_headers) {
  1624. $passed = false;
  1625. $wanted = $wanted_headers . "\n--HEADERS--\n" . $wanted;
  1626. $output = $output_headers . "\n--HEADERS--\n" . $output;
  1627. if (isset($wanted_re)) {
  1628. $wanted_re = preg_quote($wanted_headers . "\n--HEADERS--\n", '/') . $wanted_re;
  1629. }
  1630. }
  1631. if ($leaked) {
  1632. $restype[] = 'LEAK';
  1633. }
  1634. if ($warn) {
  1635. $restype[] = 'WARN';
  1636. }
  1637. if (!$passed) {
  1638. if (isset($section_text['XFAIL'])) {
  1639. $restype[] = 'XFAIL';
  1640. $info = ' XFAIL REASON: ' . rtrim($section_text['XFAIL']);
  1641. } else {
  1642. $restype[] = 'FAIL';
  1643. }
  1644. }
  1645. if (!$passed) {
  1646. // write .exp
  1647. if (strpos($log_format, 'E') !== false && file_put_contents($exp_filename, $wanted, FILE_BINARY) === false) {
  1648. error("Cannot create expected test output - $exp_filename");
  1649. }
  1650. // write .out
  1651. if (strpos($log_format, 'O') !== false && file_put_contents($output_filename, $output, FILE_BINARY) === false) {
  1652. error("Cannot create test output - $output_filename");
  1653. }
  1654. // write .diff
  1655. $diff = generate_diff($wanted, $wanted_re, $output);
  1656. if (is_array($IN_REDIRECT)) {
  1657. $diff = "# original source file: $shortname\n" . $diff;
  1658. }
  1659. show_file_block('diff', $diff);
  1660. if (strpos($log_format, 'D') !== false && file_put_contents($diff_filename, $diff, FILE_BINARY) === false) {
  1661. error("Cannot create test diff - $diff_filename");
  1662. }
  1663. // write .sh
  1664. if (strpos($log_format, 'S') !== false && file_put_contents($sh_filename, "#!/bin/sh
  1665. {$cmd}
  1666. ", FILE_BINARY) === false) {
  1667. error("Cannot create test shell script - $sh_filename");
  1668. }
  1669. chmod($sh_filename, 0755);
  1670. // write .log
  1671. if (strpos($log_format, 'L') !== false && file_put_contents($log_filename, "
  1672. ---- EXPECTED OUTPUT
  1673. $wanted
  1674. ---- ACTUAL OUTPUT
  1675. $output
  1676. ---- FAILED
  1677. ", FILE_BINARY) === false) {
  1678. error("Cannot create test log - $log_filename");
  1679. error_report($file, $log_filename, $tested);
  1680. }
  1681. }
  1682. show_result(implode('&', $restype), $tested, $tested_file, $info, $temp_filenames);
  1683. foreach ($restype as $type) {
  1684. $PHP_FAILED_TESTS[$type.'ED'][] = array (
  1685. 'name' => $file,
  1686. 'test_name' => (is_array($IN_REDIRECT) ? $IN_REDIRECT['via'] : '') . $tested . " [$tested_file]",
  1687. 'output' => $output_filename,
  1688. 'diff' => $diff_filename,
  1689. 'info' => $info,
  1690. );
  1691. }
  1692. if (isset($old_php)) {
  1693. $php = $old_php;
  1694. }
  1695. junit_mark_test_as($restype, str_replace($cwd . '/', '', $tested_file), $tested, null, $info, "<![CDATA[\n " . preg_replace('/\e/', '<esc>', $diff) . "\n]]>");
  1696. return $restype[0] . 'ED';
  1697. }
  1698. function comp_line($l1, $l2, $is_reg)
  1699. {
  1700. if ($is_reg) {
  1701. return preg_match('/^'. $l1 . '$/s', $l2);
  1702. } else {
  1703. return !strcmp($l1, $l2);
  1704. }
  1705. }
  1706. function count_array_diff($ar1, $ar2, $is_reg, $w, $idx1, $idx2, $cnt1, $cnt2, $steps)
  1707. {
  1708. $equal = 0;
  1709. while ($idx1 < $cnt1 && $idx2 < $cnt2 && comp_line($ar1[$idx1], $ar2[$idx2], $is_reg)) {
  1710. $idx1++;
  1711. $idx2++;
  1712. $equal++;
  1713. $steps--;
  1714. }
  1715. if (--$steps > 0) {
  1716. $eq1 = 0;
  1717. $st = $steps / 2;
  1718. for ($ofs1 = $idx1 + 1; $ofs1 < $cnt1 && $st-- > 0; $ofs1++) {
  1719. $eq = @count_array_diff($ar1, $ar2, $is_reg, $w, $ofs1, $idx2, $cnt1, $cnt2, $st);
  1720. if ($eq > $eq1) {
  1721. $eq1 = $eq;
  1722. }
  1723. }
  1724. $eq2 = 0;
  1725. $st = $steps;
  1726. for ($ofs2 = $idx2 + 1; $ofs2 < $cnt2 && $st-- > 0; $ofs2++) {
  1727. $eq = @count_array_diff($ar1, $ar2, $is_reg, $w, $idx1, $ofs2, $cnt1, $cnt2, $st);
  1728. if ($eq > $eq2) {
  1729. $eq2 = $eq;
  1730. }
  1731. }
  1732. if ($eq1 > $eq2) {
  1733. $equal += $eq1;
  1734. } else if ($eq2 > 0) {
  1735. $equal += $eq2;
  1736. }
  1737. }
  1738. return $equal;
  1739. }
  1740. function generate_array_diff($ar1, $ar2, $is_reg, $w)
  1741. {
  1742. $idx1 = 0; $ofs1 = 0; $cnt1 = @count($ar1);
  1743. $idx2 = 0; $ofs2 = 0; $cnt2 = @count($ar2);
  1744. $diff = array();
  1745. $old1 = array();
  1746. $old2 = array();
  1747. while ($idx1 < $cnt1 && $idx2 < $cnt2) {
  1748. if (comp_line($ar1[$idx1], $ar2[$idx2], $is_reg)) {
  1749. $idx1++;
  1750. $idx2++;
  1751. continue;
  1752. } else {
  1753. $c1 = @count_array_diff($ar1, $ar2, $is_reg, $w, $idx1+1, $idx2, $cnt1, $cnt2, 10);
  1754. $c2 = @count_array_diff($ar1, $ar2, $is_reg, $w, $idx1, $idx2+1, $cnt1, $cnt2, 10);
  1755. if ($c1 > $c2) {
  1756. $old1[$idx1] = sprintf("%03d- ", $idx1+1) . $w[$idx1++];
  1757. $last = 1;
  1758. } else if ($c2 > 0) {
  1759. $old2[$idx2] = sprintf("%03d+ ", $idx2+1) . $ar2[$idx2++];
  1760. $last = 2;
  1761. } else {
  1762. $old1[$idx1] = sprintf("%03d- ", $idx1+1) . $w[$idx1++];
  1763. $old2[$idx2] = sprintf("%03d+ ", $idx2+1) . $ar2[$idx2++];
  1764. }
  1765. }
  1766. }
  1767. reset($old1); $k1 = key($old1); $l1 = -2;
  1768. reset($old2); $k2 = key($old2); $l2 = -2;
  1769. while ($k1 !== null || $k2 !== null) {
  1770. if ($k1 == $l1 + 1 || $k2 === null) {
  1771. $l1 = $k1;
  1772. $diff[] = current($old1);
  1773. $k1 = next($old1) ? key($old1) : null;
  1774. } else if ($k2 == $l2 + 1 || $k1 === null) {
  1775. $l2 = $k2;
  1776. $diff[] = current($old2);
  1777. $k2 = next($old2) ? key($old2) : null;
  1778. } else if ($k1 < $k2) {
  1779. $l1 = $k1;
  1780. $diff[] = current($old1);
  1781. $k1 = next($old1) ? key($old1) : null;
  1782. } else {
  1783. $l2 = $k2;
  1784. $diff[] = current($old2);
  1785. $k2 = next($old2) ? key($old2) : null;
  1786. }
  1787. }
  1788. while ($idx1 < $cnt1) {
  1789. $diff[] = sprintf("%03d- ", $idx1 + 1) . $w[$idx1++];
  1790. }
  1791. while ($idx2 < $cnt2) {
  1792. $diff[] = sprintf("%03d+ ", $idx2 + 1) . $ar2[$idx2++];
  1793. }
  1794. return $diff;
  1795. }
  1796. function generate_diff($wanted, $wanted_re, $output)
  1797. {
  1798. $w = explode("\n", $wanted);
  1799. $o = explode("\n", $output);
  1800. $r = is_null($wanted_re) ? $w : explode("\n", $wanted_re);
  1801. $diff = generate_array_diff($r, $o, !is_null($wanted_re), $w);
  1802. return implode("\r\n", $diff);
  1803. }
  1804. function error($message)
  1805. {
  1806. echo "ERROR: {$message}\n";
  1807. exit(1);
  1808. }
  1809. function settings2array($settings, &$ini_settings)
  1810. {
  1811. foreach($settings as $setting) {
  1812. if (strpos($setting, '=') !== false) {
  1813. $setting = explode("=", $setting, 2);
  1814. $name = trim($setting[0]);
  1815. $value = trim($setting[1]);
  1816. if ($name == 'extension') {
  1817. if (!isset($ini_settings[$name])) {
  1818. $ini_settings[$name] = array();
  1819. }
  1820. $ini_settings[$name][] = $value;
  1821. } else {
  1822. $ini_settings[$name] = $value;
  1823. }
  1824. }
  1825. }
  1826. }
  1827. function settings2params(&$ini_settings)
  1828. {
  1829. $settings = '';
  1830. foreach($ini_settings as $name => $value) {
  1831. if (is_array($value)) {
  1832. foreach($value as $val) {
  1833. $val = addslashes($val);
  1834. $settings .= " -d \"$name=$val\"";
  1835. }
  1836. } else {
  1837. if (substr(PHP_OS, 0, 3) == "WIN" && !empty($value) && $value{0} == '"') {
  1838. $len = strlen($value);
  1839. if ($value{$len - 1} == '"') {
  1840. $value{0} = "'";
  1841. $value{$len - 1} = "'";
  1842. }
  1843. } else {
  1844. $value = addslashes($value);
  1845. }
  1846. $settings .= " -d \"$name=$value\"";
  1847. }
  1848. }
  1849. $ini_settings = $settings;
  1850. }
  1851. function compute_summary()
  1852. {
  1853. global $n_total, $test_results, $ignored_by_ext, $sum_results, $percent_results;
  1854. $n_total = count($test_results);
  1855. $n_total += $ignored_by_ext;
  1856. $sum_results = array(
  1857. 'PASSED' => 0,
  1858. 'WARNED' => 0,
  1859. 'SKIPPED' => 0,
  1860. 'FAILED' => 0,
  1861. 'BORKED' => 0,
  1862. 'LEAKED' => 0,
  1863. 'XFAILED' => 0
  1864. );
  1865. foreach ($test_results as $v) {
  1866. $sum_results[$v]++;
  1867. }
  1868. $sum_results['SKIPPED'] += $ignored_by_ext;
  1869. $percent_results = array();
  1870. while (list($v, $n) = each($sum_results)) {
  1871. $percent_results[$v] = (100.0 * $n) / $n_total;
  1872. }
  1873. }
  1874. function get_summary($show_ext_summary, $show_html)
  1875. {
  1876. global $exts_skipped, $exts_tested, $n_total, $sum_results, $percent_results, $end_time, $start_time, $failed_test_summary, $PHP_FAILED_TESTS, $leak_check;
  1877. $x_total = $n_total - $sum_results['SKIPPED'] - $sum_results['BORKED'];
  1878. if ($x_total) {
  1879. $x_warned = (100.0 * $sum_results['WARNED']) / $x_total;
  1880. $x_failed = (100.0 * $sum_results['FAILED']) / $x_total;
  1881. $x_xfailed = (100.0 * $sum_results['XFAILED']) / $x_total;
  1882. $x_leaked = (100.0 * $sum_results['LEAKED']) / $x_total;
  1883. $x_passed = (100.0 * $sum_results['PASSED']) / $x_total;
  1884. } else {
  1885. $x_warned = $x_failed = $x_passed = $x_leaked = $x_xfailed = 0;
  1886. }
  1887. $summary = '';
  1888. if ($show_html) {
  1889. $summary .= "<pre>\n";
  1890. }
  1891. if ($show_ext_summary) {
  1892. $summary .= '
  1893. =====================================================================
  1894. TEST RESULT SUMMARY
  1895. ---------------------------------------------------------------------
  1896. Exts skipped : ' . sprintf('%4d', $exts_skipped) . '
  1897. Exts tested : ' . sprintf('%4d', $exts_tested) . '
  1898. ---------------------------------------------------------------------
  1899. ';
  1900. }
  1901. $summary .= '
  1902. Number of tests : ' . sprintf('%4d', $n_total) . ' ' . sprintf('%8d', $x_total);
  1903. if ($sum_results['BORKED']) {
  1904. $summary .= '
  1905. Tests borked : ' . sprintf('%4d (%5.1f%%)', $sum_results['BORKED'], $percent_results['BORKED']) . ' --------';
  1906. }
  1907. $summary .= '
  1908. Tests skipped : ' . sprintf('%4d (%5.1f%%)', $sum_results['SKIPPED'], $percent_results['SKIPPED']) . ' --------
  1909. Tests warned : ' . sprintf('%4d (%5.1f%%)', $sum_results['WARNED'], $percent_results['WARNED']) . ' ' . sprintf('(%5.1f%%)', $x_warned) . '
  1910. Tests failed : ' . sprintf('%4d (%5.1f%%)', $sum_results['FAILED'], $percent_results['FAILED']) . ' ' . sprintf('(%5.1f%%)', $x_failed) . '
  1911. Expected fail : ' . sprintf('%4d (%5.1f%%)', $sum_results['XFAILED'], $percent_results['XFAILED']) . ' ' . sprintf('(%5.1f%%)', $x_xfailed);
  1912. if ($leak_check) {
  1913. $summary .= '
  1914. Tests leaked : ' . sprintf('%4d (%5.1f%%)', $sum_results['LEAKED'], $percent_results['LEAKED']) . ' ' . sprintf('(%5.1f%%)', $x_leaked);
  1915. }
  1916. $summary .= '
  1917. Tests passed : ' . sprintf('%4d (%5.1f%%)', $sum_results['PASSED'], $percent_results['PASSED']) . ' ' . sprintf('(%5.1f%%)', $x_passed) . '
  1918. ---------------------------------------------------------------------
  1919. Time taken : ' . sprintf('%4d seconds', $end_time - $start_time) . '
  1920. =====================================================================
  1921. ';
  1922. $failed_test_summary = '';
  1923. if (count($PHP_FAILED_TESTS['XFAILED'])) {
  1924. $failed_test_summary .= '
  1925. =====================================================================
  1926. EXPECTED FAILED TEST SUMMARY
  1927. ---------------------------------------------------------------------
  1928. ';
  1929. foreach ($PHP_FAILED_TESTS['XFAILED'] as $failed_test_data) {
  1930. $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
  1931. }
  1932. $failed_test_summary .= "=====================================================================\n";
  1933. }
  1934. if (count($PHP_FAILED_TESTS['BORKED'])) {
  1935. $failed_test_summary .= '
  1936. =====================================================================
  1937. BORKED TEST SUMMARY
  1938. ---------------------------------------------------------------------
  1939. ';
  1940. foreach ($PHP_FAILED_TESTS['BORKED'] as $failed_test_data) {
  1941. $failed_test_summary .= $failed_test_data['info'] . "\n";
  1942. }
  1943. $failed_test_summary .= "=====================================================================\n";
  1944. }
  1945. if (count($PHP_FAILED_TESTS['FAILED'])) {
  1946. $failed_test_summary .= '
  1947. =====================================================================
  1948. FAILED TEST SUMMARY
  1949. ---------------------------------------------------------------------
  1950. ';
  1951. foreach ($PHP_FAILED_TESTS['FAILED'] as $failed_test_data) {
  1952. $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
  1953. }
  1954. $failed_test_summary .= "=====================================================================\n";
  1955. }
  1956. if (count($PHP_FAILED_TESTS['WARNED'])) {
  1957. $failed_test_summary .= '
  1958. =====================================================================
  1959. WARNED TEST SUMMARY
  1960. ---------------------------------------------------------------------
  1961. ';
  1962. foreach ($PHP_FAILED_TESTS['WARNED'] as $failed_test_data) {
  1963. $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
  1964. }
  1965. $failed_test_summary .= "=====================================================================\n";
  1966. }
  1967. if (count($PHP_FAILED_TESTS['LEAKED'])) {
  1968. $failed_test_summary .= '
  1969. =====================================================================
  1970. LEAKED TEST SUMMARY
  1971. ---------------------------------------------------------------------
  1972. ';
  1973. foreach ($PHP_FAILED_TESTS['LEAKED'] as $failed_test_data) {
  1974. $failed_test_summary .= $failed_test_data['test_name'] . $failed_test_data['info'] . "\n";
  1975. }
  1976. $failed_test_summary .= "=====================================================================\n";
  1977. }
  1978. if ($failed_test_summary && !getenv('NO_PHPTEST_SUMMARY')) {
  1979. $summary .= $failed_test_summary;
  1980. }
  1981. if ($show_html) {
  1982. $summary .= "</pre>";
  1983. }
  1984. return $summary;
  1985. }
  1986. function show_start($start_time)
  1987. {
  1988. global $html_output, $html_file;
  1989. if ($html_output) {
  1990. fwrite($html_file, "<h2>Time Start: " . date('Y-m-d H:i:s', $start_time) . "</h2>\n");
  1991. fwrite($html_file, "<table>\n");
  1992. }
  1993. echo "TIME START " . date('Y-m-d H:i:s', $start_time) . "\n=====================================================================\n";
  1994. }
  1995. function show_end($end_time)
  1996. {
  1997. global $html_output, $html_file;
  1998. if ($html_output) {
  1999. fwrite($html_file, "</table>\n");
  2000. fwrite($html_file, "<h2>Time End: " . date('Y-m-d H:i:s', $end_time) . "</h2>\n");
  2001. }
  2002. echo "=====================================================================\nTIME END " . date('Y-m-d H:i:s', $end_time) . "\n";
  2003. }
  2004. function show_summary()
  2005. {
  2006. global $html_output, $html_file;
  2007. if ($html_output) {
  2008. fwrite($html_file, "<hr/>\n" . get_summary(true, true));
  2009. }
  2010. echo get_summary(true, false);
  2011. }
  2012. function show_redirect_start($tests, $tested, $tested_file)
  2013. {
  2014. global $html_output, $html_file, $line_length, $SHOW_ONLY_GROUPS;
  2015. if ($html_output) {
  2016. fwrite($html_file, "<tr><td colspan='3'>---&gt; $tests ($tested [$tested_file]) begin</td></tr>\n");
  2017. }
  2018. if (!$SHOW_ONLY_GROUPS || in_array('REDIRECT', $SHOW_ONLY_GROUPS)) {
  2019. echo "REDIRECT $tests ($tested [$tested_file]) begin\n";
  2020. } else {
  2021. // Write over the last line to avoid random trailing chars on next echo
  2022. echo str_repeat(" ", $line_length), "\r";
  2023. }
  2024. }
  2025. function show_redirect_ends($tests, $tested, $tested_file)
  2026. {
  2027. global $html_output, $html_file, $line_length, $SHOW_ONLY_GROUPS;
  2028. if ($html_output) {
  2029. fwrite($html_file, "<tr><td colspan='3'>---&gt; $tests ($tested [$tested_file]) done</td></tr>\n");
  2030. }
  2031. if (!$SHOW_ONLY_GROUPS || in_array('REDIRECT', $SHOW_ONLY_GROUPS)) {
  2032. echo "REDIRECT $tests ($tested [$tested_file]) done\n";
  2033. } else {
  2034. // Write over the last line to avoid random trailing chars on next echo
  2035. echo str_repeat(" ", $line_length), "\r";
  2036. }
  2037. }
  2038. function show_test($test_idx, $shortname)
  2039. {
  2040. global $test_cnt;
  2041. global $line_length;
  2042. $str = "TEST $test_idx/$test_cnt [$shortname]\r";
  2043. $line_length = strlen($str);
  2044. echo $str;
  2045. flush();
  2046. }
  2047. function show_result($result, $tested, $tested_file, $extra = '', $temp_filenames = null)
  2048. {
  2049. global $html_output, $html_file, $temp_target, $temp_urlbase, $line_length, $SHOW_ONLY_GROUPS;
  2050. if (!$SHOW_ONLY_GROUPS || in_array($result, $SHOW_ONLY_GROUPS)) {
  2051. echo "$result $tested [$tested_file] $extra\n";
  2052. } else {
  2053. // Write over the last line to avoid random trailing chars on next echo
  2054. echo str_repeat(" ", $line_length), "\r";
  2055. }
  2056. if ($html_output) {
  2057. if (isset($temp_filenames['file']) && file_exists($temp_filenames['file'])) {
  2058. $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['file']);
  2059. $tested = "<a href='$url'>$tested</a>";
  2060. }
  2061. if (isset($temp_filenames['skip']) && file_exists($temp_filenames['skip'])) {
  2062. if (empty($extra)) {
  2063. $extra = "skipif";
  2064. }
  2065. $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['skip']);
  2066. $extra = "<a href='$url'>$extra</a>";
  2067. } else if (empty($extra)) {
  2068. $extra = "&nbsp;";
  2069. }
  2070. if (isset($temp_filenames['diff']) && file_exists($temp_filenames['diff'])) {
  2071. $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['diff']);
  2072. $diff = "<a href='$url'>diff</a>";
  2073. } else {
  2074. $diff = "&nbsp;";
  2075. }
  2076. if (isset($temp_filenames['mem']) && file_exists($temp_filenames['mem'])) {
  2077. $url = str_replace($temp_target, $temp_urlbase, $temp_filenames['mem']);
  2078. $mem = "<a href='$url'>leaks</a>";
  2079. } else {
  2080. $mem = "&nbsp;";
  2081. }
  2082. fwrite($html_file,
  2083. "<tr>" .
  2084. "<td>$result</td>" .
  2085. "<td>$tested</td>" .
  2086. "<td>$extra</td>" .
  2087. "<td>$diff</td>" .
  2088. "<td>$mem</td>" .
  2089. "</tr>\n");
  2090. }
  2091. }
  2092. function junit_init() {
  2093. // Check whether a junit log is wanted.
  2094. $JUNIT = getenv('TEST_PHP_JUNIT');
  2095. if (empty($JUNIT)) {
  2096. $JUNIT = FALSE;
  2097. } elseif (!$fp = fopen($JUNIT, 'w')) {
  2098. error("Failed to open $JUNIT for writing.");
  2099. } else {
  2100. $JUNIT = array(
  2101. 'fp' => $fp,
  2102. 'name' => 'php-src',
  2103. 'test_total' => 0,
  2104. 'test_pass' => 0,
  2105. 'test_fail' => 0,
  2106. 'test_error' => 0,
  2107. 'test_skip' => 0,
  2108. 'execution_time'=> 0,
  2109. 'suites' => array(),
  2110. 'files' => array()
  2111. );
  2112. }
  2113. $GLOBALS['JUNIT'] = $JUNIT;
  2114. }
  2115. function junit_save_xml() {
  2116. global $JUNIT;
  2117. if (!junit_enabled()) return;
  2118. $xml = '<?xml version="1.0" encoding="UTF-8"?>'. PHP_EOL .
  2119. '<testsuites>' . PHP_EOL;
  2120. $xml .= junit_get_suite_xml();
  2121. $xml .= '</testsuites>';
  2122. fwrite($JUNIT['fp'], $xml);
  2123. }
  2124. function junit_get_suite_xml($suite_name = '') {
  2125. global $JUNIT;
  2126. $suite = $suite_name ? $JUNIT['suites'][$suite_name] : $JUNIT;
  2127. $result = sprintf(
  2128. '<testsuite name="%s" tests="%s" failures="%d" errors="%d" skip="%d" time="%s">' . PHP_EOL,
  2129. $suite['name'], $suite['test_total'], $suite['test_fail'], $suite['test_error'], $suite['test_skip'],
  2130. $suite['execution_time']
  2131. );
  2132. foreach($suite['suites'] as $sub_suite) {
  2133. $result .= junit_get_suite_xml($sub_suite['name']);
  2134. }
  2135. // Output files only in subsuites
  2136. if (!empty($suite_name)) {
  2137. foreach($suite['files'] as $file) {
  2138. $result .= $JUNIT['files'][$file]['xml'];
  2139. }
  2140. }
  2141. $result .= '</testsuite>' . PHP_EOL;
  2142. return $result;
  2143. }
  2144. function junit_enabled() {
  2145. global $JUNIT;
  2146. return !empty($JUNIT);
  2147. }
  2148. /**
  2149. * @param array|string $type
  2150. * @param string $file_name
  2151. * @param string $test_name
  2152. * @param int|string $time
  2153. * @param string $message
  2154. * @param string $details
  2155. * @return void
  2156. */
  2157. function junit_mark_test_as($type, $file_name, $test_name, $time = null, $message = '', $details = '') {
  2158. global $JUNIT;
  2159. if (!junit_enabled()) return;
  2160. $suite = junit_get_suitename_for($file_name);
  2161. junit_suite_record($suite, 'test_total');
  2162. $time = null !== $time ? $time : junit_get_timer($file_name);
  2163. junit_suite_record($suite, 'execution_time', $time);
  2164. $escaped_test_name = basename($file_name) . ' - ' . htmlspecialchars($test_name, ENT_QUOTES);
  2165. $JUNIT['files'][$file_name]['xml'] = "<testcase classname='$suite' name='$escaped_test_name' time='$time'>\n";
  2166. if (is_array($type)) {
  2167. $output_type = $type[0] . 'ED';
  2168. $type = reset(array_intersect(array('XFAIL', 'FAIL'), $type));
  2169. } else {
  2170. $output_type = $type . 'ED';
  2171. }
  2172. if ('PASS' == $type || 'XFAIL' == $type) {
  2173. junit_suite_record($suite, 'test_pass');
  2174. } elseif ('BORK' == $type) {
  2175. junit_suite_record($suite, 'test_error');
  2176. $JUNIT['files'][$file_name]['xml'] .= "<error type='$output_type' message='$message'/>\n";
  2177. } elseif ('SKIP' == $type) {
  2178. junit_suite_record($suite, 'test_skip');
  2179. $JUNIT['files'][$file_name]['xml'] .= "<skipped>$message</skipped>\n";
  2180. } elseif('FAIL' == $type) {
  2181. junit_suite_record($suite, 'test_fail');
  2182. $JUNIT['files'][$file_name]['xml'] .= "<failure type='$output_type' message='$message'>$details</failure>\n";
  2183. } else {
  2184. junit_suite_record($suite, 'test_error');
  2185. $JUNIT['files'][$file_name]['xml'] .= "<error type='$output_type' message='$message'>$details</error>\n";
  2186. }
  2187. $JUNIT['files'][$file_name]['xml'] .= "</testcase>\n";
  2188. }
  2189. function junit_suite_record($suite, $param, $value = 1) {
  2190. global $JUNIT;
  2191. $JUNIT[$param] += $value;
  2192. $JUNIT['suites'][$suite][$param] += $value;
  2193. }
  2194. function junit_get_timer($file_name) {
  2195. global $JUNIT;
  2196. if (!junit_enabled()) return 0;
  2197. if (isset($JUNIT['files'][$file_name]['total'])) {
  2198. return number_format($JUNIT['files'][$file_name]['total'], 4);
  2199. }
  2200. return 0;
  2201. }
  2202. function junit_start_timer($file_name) {
  2203. global $JUNIT;
  2204. if (!junit_enabled()) return;
  2205. if (!isset($JUNIT['files'][$file_name]['start'])) {
  2206. $JUNIT['files'][$file_name]['start'] = microtime(true);
  2207. $suite = junit_get_suitename_for($file_name);
  2208. junit_init_suite($suite);
  2209. $JUNIT['suites'][$suite]['files'][$file_name] = $file_name;
  2210. }
  2211. }
  2212. function junit_get_suitename_for($file_name) {
  2213. return junit_path_to_classname(dirname($file_name));
  2214. }
  2215. function junit_path_to_classname($file_name) {
  2216. global $JUNIT;
  2217. return $JUNIT['name'] . '.' . str_replace(DIRECTORY_SEPARATOR, '.', $file_name);
  2218. }
  2219. function junit_init_suite($suite_name) {
  2220. global $JUNIT;
  2221. if (!junit_enabled()) return;
  2222. if (!empty($JUNIT['suites'][$suite_name])) {
  2223. return;
  2224. }
  2225. $JUNIT['suites'][$suite_name] = array(
  2226. 'name' => $suite_name,
  2227. 'test_total' => 0,
  2228. 'test_pass' => 0,
  2229. 'test_fail' => 0,
  2230. 'test_error' => 0,
  2231. 'test_skip' => 0,
  2232. 'suites' => array(),
  2233. 'files' => array(),
  2234. 'execution_time'=> 0,
  2235. );
  2236. }
  2237. function junit_finish_timer($file_name) {
  2238. global $JUNIT;
  2239. if (!junit_enabled()) return;
  2240. if (!isset($JUNIT['files'][$file_name]['start'])) {
  2241. error("Timer for $file_name was not started!");
  2242. }
  2243. if (!isset($JUNIT['files'][$file_name]['total'])) {
  2244. $JUNIT['files'][$file_name]['total'] = 0;
  2245. }
  2246. $start = $JUNIT['files'][$file_name]['start'];
  2247. $JUNIT['files'][$file_name]['total'] += microtime(true) - $start;
  2248. unset($JUNIT['files'][$file_name]['start']);
  2249. }
  2250. /*
  2251. * Local variables:
  2252. * tab-width: 4
  2253. * c-basic-offset: 4
  2254. * End:
  2255. * vim: noet sw=4 ts=4
  2256. */
  2257. ?>