Refactored test system to be object-oriented

This commit is contained in:
Marcin Kurczewski 2014-05-06 18:09:23 +02:00
parent c005da2e6d
commit 2e6687329b
2 changed files with 216 additions and 154 deletions

View file

@ -8,6 +8,14 @@ class AbstractTest
$this->assert = new Assert(); $this->assert = new Assert();
} }
public function setup()
{
}
public function teardown()
{
}
protected function mockUser() protected function mockUser()
{ {
$user = UserModel::spawn(); $user = UserModel::spawn();

View file

@ -3,8 +3,17 @@ require_once __DIR__ . '/../src/core.php';
require_once __DIR__ . '/../src/upgrade.php'; require_once __DIR__ . '/../src/upgrade.php';
\Chibi\Autoloader::registerFileSystem(__DIR__); \Chibi\Autoloader::registerFileSystem(__DIR__);
$options = getopt('cf:', ['clean', 'filter:']); class TestRunner
{
protected $dbPath;
public function __construct()
{
$this->dbPath = __DIR__ . '/db.sqlite';
}
public function run($options)
{
$cleanDatabase = (isset($options['c']) or isset($options['clean'])); $cleanDatabase = (isset($options['c']) or isset($options['clean']));
if (isset($options['f'])) if (isset($options['f']))
@ -14,34 +23,39 @@ elseif (isset($options['filter']))
else else
$filter = null; $filter = null;
$dbPath = __DIR__ . '/db.sqlite'; if ($cleanDatabase)
$this->cleanDatabase();
if (file_exists($dbPath) and $cleanDatabase)
unlink($dbPath);
try try
{ {
resetEnvironment(); $this->resetEnvironment();
upgradeDatabase(); upgradeDatabase();
runAll($filter); $testFixtures = $this->getTestFixtures($filter);
$this->runAll($testFixtures);
} }
finally finally
{ {
removeTestFolders(); $this->removeTestFolders();
}
} }
function resetEnvironment() protected function cleanDatabase()
{
if (file_exists($this->dbPath))
unlink($this->dbPath);
}
protected function resetEnvironment()
{ {
global $dbPath;
prepareConfig(true); prepareConfig(true);
getConfig()->main->dbDriver = 'sqlite'; getConfig()->main->dbDriver = 'sqlite';
getConfig()->main->dbLocation = $dbPath; getConfig()->main->dbLocation = $this->dbPath;
removeTestFolders(); $this->removeTestFolders();
prepareEnvironment(true); prepareEnvironment(true);
} }
function removeTestFolders() protected function removeTestFolders()
{ {
$folders = $folders =
[ [
@ -71,7 +85,7 @@ function removeTestFolders()
} }
} }
function getTestMethods($filter) protected function getTestFixtures($filter)
{ {
$testFiles = []; $testFiles = [];
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__)) as $fileName) foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__)) as $fileName)
@ -91,92 +105,132 @@ function getTestMethods($filter)
}); });
} }
$testMethods = []; $testFixtures = [];
foreach ($testClasses as $class) foreach ($testClasses as $class)
{ {
$reflectionClass = new ReflectionClass($class); $reflectionClass = new ReflectionClass($class);
if ($reflectionClass->isAbstract())
continue;
$testFixture = new StdClass;
$testFixture->class = $reflectionClass;
$testFixture->methods = [];
foreach ($reflectionClass->getMethods() as $method) foreach ($reflectionClass->getMethods() as $method)
{ {
if (preg_match('/test/i', $method->name) and $method->isPublic()) if (preg_match('/test/i', $method->name)
and $method->isPublic()
and $method->getNumberOfParameters() == 0)
{ {
$testMethods []= $method; $testFixture->methods []= $method;
} }
} }
$testFixtures []= $testFixture;
} }
return $testMethods; return $testFixtures;
} }
function runAll($filter) protected function runAll($testFixtures)
{ {
$startTime = microtime(true); $startTime = microtime(true);
$testMethods = getTestMethods($filter);
echo 'Starting tests' . PHP_EOL; $testNumber = 0;
$resultPrinter = function($result) use (&$testNumber)
//get display names of the methods
$labels = [];
foreach ($testMethods as $key => $method)
$labels[$key] = $method->class . '::' . $method->name;
//ensure every label has the same length
$maxLabelLength = count($testMethods) > 0 ? max(array_map('strlen', $labels)) : 0;
foreach ($labels as &$label)
$label = str_pad($label, $maxLabelLength + 1, ' ');
$pad = count($testMethods) ? ceil(log10(1 + count($testMethods))) : 0;
//run all the methods
$success = true;
foreach ($testMethods as $key => $method)
{ {
$instance = new $method->class(); printf('%3d %-65s ', ++ $testNumber, $result->origin->class . '::' . $result->origin->name);
$testStartTime = microtime(true);
echo str_pad($key + 1, $pad, ' ', STR_PAD_LEFT) . ' '; if ($result->success)
echo $labels[$key] . '... ';
unset($e);
try
{
runSingle(function() use ($method, $instance)
{
$method->invoke($instance);
});
echo 'OK'; echo 'OK';
} else
catch (Exception $e)
{
$success = false;
echo 'FAIL'; echo 'FAIL';
}
printf(' [%.03fs]' . PHP_EOL, microtime(true) - $testStartTime); printf(' [%.03fs]' . PHP_EOL, $result->duration);
if (isset($e)) if ($result->exception)
{ {
echo '---' . PHP_EOL; echo '---' . PHP_EOL;
echo $e->getMessage() . PHP_EOL; echo $result->exception->getMessage() . PHP_EOL;
echo $e->getTraceAsString() . PHP_EOL; echo $result->exception->getTraceAsString() . PHP_EOL;
echo '---' . PHP_EOL . PHP_EOL; echo '---' . PHP_EOL . PHP_EOL;
} }
};
//run all the methods
echo 'Starting tests' . PHP_EOL;
$success = true;
foreach ($testFixtures as $className => $testFixture)
{
$results = $this->runTestFixture($testFixture, $resultPrinter);
foreach ($results as $result)
$success &= $result->success;
} }
printf('%s %s... %s [%.03fs]' . PHP_EOL, printf('%3s %-65s %s [%.03fs]' . PHP_EOL,
str_pad('', $pad, ' '), ' ',
str_pad('All tests', $maxLabelLength + 1, ' '), 'All tests',
$success ? 'OK' : 'FAIL', $success ? 'OK' : 'FAIL',
microtime(true) - $startTime); microtime(true) - $startTime);
return $success; return $success;
} }
function runSingle($callback) protected function runTestFixture($testFixture, $resultPrinter)
{
$instance = $testFixture->class->newInstance();
$instance->setup();
$results = [];
foreach ($testFixture->methods as $method)
{
$result = $this->runTest(function() use ($method, $instance)
{
$method->invoke($instance);
});
$result->origin = $method;
if ($resultPrinter !== null)
$resultPrinter($result);
$results []= $result;
}
$instance->teardown();
return $results;
}
protected function runTest($callback)
{
$this->resetEnvironment();
$startTime = microtime(true);
$result = new TestResult();
try
{ {
resetEnvironment();
resetEnvironment(true);
\Chibi\Database::rollback(function() use ($callback) \Chibi\Database::rollback(function() use ($callback)
{ {
$callback(); $callback();
}); });
$result->success = true;
} }
catch (Exception $e)
{
$result->exception = $e;
$result->success = false;
}
$endTime = microtime(true);
$result->duration = $endTime - $startTime;
return $result;
}
}
class TestResult
{
public $duration;
public $success;
public $exception;
public $origin;
}
$options = getopt('cf:', ['clean', 'filter:']);
(new TestRunner)->run($options);