-
Notifications
You must be signed in to change notification settings - Fork 0
/
shell_tester.php
655 lines (603 loc) · 23.5 KB
/
shell_tester.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
<?php
/**
* base include file for SimpleTest
* @package SimpleTest
* @subpackage UnitTester
* @version $Id$
*/
/**#@+
* include other SimpleTest class files
*/
require_once(dirname(__FILE__) . '/test_case.php');
/**#@-*/
/**
* Wrapper for exec() functionality.
* @package SimpleTest
* @subpackage UnitTester
*/
class SimpleShell {
protected $output;
/**
* Executes the shell command and stashes the output.
* @access public
*/
function __construct() {
/*
And a little hack to make sure PHP does not timeout
*/
// http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time
set_time_limit(max(5 * 60, ini_get('max_execution_time')));
$this->output = false;
}
/**
* Actually runs the command. Does not trap the
* error stream output as this need PHP 4.3+.
* @param string $command The actual command line
* to run.
* @return integer Exit code.
* @access public
*/
function execute($command) {
$this->output = false;
exec($this->fixPHPpathInCommand($command), $this->output, $ret);
return $ret;
}
/**
* Accessor for the last output.
* @return string Output as text.
* @access public
*/
function getOutput() {
return implode("\n", $this->output);
}
/**
* Accessor for the last output.
* @return array Output as array of lines.
* @access public
*/
function getOutputAsList() {
return $this->output;
}
/**
* Test whether the given 'php' binary path actually points to a valid and accessible php binary.
*
* @return $exe path when the binary is valid, FALSE otherwise.
* @access private
*/
private function checkPHPexePath($exe)
{
if (is_executable($exe))
{
exec($exe . ' -v', $output, $exit_status);
if ($exit_status === 0)
{
if (0)
{
// but a lot of binaries on UNIX (and Windows) do work for the above command, so we make double sure:
exec($exe . ' -i', $output, $exit_status);
// ... and ascertain that the phpinfo() actually ran by looking for something which should always show up in there:
if ($exit_status === 0 && strpos(implode('', $output), 'extension_dir') !== false)
{
return $exe;
}
}
else
{
// it's enough when '-v' produces a 'PHP n.n.n' response to ensure that the binary addressed is indeed a valid PHP engine:
if (preg_match('/PHP\s*[4-9]\.[0-9]+\.[0-9]+/', implode('', $output)) == 1)
{
return $exe;
}
}
}
}
return false;
}
/**
* Test whether the given directory path actually contains a valid and accessible php binary.
*
* @return the complete path to the PHP binary when a valid binary has been located, FALSE otherwise.
* @access private
*/
private function expandPHPexePath($dir)
{
$dir = (empty($dir) ? $dir : str_replace('//', '/', strtr($dir . '/', '\\', '/')));
$version = explode('.', phpversion());
$phpcli = array('php', 'php' . $version[0], 'php.exe', 'php' . $version[0] . '.exe');
$fileset = array();
foreach($phpcli as $binname)
{
$fileset[] = $dir . $binname;
}
// also accommodate environments where php binary names are augmented, e.g. 'php-5.2.8.exe', but
// don't use glob() when we expect the platform shell to resolve our path issue for us at the same time:
if (!empty($dir))
{
$scanarr = array('php*.exe');
if (!isset($_SERVER['WINDIR']))
{
$scanarr[] = 'php*'; // only add this one on UNIX as it can produce a lot of clutter on Windows when scanning the 'extensions_dir' path train...
}
foreach($scanarr as $wildcard)
{
$rv = glob($dir . $wildcard);
if (is_array($rv))
{
// strip out any .dll, .so, etc. as they're useless and should not be 'executed' anyhow:
foreach($rv as $idx => $file)
{
if (preg_match('/\.(dll|so|a|o|com|lib|sh)$/', $file) == 1)
{
unset($rv[$idx]);
}
}
$fileset = array_merge($fileset, $rv);
}
}
}
foreach($fileset as $file)
{
$rv = $this->checkPHPexePath($file);
if ($rv !== false) return $rv;
}
return false;
}
/**
* Test whether the given directory path OR any of its parent directories actually contains a valid and accessible php binary.
*
* Note: This scan also looks in places where you might expect PHP to reside when you're running a LAMP/WAMP/XAMPP rig.
*
* @return the complete path to the PHP binary when a valid binary has been located, FALSE otherwise.
* @access private
*/
private function ascendedScan4PHPexePath($dir)
{
if (!empty($dir))
{
$olddir = $dir . '/xxx'; // fake, done to suit the precondition for the next loop
for (;;)
{
$dir = str_replace('//', '/', strtr($dir . '/', '\\', '/'));
if (strlen($olddir) - strlen($dir) < 2) break;
// LAMP/WAMP/XAMPP: also scan the ./php/ and ./php/bin/ branches:
foreach(array('', '/php/', '/php/bin/') as $branch)
{
$exe = $this->expandPHPexePath($dir . $branch);
if ($exe !== false) return $exe;
}
// fix for Windows path ascend: the shortest path on Windows is either 'C:/' i.e. 3 or '//?/c/' (UNC) or '/c/' (Cygwin/MingW)
$olddir = $dir;
$dir = dirname(substr($dir, 0, strlen($dir) - 1));
}
}
return false;
}
/**
* Delivers the path to a usable PHP executable.
* This is useful for many installations which don't have 'php' (or 'php.exe')
* not readily available in the PATH.
*
* @return the path to the PHP executable
* @access public
*/
function getPHPexePath() {
global $_SERVER;
static $exe_path;
if (empty($exe_path))
{
for ($state = 0; ; $state++)
{
switch($state)
{
case 0:
$exe = $this->expandPHPexePath('');
break;
case 1:
if (defined('PHP_BINDIR') && PHP_BINDIR !== '.')
{
$exe = $this->expandPHPexePath(PHP_BINDIR);
break;
}
continue 2;
case 2:
if (!empty($_SERVER['PHPRC']))
{
$exe = $this->expandPHPexePath($_SERVER['PHPRC']);
break;
}
continue 2;
case 3:
// http://stackoverflow.com/questions/2372624/get-current-php-executable-from-within-script
if (!empty($_SERVER['_']))
{
$exe = $this->checkPHPexePath($_SERVER['_']);
break;
}
continue 2;
case 4:
// once more inspired by http://stackoverflow.com/questions/2372624/get-current-php-executable-from-within-script
//
// This time around we expect either the path to PHP itself or to the PHP_CGI version or in case of apache running
// with PHP as a module, the path to Apache.
// Hence we do NOT assume that the binary path delivered via the pid lookup(s) below are necessarily PHP binaries
// themselves; we perform a path-ascend-scan to check for other viable PHP locations as well:
if (function_exists('posix_getpid'))
{
// Gets the PID of the current executable
$pid = posix_getpid();
// Returns the exact path to the PHP executable.
$path = exec("readlink -f /proc/$pid/exe");
if (!empty($path))
{
// don't test httpd server binaries themselves: pretty useless effort anyway:
if (strpos($path, 'php') !== false)
{
$exe = $this->checkPHPexePath($path);
if ($exe !== false) break;
}
$exe = $this->ascendedScan4PHPexePath(dirname($path));
if ($exe !== false) break;
}
}
else if (function_exists('getmypid'))
{
$pid = getmypid();
$path = exec("readlink -f /proc/$pid/exe");
if (!empty($path))
{
// don't test httpd server binaries themselves: pretty useless effort anyway:
if (strpos($path, 'php') !== false)
{
$exe = $this->checkPHPexePath($path);
if ($exe !== false) break;
}
$exe = $this->ascendedScan4PHPexePath(dirname($path));
if ($exe !== false) break;
}
}
// The above is kept as not everyone will have /proc/self/exe:
$path = exec("readlink -f /proc/self/exe");
if (!empty($path))
{
// don't test httpd server binaries themselves: pretty useless effort anyway:
if (strpos($path, 'php') !== false)
{
$exe = $this->checkPHPexePath($path);
if ($exe !== false) break;
}
$exe = $this->ascendedScan4PHPexePath(dirname($path));
if ($exe !== false) break;
}
continue 2;
case 5:
// on Windows you might need to look in a few other places, e.g. when you have a XAMPP or WAMP install:
// using code from http://www.apachehaus.com/forum/index.php?topic=38.0
if (class_exists('COM'))
{
$wmi = new COM('winmgmts://');
foreach(array('httpd', 'apache', 'php', 'php%') as $exename)
{
$processes = $wmi->ExecQuery("SELECT * FROM Win32_Process WHERE Name LIKE '$exename.exe'");
foreach($processes as $process)
{
if (property_exists($process, 'CommandLine'))
{
if ($process->CommandLine{0} == '"')
{
$cmd = substr($process->CommandLine, 1);
$cmd = substr($cmd, 0, strcspn($cmd, '"'));
}
else
{
$cmd = substr($process->CommandLine, 0, strcspn($process->CommandLine, " \t"));
}
// don't test the apache binaries themselves: pretty useless effort anyway:
if (strpos($exename, 'php') !== false)
{
$exe = $this->checkPHPexePath($cmd);
if ($exe !== false) break 3;
}
$exe = $this->ascendedScan4PHPexePath(dirname($cmd));
if ($exe !== false) break 3;
}
}
}
}
continue 2;
case 6:
// on Windows (and probably on some other platforms as well), we MAY expect to find the extensions quite near the php binary itself:
$dir = ini_get('extension_dir');
if (!empty($dir))
{
$exe = $this->ascendedScan4PHPexePath($dir);
if ($exe !== false) break;
}
continue 2;
case 7:
// inspired by http://stackoverflow.com/questions/3889486/how-to-get-the-path-of-the-php-bin-from-php/3889630#3889630
$paths = explode(PATH_SEPARATOR, getenv('PATH'));
foreach ($paths as $path)
{
$exe = $this->expandPHPexePath($path);
if ($exe !== false) break 2;
}
continue 2;
default:
break 2;
}
if (!empty($exe))
{
$exe_path = $exe;
return $exe;
}
}
// this will fail, but we pass it on anyhow...
$exe_path = 'php';
return 'php';
}
return $exe_path;
}
/**
* Process the command line so users can always write 'php yada yada ...' and not have to
* worry about where their PHP executable resides exactly.
*
* @return processed command line
* @access public
*/
function fixPHPpathInCommand($command)
{
$command = explode(' ', $command, 2);
if ($command[0] === 'php')
{
$command[0] = $this->getPHPexePath();
}
return implode(' ', $command);
}
}
/**
* Test case for testing of command line scripts and
* utilities. Usually scripts that are external to the
* PHP code, but support it in some way.
* @package SimpleTest
* @subpackage UnitTester
*/
class ShellTestCase extends SimpleTestCase {
protected $current_shell;
protected $last_status;
protected $last_command;
/**
* Creates an empty test case. Should be subclassed
* with test methods for a functional test case.
* @param string $label Name of test case. Will use
* the class name if none specified.
* @access public
*/
function __construct($label = false) {
parent::__construct($label);
$this->current_shell = $this->createShell();
$this->last_status = false;
$this->last_command = '';
}
/**
* Executes a command and buffers the results.
* @param string $command Command to run.
* @return boolean True if zero exit code.
* @access public
*/
function execute($command) {
$shell = $this->getShell();
$this->last_status = $shell->execute($command);
$this->last_command = $command;
return ($this->last_status === 0);
}
/**
* Dumps the output of the last command.
* @access public
*/
function dumpOutput() {
$this->dump($this->getOutput());
}
/**
* Accessor for the last output.
* @return string Output as text.
* @access public
*/
function getOutput() {
$shell = $this->getShell();
return $shell->getOutput();
}
/**
* Accessor for the last output.
* @return array Output as array of lines.
* @access public
*/
function getOutputAsList() {
$shell = $this->getShell();
return $shell->getOutputAsList();
}
/**
* Called from within the test methods to register
* passes and failures.
* @param boolean $result Pass on true.
* @param string $message Message to display describing
* the test state.
* @return boolean True on pass
* @access public
*/
function assertTrue($result, $message = false) {
return $this->assert(new TrueExpectation(), $result, $message);
}
/**
* Will be true on false and vice versa. False
* is the PHP definition of false, so that null,
* empty strings, zero and an empty array all count
* as false.
* @param boolean $result Pass on false.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertFalse($result, $message = '%s') {
return $this->assert(new FalseExpectation(), $result, $message);
}
/**
* Will trigger a pass if the two parameters have
* the same value only. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertEqual($first, $second, $message = "%s") {
return $this->assert(
new EqualExpectation($first),
$second,
$message);
}
/**
* Will trigger a pass if the two parameters have
* a different value. Otherwise a fail. This
* is for testing hand extracted text, etc.
* @param mixed $first Value to compare.
* @param mixed $second Value to compare.
* @param string $message Message to display.
* @return boolean True on pass
* @access public
*/
function assertNotEqual($first, $second, $message = "%s") {
return $this->assert(
new NotEqualExpectation($first),
$second,
$message);
}
/**
* Tests the last status code from the shell.
* @param integer $status Expected status of last
* command.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertExitCode($status, $message = "%s") {
$message = sprintf($message, "Expected status code of [$status] from [" .
$this->last_command . "], but got [" .
$this->last_status . "]");
return $this->assertTrue($status === $this->last_status, $message);
}
/**
* Attempt to exactly match the combined STDERR and
* STDOUT output.
* @param string $expected Expected output.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertOutput($expected, $message = "%s") {
$shell = $this->getShell();
return $this->assert(
new EqualExpectation($expected),
$shell->getOutput(),
$message);
}
/**
* Scans the output for a Perl regex. If found
* anywhere it passes, else it fails.
* @param string $pattern Regex to search for.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertOutputPattern($pattern, $message = "%s") {
$shell = $this->getShell();
return $this->assert(
new PatternExpectation($pattern),
$shell->getOutput(),
$message);
}
/**
* If a Perl regex is found anywhere in the current
* output then a failure is generated, else a pass.
* @param string $pattern Regex to search for.
* @param $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertNoOutputPattern($pattern, $message = "%s") {
$shell = $this->getShell();
return $this->assert(
new NoPatternExpectation($pattern),
$shell->getOutput(),
$message);
}
/**
* File existence check.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertFileExists($path, $message = "%s") {
$message = sprintf($message, "File [$path] should exist");
return $this->assertTrue(file_exists($path), $message);
}
/**
* File non-existence check.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertFileNotExists($path, $message = "%s") {
$message = sprintf($message, "File [$path] should not exist");
return $this->assertFalse(file_exists($path), $message);
}
/**
* Scans a file for a Perl regex. If found
* anywhere it passes, else it fails.
* @param string $pattern Regex to search for.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertFilePattern($pattern, $path, $message = "%s") {
return $this->assert(
new PatternExpectation($pattern),
implode('', file($path)),
$message);
}
/**
* If a Perl regex is found anywhere in the named
* file then a failure is generated, else a pass.
* @param string $pattern Regex to search for.
* @param string $path Full filename and path.
* @param string $message Message to display.
* @return boolean True if pass.
* @access public
*/
function assertNoFilePattern($pattern, $path, $message = "%s") {
return $this->assert(
new NoPatternExpectation($pattern),
implode('', file($path)),
$message);
}
/**
* Accessor for current shell. Used for testing the
* the tester itself.
* @return Shell Current shell.
* @access protected
*/
protected function getShell() {
return $this->current_shell;
}
/**
* Factory for the shell to run the command on.
* @return Shell New shell object.
* @access protected
*/
protected function createShell() {
return new SimpleShell();
}
}