Posted: Sun Apr 30, 2006 8:39 pm
Hey silicate, good to see you over here. I modified the code so it would support Marcus' interface. Untested and a little bit of a hack. maybe someone can improve the code -- especially the stack_track part. It should work PHP4 or PHP5, but in PHP4 you will have to call run() explicitly.
Code: Select all
function ensure($condition) {
static $tester;
if (! $tester) {
$tester = new UnitTester();
}
$tester->assertTrue($condition, 1);
}
class UnitTester {
var $_passes = 0;
var $_fails = 0;
var $_test_stack = array();
var $_trace_pos = 0;
var $output = '';
function assertTrue($result, $pos=0) {
if ($result) {
$this->pass();
} else {
$this->_trace_pos = $pos + 1;
$this->fail();
}
}
function assertFalse($result, $pos=0) {
if ($result) {
$this->_trace_pos = $pos + 1;
$this->fail();
} else {
$this->pass();
}
}
function pass() {
++$this->_passes;
}
function fail() {
++$this->_fails;
$test_data = debug_backtrace();
$this->_test_stack[] = $test_data[$this->_trace_pos];
$this->_trace_pos = 0;
}
var $passed_heading_style = 'color: white; background-color: green; margin-top: 2; padding: 4 4 4 4;';
var $failed_heading_style = 'color: white; background-color: red; margin-top: 2; padding: 4 4 4 4;';
var $failed_test_style = 'color: white; background-color: red; margin-top: 2; padding-left: 4;';
function __destruct() {
if ($this->_fails > 0) {
$output = '<div style="' . $this->failed_heading_style . '">Failed ' . $this->_fails . ' of ' . ($this->_fails + $this->_passes) . ' tests. </div>';
$n = 1;
foreach ($this->_test_stack as $this_data) {
$message = $n++ . ". Failed: {$this_data['function']} on line {$this_data['line']} of file {$this_data['file']}. ";
$output .= '<div style="' . $this->failed_test_style . '">' . $message . '</div>';
}
} else {
$output = '<div style="' . $this->passed_heading_style . '">Passed ' .$this->_passes . ' tests.</div>';
}
echo $output;
}
function __destruct() {
if ($this->output == '') {
$this->run();
}
}
}