source: trunk/library/PEAR/PEAR/RunTest.php @ 6057

Revision 6057, 35.4 KB checked in by marcosw, 12 years ago (diff)

Ticket #2398 - Compatibilizacao com PHP-5.3 em alguns módulos do expresso

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