Last active
May 11, 2018 16:41
-
-
Save picasso250/48ba1516ab18b03e0958cfd00130ca78 to your computer and use it in GitHub Desktop.
PHP test tool by xiaochi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!env php | |
<?php | |
// PHP test tool by xiaochi | |
// Usage: test.php foo.php | |
// If you have a test_foo.php, it will automatically include | |
// foo.php and run test_foo.php. | |
// It also includes `vendor/autoload.php` | |
$vendor_autoload = "vendor/autoload.php"; | |
if (is_file($vendor_autoload)) { | |
require $vendor_autoload; | |
} | |
function exception_error_handler($severity, $message, $file, $line) { | |
if (!(error_reporting() & $severity)) { | |
// This error code is not included in error_reporting | |
return; | |
} | |
throw new ErrorException($message, 0, $severity, $file, $line); | |
} | |
set_error_handler("exception_error_handler"); | |
$assert_total = 0; | |
$assert_fail = 0; | |
if (isset($argv[1])) { | |
if (!is_file($argv[1])) { | |
die("$argv[1] is not file\n"); | |
} | |
test_file($argv[1]); | |
} else { | |
foreach (glob("test_*.php") as $tf) { | |
$f = substr($tf, 5); | |
if (!is_file($f)) { | |
die("$tf ok, but $f is not file"); | |
} | |
test_file($file); | |
} | |
} | |
function test_file($file) | |
{ | |
global $assert_total; | |
global $assert_fail; | |
require $file; | |
$tf = "test_$file"; | |
if (!is_file($tf)) { | |
die("$tf is not file\n"); | |
} | |
echo "# $tf\n"; | |
require $tf; | |
foreach(file($tf) as $line) { | |
if (preg_match('/^function\s*test_(\w+)\s*\(/', $line, $m)) { | |
$func = "test_$m[1]"; | |
echo "## $func()\n"; | |
$func(); | |
} | |
} | |
$ok = $assert_total-$assert_fail; | |
echo "$ok/$assert_total ".($assert_fail===0?"OK":"FAIL!!!")."\n"; | |
} | |
function assert_true($t, $msg=null) { | |
global $assert_total; | |
global $assert_fail; | |
//debug_print_backtrace();; | |
$db = debug_backtrace(); | |
//echo __FUNCTION__,PHP_EOL; | |
foreach($db as $i=>$trace) { | |
//echo "$i => $trace[file]: $trace[function]()\n"; | |
if ($trace['function'] == __FUNCTION__) | |
break; | |
} | |
//print_r($trace);exit; | |
if ($t===true) { | |
// do nothing | |
} else { | |
$assert_fail++; | |
$line_no = $trace['line']; | |
$line = trim(_get_line($trace['file'], $line_no)); | |
echo "$line_no: $line $msg\n"; | |
} | |
$assert_total++; | |
} | |
function _get_line($file, $line_no) { | |
foreach (file($file) as $i => $line) { | |
if ($i == $line_no-1) | |
return $line; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment