forked from php/php-src
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server-tests.php
executable file
·1568 lines (1410 loc) · 50.5 KB
/
server-tests.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
+----------------------------------------------------------------------+
| PHP Version 5 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Ilia Alshanetsky <ilia@php.net> |
| Preston L. Bannister <pbannister@php.net> |
| Marcus Boerger <helly@php.net> |
| Shane Caraveo <shane@php.net> |
| Derick Rethans <derick@php.net> |
| Sander Roobol <sander@php.net> |
| (based on version by: Stig Bakken <ssb@php.net>) |
| (based on the PHP 3 test framework by Rasmus Lerdorf) |
+----------------------------------------------------------------------+
*/
set_time_limit(0);
while(@ob_end_clean());
if (ob_get_level()) echo "Not all buffers were deleted.\n";
error_reporting(E_ALL);
/**********************************************************************
* QA configuration
*/
define('PHP_QA_EMAIL', 'qa-reports@lists.php.net');
define('QA_SUBMISSION_PAGE', 'http://qa.php.net/buildtest-process.php');
/**********************************************************************
* error messages
*/
define('PCRE_MISSING_ERROR',
'+-----------------------------------------------------------+
| ! ERROR ! |
| The test-suite requires that you have pcre extension |
| enabled. To enable this extension either compile your PHP |
| with --with-pcre-regex or if you have compiled pcre as a |
| shared module load it via php.ini. |
+-----------------------------------------------------------+');
define('SAFE_MODE_WARNING',
'+-----------------------------------------------------------+
| ! WARNING ! |
| You are running the test-suite with "safe_mode" ENABLED ! |
| |
| Chances are high that no test will work at all, |
| depending on how you configured "safe_mode" ! |
+-----------------------------------------------------------+');
define('TMP_MISSING',
'+-----------------------------------------------------------+
| ! ERROR ! |
| You must create /tmp for session tests to work! |
| |
+-----------------------------------------------------------+');
define('PROC_OPEN_MISSING',
'+-----------------------------------------------------------+
| ! ERROR ! |
| The test-suite requires that proc_open() is available. |
| Please check if you disabled it in php.ini. |
+-----------------------------------------------------------+');
define('REQ_PHP_VERSION',
'+-----------------------------------------------------------+
| ! ERROR ! |
| The test-suite must be run with PHP 5 or later. |
| You can still test older extecutables by setting |
| TEST_PHP_EXECUTABLE and running this script with PHP 5. |
+-----------------------------------------------------------+');
/**********************************************************************
* information scripts
*/
define('PHP_INFO_SCRIPT','<?php echo "
PHP_SAPI=" . PHP_SAPI . "
PHP_VERSION=" . phpversion() . "
ZEND_VERSION=" . zend_version() . "
PHP_OS=" . PHP_OS . "
INCLUDE_PATH=" . get_cfg_var("include_path") . "
INI=" . realpath(get_cfg_var("cfg_file_path")) . "
SCANNED_INI=" . (function_exists(\'php_ini_scanned_files\') ?
str_replace("\n","", php_ini_scanned_files()) :
"** not determined **") . "
SERVER_SOFTWARE=" . (isset($_ENV[\'SERVER_SOFTWARE\']) ? $_ENV[\'SERVER_SOFTWARE\'] : \'UNKNOWN\');
?>');
define('PHP_EXTENSIONS_SCRIPT','<?php print join(get_loaded_extensions(),":"); ?>');
define('PHP_INI_SETTINGS_SCRIPT','<?php echo serialize(ini_get_all()); ?>');
/**********************************************************************
* various utility functions
*/
function settings2array($settings, &$ini_settings)
{
foreach($settings as $setting) {
if (strpos($setting, '=')!==false) {
$setting = explode("=", $setting, 2);
$name = trim($setting[0]);
$value = trim($setting[1]);
$ini_settings[$name] = $value;
}
}
}
function settings2params(&$ini_settings)
{
$settings = '';
if (count($ini_settings)) {
foreach($ini_settings as $name => $value) {
$value = addslashes($value);
$settings .= " -d \"".strtolower($name)."=$value\"";
}
}
return $settings;
}
function generate_diff($wanted,$output)
{
$w = explode("\n", $wanted);
$o = explode("\n", $output);
$w1 = array_diff_assoc($w,$o);
$o1 = array_diff_assoc($o,$w);
$w2 = array();
$o2 = array();
foreach($w1 as $idx => $val) $w2[sprintf("%03d<",$idx)] = sprintf("%03d- ", $idx+1).$val;
foreach($o1 as $idx => $val) $o2[sprintf("%03d>",$idx)] = sprintf("%03d+ ", $idx+1).$val;
$diff = array_merge($w2, $o2);
ksort($diff);
return implode("\r\n", $diff);
}
function mkpath($path,$mode = 0777) {
$dirs = split('[\\/]',$path);
$path = $dirs[0];
for($i = 1;$i < count($dirs);$i++) {
$path .= '/'.$dirs[$i];
@mkdir($path,$mode);
}
}
function copyfiles($src,$new) {
$d = dir($src);
while (($entry = $d->read())) {
if (is_file("$src/$entry")) {
copy("$src/$entry", "$new/$entry");
}
}
$d->close();
}
function post_result_data($query,$data)
{
$url = QA_SUBMISSION_PAGE.'?'.$query;
$post = "php_test_data=" . urlencode(base64_encode(preg_replace("/[\\x00]/", "[0x0]", $data)));
$r = new HTTPRequest($url,NULL,NULL,$post);
return $this->response_headers['Status']=='200';
}
function execute($command, $args=NULL, $input=NULL, $cwd=NULL, $env=NULL)
{
$data = "";
if (gettype($args)=='array') {
$args = join($args,' ');
}
$commandline = "$command $args";
$proc = proc_open($commandline, array(
0 => array('pipe', 'r'),
1 => array('pipe', 'w')),
$pipes, $cwd, $env);
if (!$proc)
return false;
if ($input) {
$out = fwrite($pipes[0],$input);
if ($out != strlen($input)) {
return NULL;
}
}
fclose($pipes[0]);
while (true) {
/* hide errors from interrupted syscalls */
$r = $pipes;
$w = null;
$e = null;
$n = @stream_select($r, $w, $e, 60);
if ($n === 0) {
/* timed out */
$data .= "\n ** ERROR: process timed out **\n";
proc_terminate($proc);
return $data;
} else if ($n) {
$line = fread($pipes[1], 8192);
if (strlen($line) == 0) {
/* EOF */
break;
}
$data .= $line;
}
}
$code = proc_close($proc);
return $data;
}
function executeCode($php, $ini_overwrites, $code, $remove_headers=true, $cwd=NULL, $env=NULL)
{
$params = NULL;
if ($ini_overwrites) {
$info_params = array();
settings2array($ini_overwrites,$info_params);
$params = settings2params($info_params);
}
$out = execute($php, $params, $code, $cwd, $env);
// kill the headers
if ($remove_headers && preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $out, $match)) {
$out = $match[2];
}
return $out;
}
/**********************************************************************
* a simple request class that lets us handle http based tests
*/
class HTTPRequest
{
public $headers = array();
public $timeout = 4;
public $urlparts = NULL;
public $url = '';
public $userAgent = 'PHP-Test-Harness';
public $options = array();
public $postdata = NULL;
public $errmsg = '';
public $errno = 0;
public $response;
public $response_headers;
public $outgoing_payload;
public $incoming_payload = '';
/*
URL is the full url
headers is assoc array of outgoing http headers
options may include
timeout
proxy_host
proxy_port
proxy_user
proxy_pass
method (GET|POST)
post data is, well, post data. It is not processed so
multipart stuff must be prepared before calling this
(or add it to class)
*/
function HTTPRequest($URL, $headers=array(), $options=array(), $postdata=NULL)
{
$this->urlparts = @parse_url($URL);
$this->url = $URL;
$this->options = $options;
$this->headers = $headers;
$this->postdata = &$postdata;
$this->doRequest();
}
function doRequest()
{
if (!$this->_validateUrl()) return;
if (isset($this->options['timeout']))
$this->timeout = (int)$this->options['timeout'];
$this->_sendHTTP();
}
function _validateUrl()
{
if ( ! is_array($this->urlparts) ) {
return FALSE;
}
if (!isset($this->urlparts['host'])) {
$this->urlparts['host']='127.0.0.1';
}
if (!isset($this->urlparts['port'])) {
$this->urlparts['port'] = 80;
}
if (!isset($this->urlparts['path']) || !$this->urlparts['path'])
$this->urlparts['path'] = '/';
return TRUE;
}
function _parseResponse()
{
if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $this->incoming_payload, $match)) {
$this->response = $match[2];
if (preg_match("/^HTTP\/1\.. (\d+).*/s",$match[1],$status) && !$status[1]) {
$this->errmsg = "HTTP Response $status[1] Not Found";
return FALSE;
}
$rh = preg_split("/[\n\r]+/",$match[1]);
$this->response_headers = array();
foreach ($rh as $line) {
if (strpos($line, ':')!==false) {
$line = explode(":", $line, 2);
$this->response_headers[trim($line[0])] = trim($line[1]);
}
}
$this->response_headers['Status']=$status[1];
// if no content, return false
if(strlen($this->response) > 0) return TRUE;
}
$this->errmsg = 'Invalid HTTP Response';
return FALSE;
}
function &_getRequest()
{
$fullpath = $this->urlparts['path'].
(isset($this->urlparts['query'])?'?'.$this->urlparts['query']:'').
(isset($this->urlparts['fragment'])?'#'.$this->urlparts['fragment']:'');
if (isset($this->options['proxy_host'])) {
$fullpath = 'http://'.$this->urlparts['host'].':'.$this->urlparts['port'].$fullpath;
}
if (isset($this->options['proxy_user'])) {
$headers['Proxy-Authorization'] = 'Basic ' . base64_encode($this->options['proxy_user'].":".$this->options['proxy_pass']);
}
$headers['User-Agent'] = $this->userAgent;
$headers['Host'] = $this->urlparts['host'];
$headers['Content-Length'] = strlen($this->postdata);
$headers['Content-Type'] = 'application/x-www-form-urlencoded';
if (isset($this->headers)) {
$headers = array_merge($headers, $this->headers);
}
$headertext = '';
foreach ($headers as $k => $v) {
$headertext .= "$k: $v\r\n";
}
$method = trim($this->options['method'])?strtoupper(trim($this->options['method'])):'GET';
$this->outgoing_payload =
"$method $fullpath HTTP/1.0\r\n".
$headertext."\r\n".
$this->postdata;
return $this->outgoing_payload;
}
function &_sendHTTP()
{
$this->_getRequest();
$host = $this->urlparts['host'];
$port = $this->urlparts['port'];
if (isset($this->options['proxy_host'])) {
$host = $this->options['proxy_host'];
$port = isset($this->options['proxy_port'])?$this->options['proxy_port']:8080;
}
// send
if ($this->timeout > 0) {
$fp = fsockopen($host, $port, $this->errno, $this->errmsg, $this->timeout);
} else {
$fp = fsockopen($host, $port, $this->errno, $this->errmsg);
}
if (!$fp) {
$this->errmsg = "Connect Error to $host:$port";
return NULL;
}
if ($this->timeout > 0) {
// some builds of php do not support this, silence
// the warning
@socket_set_timeout($fp, $this->timeout);
}
if (!fputs($fp, $this->outgoing_payload, strlen($this->outgoing_payload))) {
$this->errmsg = "Error Sending Request Data to $host";
return NULL;
}
while ($data = fread($fp, 32768)) {
$this->incoming_payload .= $data;
}
fclose($fp);
$this->_parseResponse();
}
# a simple test case
#$r = new HTTPRequest('http://localhost:81/info.php/path/info');
#print_r($r->response_headers);
#print $r->response;
} // end HTTPRequest
/**********************************************************************
* main test harness
*/
class testHarness {
public $cwd;
public $xargs = array(
#arg env var value default description
'c' => array('' ,'file' ,NULL ,'configuration file, see server-tests-config.php for example'),
'd' => array('TEST_PATHS' ,'paths' ,NULL ,'colon seperate path list'),
'e' => array('TEST_PHP_ERROR_STYLE','EMACS|MSVC' ,'EMACS' ,'editor error style'),
'h' => array('' ,'' ,NULL ,'this help'),
'i' => array('PHPRC' ,'path|file' ,NULL ,'ini file to use for tests (sets PHPRC)'),
'l' => array('TEST_PHP_LOG_FORMAT' ,'string' ,'LEODC' ,'any combination of CDELO'),
'm' => array('TEST_BASE_PATH' ,'path' ,NULL ,'copy tests to this path before testing'),
'n' => array('NO_PHPTEST_SUMMARY' ,'' ,0 ,'do not print test summary'),
'p' => array('TEST_PHP_EXECUTABLE' ,'path' ,NULL ,'php executable to be tested'),
'q' => array('NO_INTERACTION' ,'' ,0 ,'no console interaction (ie dont contact QA)'),
'r' => array('REPORT_EXIT_STATUS' ,'' ,0 ,'exit with status at end of execution'),
's' => array('TEST_PHP_SRCDIR' ,'path' ,NULL ,'path to php source code'),
't' => array('TEST_PHP_DETAILED' ,'number' ,0 ,'level of detail output to dump'),
'u' => array('TEST_WEB_BASE_URL' ,'url' ,'' ,'base url for http testing'),
'v' => array('TEST_CONTEXT_INFO' ,'' ,0 ,'view text executable context info'),
'w' => array('TEST_WEB' ,'' ,0 ,'run tests via http'),
'x' => array('TEST_WEB_EXT' ,'file ext' ,'php' ,'http file extension to use')
);
public $conf = array();
public $test_to_run = array();
public $test_files = array();
public $test_results = array();
public $failed_tests = array();
public $exts_to_test;
public $exts_tested = 0;
public $exts_skipped = 0;
public $ignored_by_ext = 0;
public $test_dirs = array('tests', 'pear', 'ext', 'sapi');
public $start_time;
public $end_time;
public $exec_info;
public $test_executable_iscgi = false;
public $inisettings; // the test executables settings, used for web tests
public $iswin32 = false;
public $ddash = "=====================================================================";
public $sdash = "---------------------------------------------------------------------";
// Default ini settings
public $ini_overwrites = array(
'output_handler'=>'',
'zlib.output_compression'=>'Off',
'open_basedir'=>'',
'safe_mode'=>'0',
'disable_functions'=>'',
'output_buffering'=>'Off',
'error_reporting'=>'4095',
'display_errors'=>'1',
'log_errors'=>'0',
'html_errors'=>'0',
'track_errors'=>'1',
'report_memleaks'=>'1',
'report_zend_debug'=>'0',
'docref_root'=>'/phpmanual/',
'docref_ext'=>'.html',
'error_prepend_string'=>'',
'error_append_string'=>'',
'auto_prepend_file'=>'',
'auto_append_file'=>'',
'magic_quotes_runtime'=>'0',
);
public $env = array();
public $info_params = array();
function testHarness() {
$this->iswin32 = substr(PHP_OS, 0, 3) == "WIN";
$this->checkRequirements();
$this->env = $_ENV;
$this->removeSensitiveEnvVars();
$this->initializeConfiguration();
$this->parseArgs();
$this->setTestPaths();
# change to working directory
if ($this->conf['TEST_PHP_SRCDIR']) {
@chdir($this->conf['TEST_PHP_SRCDIR']);
}
$this->cwd = getcwd();
if (!$this->conf['TEST_PHP_SRCDIR'])
$this->conf['TEST_PHP_SRCDIR'] = $this->cwd;
if (!$this->conf['TEST_BASE_PATH'] && $this->conf['TEST_PHP_SRCDIR'])
$this->conf['TEST_BASE_PATH'] = $this->conf['TEST_PHP_SRCDIR'];
if ($this->iswin32) {
$this->conf['TEST_PHP_SRCDIR'] = str_replace('/','\\',$this->conf['TEST_PHP_SRCDIR']);
$this->conf['TEST_BASE_PATH'] = str_replace('/','\\',$this->conf['TEST_BASE_PATH']);
}
if (!$this->conf['TEST_WEB'] && !is_executable($this->conf['TEST_PHP_EXECUTABLE'])) {
$this->error("invalid PHP executable specified by TEST_PHP_EXECUTABLE = " .
$this->conf['TEST_PHP_EXECUTABLE']);
return false;
}
$this->getInstalledExtensions();
$this->getExecutableInfo();
$this->getExecutableIniSettings();
$this->test_executable_iscgi = strncmp($this->exec_info['PHP_SAPI'],'cgi',3)==0;
$this->calculateDocumentRoot();
// add TEST_PHP_SRCDIR to the include path, this facilitates
// tests including files from src/tests
//$this->ini_overwrites['include_path'] = $this->cwd.($this->iswin32?';.;':':.:').$this->exec_info['INCLUDE_PATH'];
$params = array();
settings2array($this->ini_overwrites,$params);
$this->info_params = settings2params($params);
$this->contextHeader();
if ($this->conf['TEST_CONTEXT_INFO']) return;
$this->loadFileList();
$this->moveTestFiles();
$this->run();
$this->summarizeResults();
}
function getExecutableIniSettings()
{
$out = $this->runscript(PHP_INI_SETTINGS_SCRIPT,true);
$this->inisettings = unserialize($out);
}
function getExecutableInfo()
{
$out = $this->runscript(PHP_INFO_SCRIPT,true);
$out = preg_split("/[\n\r]+/",$out);
$info = array();
foreach ($out as $line) {
if (strpos($line, '=')!==false) {
$line = explode("=", $line, 2);
$name = trim($line[0]);
$value = trim($line[1]);
$info[$name] = $value;
}
}
$this->exec_info = $info;
}
function getInstalledExtensions()
{
// get the list of installed extensions
$out = $this->runscript(PHP_EXTENSIONS_SCRIPT,true);
$this->exts_to_test = split(":",$out);
sort($this->exts_to_test);
$this->exts_tested = count($this->exts_to_test);
}
// if running local, calls executeCode,
// otherwise does an http request
function runscript($script,$removeheaders=false,$cwd=NULL)
{
if ($this->conf['TEST_WEB']) {
$pi = '/testscript.' . $this->conf['TEST_WEB_EXT'];
if (!$cwd) $cwd = $this->conf['TEST_BASE_PATH'];
$tmp_file = "$cwd$pi";
$pi = substr($cwd,strlen($this->conf['TEST_BASE_PATH'])) . $pi;
$url = $this->conf['TEST_WEB_BASE_URL'] . $pi;
file_put_contents($tmp_file,$script);
$fd = fopen($url, "rb");
$out = '';
if ($fd) {
while (!feof($fd))
$out .= fread($fd, 8192);
fclose($fd);
}
unlink($tmp_file);
if (0 && $removeheaders &&
preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $out, $match)) {
return $match[2];
}
return $out;
} else {
return executeCode($this->conf['TEST_PHP_EXECUTABLE'],$this->ini_overwrites, $script,$removeheaders,$cwd,$this->env);
}
}
// Use this function to do any displaying of text, so that
// things can be over-written as necessary.
function writemsg($msg) {
echo $msg;
}
// Another wrapper function, this one should be used any time
// a particular test passes or fails
function showstatus($item, $status, $reason = '') {
switch($status) {
case 'PASSED':
$this->writemsg("PASSED: $item ($reason)\n");
break;
case 'FAILED':
$this->writemsg("FAILED: $item ($reason)\n");
break;
case 'SKIPPED':
$this->writemsg("SKIPPED: $item ($reason)\n");
break;
}
}
function help()
{
$usage = "usage: php run-tests.php [options]\n";
foreach ($this->xargs as $arg=>$arg_info) {
$usage .= sprintf(" -%s %-12s %s\n",$arg,$arg_info[1],$arg_info[3]);
}
return $usage;
}
function parseArgs() {
global $argc;
global $argv;
global $_SERVER;
if (!isset($argv)) {
$argv = $_SERVER['argv'];
$argc = $_SERVER['argc'];
}
$conf = NULL;
for ($i=1; $i<$argc;) {
if ($argv[$i][0] != '-') continue;
$opt = $argv[$i++][1];
if (isset($value)) unset($value);
if (@$argv[$i][0] != '-') {
@$value = $argv[$i++];
}
switch($opt) {
case 'c':
/* TODO: Implement configuraiton file */
include($value);
if (!isset($conf)) {
$this->writemsg("Invalid configuration file\n");
exit(1);
}
$this->conf = array_merge($this->conf,$conf);
break;
case 'e':
$this->conf['TEST_PHP_ERROR_STYLE'] = strtoupper($value);
break;
case 'h':
print $this->help();
exit(0);
default:
if ($this->xargs[$opt][1] && isset($value))
$this->conf[$this->xargs[$opt][0]] = $value;
else if (!$this->xargs[$opt][1])
$this->conf[$this->xargs[$opt][0]] = isset($value)?$value:1;
else
$this->error("Invalid argument setting for argument $opt, should be [{$this->xargs[$opt][1]}]\n");
break;
}
}
// set config into environment, this allows
// executed tests to find out about the test
// configurations. config file or args overwrite
// env var config settings
$this->env = array_merge($this->env,$this->conf);
if (!$this->conf['TEST_WEB'] && !$this->conf['TEST_PHP_EXECUTABLE']) {
$this->writemsg($this->help());
exit(0);
}
}
function removeSensitiveEnvVars()
{
# delete sensitive env vars
$this->env['SSH_CLIENT']='deleted';
$this->env['SSH_AUTH_SOCK']='deleted';
$this->env['SSH_TTY']='deleted';
}
function setEnvConfigVar($name)
{
if (isset($this->env[$name])) {
$this->conf[$name] = $this->env[$name];
}
}
function initializeConfiguration()
{
foreach ($this->xargs as $arg=>$arg_info) {
if ($arg_info[0]) {
# initialize the default setting
$this->conf[$arg_info[0]]=$arg_info[2];
# get config from environment
$this->setEnvConfigVar($arg_info[0]);
}
}
}
function setTestPaths()
{
// configure test paths from config file or command line
if (@$this->conf['TEST_PATHS']) {
$this->test_dirs = array();
if ($this->iswin32) {
$paths = split(';',$this->conf['TEST_PATHS']);
} else {
$paths = split(':|;',$this->conf['TEST_PATHS']);
}
foreach($paths as $path) {
$this->test_dirs[] = realpath($path);
}
}
}
function test_sort($a, $b) {
$ta = strpos($a, "{$this->cwd}/tests")===0 ? 1 + (strpos($a, "{$this->cwd}/tests/run-test")===0 ? 1 : 0) : 0;
$tb = strpos($b, "{$this->cwd}/tests")===0 ? 1 + (strpos($b, "{$this->cwd}/tests/run-test")===0 ? 1 : 0) : 0;
if ($ta == $tb) {
return strcmp($a, $b);
} else {
return $tb - $ta;
}
}
function checkRequirements() {
if (version_compare(phpversion(), "5.0") < 0) {
$this->writemsg(REQ_PHP_VERSION);
exit;
}
// We might want to check another server so we won't see that server's /tmp
// if (!file_exists("/tmp")) {
// $this->writemsg(TMP_MISSING);
// exit;
// }
if (!function_exists("proc_open")) {
$this->writemsg(PROC_OPEN_MISSING);
exit;
}
if (!extension_loaded("pcre")) {
$this->writemsg(PCRE_MISSING_ERROR);
exit;
}
if (ini_get('safe_mode')) {
$this->writemsg(SAFE_MODE_WARNING);
}
}
//
// Write test context information.
//
function contextHeader()
{
$info = '';
foreach ($this->exec_info as $k=>$v) {
$info .= sprintf("%-20.s: %s\n",$k,$v);
}
$exts = '';
foreach ($this->exts_to_test as $ext) {
$exts .="$ext\n ";
}
$dirs = '';
foreach ($this->test_dirs as $test_dir) {
$dirs .= "$test_dir\n ";
}
$conf = '';
foreach ($this->conf as $k=>$v) {
$conf .= sprintf("%-20.s: %s\n",$k,$v);
}
$exeinfo = '';
if (!$this->conf['TEST_WEB'])
$exeinfo = "CWD : {$this->cwd}\n".
"PHP : {$this->conf['TEST_PHP_EXECUTABLE']}\n";
$this->writemsg("\n$this->ddash\n".
"$exeinfo$info\n".
"Test Harness Configuration:\n$conf\n".
"Extensions : $exts\n".
"Test Dirs : $dirs\n".
"$this->ddash\n");
}
function loadFileList()
{
foreach ($this->test_dirs as $dir) {
if (is_dir($dir)) {
$this->findFilesInDir($dir, ($dir == 'ext'));
} else {
$this->test_files[] = $dir;
}
}
usort($this->test_files,array($this,"test_sort"));
$this->writemsg("found ".count($this->test_files)." files\n");
}
function moveTestFiles()
{
if (!$this->conf['TEST_BASE_PATH'] ||
$this->conf['TEST_BASE_PATH'] == $this->conf['TEST_PHP_SRCDIR']) return;
$this->writemsg("moving files from {$this->conf['TEST_PHP_SRCDIR']} to {$this->conf['TEST_BASE_PATH']}\n");
$l = strlen($this->conf['TEST_PHP_SRCDIR']);
$files = array();
$dirs = array();
foreach ($this->test_files as $file) {
if (strpos($file,$this->conf['TEST_PHP_SRCDIR'])==0) {
$newlocation = $this->conf['TEST_BASE_PATH'].substr($file,$l);
$files[] = $newlocation;
$dirs[dirname($file)] = dirname($newlocation);
} else {
// XXX what to do with test files outside the
// php source directory? Need to map them into
// the new directory somehow.
}
}
foreach ($dirs as $src=>$new) {
mkpath($new);
copyfiles($src,$new);
}
$this->test_files = $files;
}
function findFilesInDir($dir,$is_ext_dir=FALSE,$ignore=FALSE)
{
$skip = array('.', '..', 'CVS');
$o = opendir($dir) or $this->error("cannot open directory: $dir");
while (($name = readdir($o)) !== FALSE) {
if (in_array($name, $skip)) continue;
if (is_dir("$dir/$name")) {
$skip_ext = ($is_ext_dir && !in_array($name, $this->exts_to_test));
if ($skip_ext) {
$this->exts_skipped++;
}
$this->findFilesInDir("$dir/$name", FALSE, $ignore || $skip_ext);
}
// Cleanup any left-over tmp files from last run.
if (substr($name, -4) == '.tmp') {
@unlink("$dir/$name");
continue;
}
// Otherwise we're only interested in *.phpt files.
if (substr($name, -5) == '.phpt') {
if ($ignore) {
$this->ignored_by_ext++;
} else {
$testfile = realpath("$dir/$name");
$this->test_files[] = $testfile;
}
}
}
closedir($o);
}
function runHeader()
{
$this->writemsg("TIME START " . date('Y-m-d H:i:s', $this->start_time) . "\n".$this->ddash."\n");
if (count($this->test_to_run)) {
$this->writemsg("Running selected tests.\n");
} else {
$this->writemsg("Running all test files.\n");
}
}
function run()
{
$this->start_time = time();
$this->runHeader();
// Run selected tests.
if (count($this->test_to_run)) {
foreach($this->test_to_run as $name=>$runnable) {
if(!preg_match("/\.phpt$/", $name))
continue;
if ($runnable) {
$this->test_results[$name] = $this->run_test($name);
}
}
} else {
foreach ($this->test_files as $name) {
$this->test_results[$name] = $this->run_test($name);
}
}
$this->end_time = time();
}
function summarizeResults()
{
if (count($this->test_results) == 0) {
$this->writemsg("No tests were run.\n");
return;
}
$n_total = count($this->test_results);
$n_total += $this->ignored_by_ext;
$sum_results = array('PASSED'=>0, 'SKIPPED'=>0, 'FAILED'=>0);
foreach ($this->test_results as $v) {
$sum_results[$v]++;
}
$sum_results['SKIPPED'] += $this->ignored_by_ext;
$percent_results = array();
while (list($v,$n) = each($sum_results)) {
$percent_results[$v] = (100.0 * $n) / $n_total;
}
$this->writemsg("\n".$this->ddash."\n".
"TIME END " . date('Y-m-d H:i:s', $this->end_time) . "\n".
$this->ddash."\n".
"TEST RESULT SUMMARY\n".
$this->sdash."\n".
"Exts skipped : " . sprintf("%4d",$this->exts_skipped) . "\n".
"Exts tested : " . sprintf("%4d",$this->exts_tested) . "\n".
$this->sdash."\n".
"Number of tests : " . sprintf("%4d",$n_total) . "\n".
"Tests skipped : " . sprintf("%4d (%2.1f%%)",$sum_results['SKIPPED'],$percent_results['SKIPPED']) . "\n".
"Tests failed : " . sprintf("%4d (%2.1f%%)",$sum_results['FAILED'],$percent_results['FAILED']) . "\n".
"Tests passed : " . sprintf("%4d (%2.1f%%)",$sum_results['PASSED'],$percent_results['PASSED']) . "\n".
$this->sdash."\n".
"Time taken : " . sprintf("%4d seconds", $this->end_time - $this->start_time) . "\n".
$this->ddash."\n");
$failed_test_summary = '';
if ($this->failed_tests) {
$failed_test_summary .= "\n".$this->ddash."\n".
"FAILED TEST SUMMARY\n".$this->sdash."\n";
foreach ($this->failed_tests as $failed_test_data) {
$failed_test_summary .= $failed_test_data['test_name'] . "\n";
}
$failed_test_summary .= $this->ddash."\n";
}
if ($failed_test_summary && !$this->conf['NO_PHPTEST_SUMMARY']) {
$this->writemsg($failed_test_summary);
}
/* We got failed Tests, offer the user to send and e-mail to QA team, unless NO_INTERACTION is set */
if ($sum_results['FAILED'] && !$this->conf['NO_INTERACTION']) {
$fp = fopen("php://stdin", "r+");
$this->writemsg("\nPlease allow this report to be send to the PHP QA\nteam. This will give us a better understanding in how\n");
$this->writemsg("PHP's test cases are doing.\n");
$this->writemsg("(choose \"s\" to just save the results to a file)? [Yns]: ");
flush();
$user_input = fgets($fp, 10);
$just_save_results = (strtolower($user_input[0]) == 's');
if ($just_save_results || strlen(trim($user_input)) == 0 || strtolower($user_input[0]) == 'y') {
/*
* Collect information about the host system for our report
* Fetch phpinfo() output so that we can see the PHP enviroment
* Make an archive of all the failed tests
* Send an email
*/
/* Ask the user to provide an email address, so that QA team can contact the user */
if (!strncasecmp($user_input, 'y', 1) || strlen(trim($user_input)) == 0) {
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): ";
flush();
$fp = fopen("php://stdin", "r+");
$user_email = trim(fgets($fp, 1024));
$user_email = str_replace("@", " at ", str_replace(".", " dot ", $user_email));
}
$failed_tests_data = '';
$sep = "\n" . str_repeat('=', 80) . "\n";
$failed_tests_data .= $failed_test_summary . "\n";
if (array_sum($this->failed_tests)) {
foreach ($this->failed_tests as $test_info) {
$failed_tests_data .= $sep . $test_info['name'];
$failed_tests_data .= $sep . file_get_contents(realpath($test_info['output']));
$failed_tests_data .= $sep . file_get_contents(realpath($test_info['diff']));
$failed_tests_data .= $sep . "\n\n";
}
$status = "failed";
} else {
$status = "success";
}
$failed_tests_data .= "\n" . $sep . 'BUILD ENVIRONMENT' . $sep;
$failed_tests_data .= "OS:\n". PHP_OS. "\n\n";
$automake = $autoconf = $libtool = $compiler = 'N/A';
if (!$this->iswin32) {
$automake = shell_exec('automake --version');