Upgraded to KH 3.3.0

This commit is contained in:
Deon George
2012-11-09 23:18:50 +11:00
parent 863bc1150a
commit ea36639638
1293 changed files with 96042 additions and 9545 deletions

View File

@@ -8,8 +8,7 @@
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
// @codingStandardsIgnoreFile
abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Database_TestCase {
abstract class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Database_TestCase {
/**
* Whether we should enable work arounds to make the tests compatible with phpunit 3.4
@@ -21,7 +20,7 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
* Make sure PHPUnit backs up globals
* @var boolean
*/
protected $backupGlobals = TRUE;
protected $backupGlobals = FALSE;
/**
* A set of unittest helpers that are shared between normal / database
@@ -36,6 +35,12 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
protected $environmentDefault = array();
/**
* The kohana database connection that PHPUnit should use for this test
* @var string
*/
protected $_database_connection = 'default';
/**
* Creates a predefined environment using the default environment
*
@@ -44,9 +49,9 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public function setUp()
{
if (self::$_assert_type_compatability === NULL)
if(self::$_assert_type_compatability === NULL)
{
if ( ! class_exists('PHPUnit_Runner_Version'))
if( ! class_exists('PHPUnit_Runner_Version'))
{
require_once 'PHPUnit/Runner/Version.php';
}
@@ -82,8 +87,7 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
public function getConnection()
{
// Get the unittesting db connection
$config = Kohana::config('database')
->{Kohana::config('unittest')->db_connection};
$config = Kohana::$config->load('database.'.$this->_database_connection);
if($config['type'] !== 'pdo')
{
@@ -101,15 +105,15 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
return $this->createDefaultDBConnection($pdo, $config['connection']['database']);
}
/**
* Gets a connection to the unittest database
*
* @return Kohana_Database The database connection
*/
public function getKohanaConnection()
{
return Database::instance(Kohana::config('unittest')->db_connection);
}
/**
* Gets a connection to the unittest database
*
* @return Kohana_Database The database connection
*/
public function getKohanaConnection()
{
return Database::instance(Kohana::$config->load('unittest')->db_connection);
}
/**
* Removes all kohana related cache files in the cache directory
@@ -167,8 +171,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertInstanceOf($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInstanceOf($expected, $actual, $message);
}
@@ -184,8 +190,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return parent::assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message);
}
@@ -200,8 +208,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertNotInstanceOf($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInstanceOf($expected, $actual, $message);
}
@@ -217,8 +227,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeNotType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message);
}
@@ -233,8 +245,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertInternalType($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInternalType($expected, $actual, $message);
}
@@ -250,8 +264,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertAttributeInternalType($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeInternalType($expected, $attributeName, $classOrObject, $message);
}
@@ -266,8 +282,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertNotInternalType($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInternalType($expected, $actual, $message);
}
@@ -283,8 +301,10 @@ abstract Class Kohana_Unittest_Database_TestCase extends PHPUnit_Extensions_Data
*/
public static function assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeNotType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message);
}

View File

@@ -132,7 +132,7 @@ class Kohana_Unittest_Helpers {
$class->setStaticPropertyValue($var, $value);
}
// If this is an environment variable
elseif (preg_match('/^[A-Z_-]+$/D', $option) OR isset($_SERVER[$option]))
elseif (preg_match('/^[A-Z_-]+$/', $option) OR isset($_SERVER[$option]))
{
if ($backup_needed)
{
@@ -146,12 +146,12 @@ class Kohana_Unittest_Helpers {
{
if ($backup_needed)
{
$this->_environment_backup[$option] = Kohana::config($option);
$this->_environment_backup[$option] = Kohana::$config->load($option);
}
list($group, $var) = explode('.', $option, 2);
Kohana::config($group)->set($var, $value);
Kohana::$config->load($group)->set($var, $value);
}
}
}

View File

@@ -4,7 +4,6 @@
* A version of the stock PHPUnit testcase that includes some extra helpers
* and default settings
*/
// @codingStandardsIgnoreFile
abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
/**
@@ -17,7 +16,7 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
* Make sure PHPUnit backs up globals
* @var boolean
*/
protected $backupGlobals = TRUE;
protected $backupGlobals = FALSE;
/**
* A set of unittest helpers that are shared between normal / database
@@ -40,9 +39,9 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public function setUp()
{
if (self::$_assert_type_compatability === NULL)
if(self::$_assert_type_compatability === NULL)
{
if ( ! class_exists('PHPUnit_Runner_Version'))
if( ! class_exists('PHPUnit_Runner_Version'))
{
require_once 'PHPUnit/Runner/Version.php';
}
@@ -122,8 +121,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertInstanceOf($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInstanceOf($expected, $actual, $message);
}
@@ -139,8 +140,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return parent::assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message);
}
@@ -155,8 +158,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertNotInstanceOf($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInstanceOf($expected, $actual, $message);
}
@@ -172,8 +177,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeNotType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message);
}
@@ -188,8 +195,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertInternalType($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInternalType($expected, $actual, $message);
}
@@ -205,8 +214,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertAttributeInternalType($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeInternalType($expected, $attributeName, $classOrObject, $message);
}
@@ -221,8 +232,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertNotInternalType($expected, $actual, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInternalType($expected, $actual, $message);
}
@@ -238,8 +251,10 @@ abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
*/
public static function assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message = '')
{
if (self::$_assert_type_compatability)
if(self::$_assert_type_compatability)
{
return self::assertAttributeNotType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message);
}

View File

@@ -0,0 +1,80 @@
<?php defined('SYSPATH') or die('No direct script access.');
/**
* A version of the stock PHPUnit testsuite that supports whitelisting and
* blacklisting for code coverage filter
*/
abstract class Kohana_Unittest_TestSuite extends PHPUnit_Framework_TestSuite
{
/**
* Holds the details of files that should be white and blacklisted for
* code coverage
*
* @var array
*/
protected $_filter_calls = array(
'addFileToBlacklist' => array(),
'addDirectoryToBlacklist' => array(),
'addFileToWhitelist' => array());
/**
* Runs the tests and collects their result in a TestResult.
*
* @param PHPUnit_Framework_TestResult $result
* @param mixed $filter
* @param array $groups
* @param array $excludeGroups
* @param boolean $processIsolation
* @return PHPUnit_Framework_TestResult
* @throws InvalidArgumentException
*/
public function run(PHPUnit_Framework_TestResult $result = NULL, $filter = FALSE, array $groups = array(), array $excludeGroups = array(), $processIsolation = FALSE)
{
// Get the code coverage filter from the suite's result object
$coverage = $result->getCodeCoverage();
if ($coverage)
{
$coverage_filter = $coverage->filter();
// Apply the white and blacklisting
foreach ($this->_filter_calls as $method => $args)
{
foreach ($args as $arg)
{
$coverage_filter->$method($arg);
}
}
}
return parent::run($result, $filter, $groups, $excludeGroups, $processIsolation);
}
/**
* Queues a file to be added to the code coverage blacklist when the suite runs
* @param string $file
*/
public function addFileToBlacklist($file)
{
$this->_filter_calls['addFileToBlacklist'][] = $file;
}
/**
* Queues a directory to be added to the code coverage blacklist when the suite runs
* @param string $dir
*/
public function addDirectoryToBlacklist($dir)
{
$this->_filter_calls['addDirectoryToBlacklist'][] = $dir;
}
/**
* Queues a file to be added to the code coverage whitelist when the suite runs
* @param string $file
*/
public function addFileToWhitelist($file)
{
$this->_filter_calls['addFileToWhitelist'][] = $file;
}
}

View File

@@ -13,13 +13,6 @@
class Kohana_Unittest_Tests {
static protected $cache = array();
/**
* Flag to identify whether the installed version of phpunit
* is greater than or equal to 3.5
* @var boolean
*/
static protected $phpunit_v35 = FALSE;
/**
* Loads test files if they cannot be found by kohana
* @param <type> $class
@@ -45,65 +38,19 @@ class Kohana_Unittest_Tests {
*/
static public function configure_environment($do_whitelist = TRUE, $do_blacklist = TRUE)
{
// During a webui request we need to manually load PHPUnit
if ( ! class_exists('PHPUnit_Util_Filter', FALSE) AND ! function_exists('phpunit_autoload'))
{
try
{
include_once 'PHPUnit/Autoload.php';
}
catch (ErrorException $e)
{
include_once 'PHPUnit/Framework.php';
}
}
// Allow PHPUnit to handle exceptions and errors
if (Kohana::$is_cli)
{
restore_exception_handler();
restore_error_handler();
}
restore_exception_handler();
restore_error_handler();
spl_autoload_register(array('Unittest_tests', 'autoload'));
// As of PHPUnit v3.5 there are slight differences in the way files are black|whitelisted
self::$phpunit_v35 = function_exists('phpunit_autoload');
Unittest_tests::$cache = (($cache = Kohana::cache('unittest_whitelist_cache')) === NULL) ? array() : $cache;
$config = Kohana::config('unittest');
if ($do_whitelist AND $config->use_whitelist)
{
self::whitelist();
}
if ($do_blacklist AND count($config['blacklist']))
{
Unittest_tests::blacklist($config->blacklist);
}
}
/**
* Helper function to see if unittest is enabled in the config
*
* @return boolean
*/
static function enabled()
{
$p_environment = Kohana::config('unittest.environment');
$k_environment = Kohana::$environment;
return (is_array($p_environment) AND in_array($k_environment, $p_environment))
OR
($k_environment === $p_environment);
}
/**
* Creates the test suite for kohana
*
* @return PHPUnit_Framework_TestSuite
* @return Unittest_TestSuite
*/
static function suite()
{
@@ -114,10 +61,25 @@ class Kohana_Unittest_Tests {
return $suite;
}
Unittest_Tests::configure_environment();
$suite = new Unittest_TestSuite;
// Load the whitelist and blacklist for code coverage
$config = Kohana::$config->load('unittest');
if ($config->use_whitelist)
{
Unittest_Tests::whitelist(NULL, $suite);
}
if (count($config['blacklist']))
{
Unittest_Tests::blacklist($config->blacklist, $suite);
}
// Add tests
$files = Kohana::list_files('tests');
$suite = new PHPUnit_Framework_TestSuite;
self::addTests($suite, $files);
return $suite;
@@ -128,23 +90,20 @@ class Kohana_Unittest_Tests {
*
* Uses recursion to scan subdirectories
*
* @param PHPUnit_Framework_TestSuite $suite The test suite to add to
* @param Unittest_TestSuite $suite The test suite to add to
* @param array $files Array of files to test
*/
// @codingStandardsIgnoreStart
static function addTests(PHPUnit_Framework_TestSuite $suite, array $files)
// @codingStandardsIgnoreEnd
static function addTests(Unittest_TestSuite $suite, array $files)
{
if (self::$phpunit_v35)
{
$filter = PHP_CodeCoverage_Filter::getInstance();
}
foreach ($files as $file)
foreach ($files as $path => $file)
{
if (is_array($file))
{
self::addTests($suite, $file);
if ($path != 'tests'.DIRECTORY_SEPARATOR.'test_data')
{
self::addTests($suite, $file);
}
}
else
{
@@ -161,14 +120,7 @@ class Kohana_Unittest_Tests {
require_once($file);
}
if (isset($filter))
{
$filter->addFileToBlacklist($file);
}
else
{
PHPUnit_Util_Filter::addFileToFilter($file);
}
$suite->addFileToBlacklist($file);
}
}
}
@@ -177,38 +129,20 @@ class Kohana_Unittest_Tests {
/**
* Blacklist a set of files in PHPUnit code coverage
*
* @param array A set of files to blacklist
* @param array $blacklist_items A set of files to blacklist
* @param Unittest_TestSuite $suite The test suite
*/
static public function blacklist(array $blacklist_items)
static public function blacklist(array $blacklist_items, Unittest_TestSuite $suite = NULL)
{
if (self::$phpunit_v35)
foreach ($blacklist_items as $item)
{
$filter = PHP_CodeCoverage_Filter::getInstance();
foreach ($blacklist_items as $item)
if (is_dir($item))
{
if (is_dir($item))
{
$filter->addDirectoryToBlacklist($item);
}
else
{
$filter->addFileToBlacklist($item);
}
$suite->addDirectoryToBlacklist($item);
}
}
else
{
foreach ($blacklist_items as $item)
else
{
if (is_dir($item))
{
PHPUnit_Util_Filter::addDirectoryToFilter($item);
}
else
{
PHPUnit_Util_Filter::addFileToFilter($item);
}
$suite->addFileToBlacklist($item);
}
}
}
@@ -220,8 +154,9 @@ class Kohana_Unittest_Tests {
* set in the config file
*
* @param array $directories Optional directories to whitelist
* @param Unittest_Testsuite $suite Suite to load the whitelist into
*/
static public function whitelist(array $directories = NULL)
static public function whitelist(array $directories = NULL, Unittest_TestSuite $suite = NULL)
{
if (empty($directories))
{
@@ -236,7 +171,7 @@ class Kohana_Unittest_Tests {
}
// Only whitelist the "top" files in the cascading filesystem
self::set_whitelist(Kohana::list_files('classes', $directories));
self::set_whitelist(Kohana::list_files('classes', $directories), $suite);
}
}
@@ -248,7 +183,7 @@ class Kohana_Unittest_Tests {
*/
static protected function get_config_whitelist()
{
$config = Kohana::config('unittest');
$config = Kohana::$config->load('unittest');
$directories = array();
if ($config->whitelist['app'])
@@ -292,19 +227,16 @@ class Kohana_Unittest_Tests {
* Recursively whitelists an array of files
*
* @param array $files Array of files to whitelist
* @param Unittest_TestSuite $suite Suite to load the whitelist into
*/
static protected function set_whitelist($files)
static protected function set_whitelist($files, Unittest_TestSuite $suite = NULL)
{
if (self::$phpunit_v35)
{
$filter = PHP_CodeCoverage_Filter::getInstance();
}
foreach ($files as $file)
{
if (is_array($file))
{
self::set_whitelist($file);
self::set_whitelist($file, $suite);
}
else
{
@@ -320,9 +252,9 @@ class Kohana_Unittest_Tests {
if (Unittest_tests::$cache[$file])
{
if (isset($filter))
if (isset($suite))
{
$filter->addFileToWhitelist($file);
$suite->addFileToWhitelist($file);
}
else
{
@@ -332,5 +264,4 @@ class Kohana_Unittest_Tests {
}
}
}
}

View File

@@ -0,0 +1,17 @@
<?php
/**
* Transparent extension for Kohana_Unittest_Database_TestCase
*
* Provides some unittest helpers and allows a kohana database connection to be
* used to connect to the database
*
* @package Kohana/UnitTest
* @author Kohana Team
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
abstract class Unittest_Database_TestCase extends Kohana_Unittest_Database_TestCase
{
}

View File

@@ -0,0 +1,3 @@
<?php defined('SYSPATH') or die('No direct script access.');
abstract class Unittest_TestCase extends Kohana_Unittest_TestCase {}

View File

@@ -0,0 +1,3 @@
<?php defined('SYSPATH') OR die('No direct script access.');
class Unittest_TestSuite extends Kohana_Unittest_TestSuite {}

View File

@@ -1,352 +0,0 @@
<?php defined('SYSPATH') or die ('No direct script access.');
/**
* PHPUnit Kohana web based test runner
*
* @package Kohana/UnitTest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @author Paul Banks
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
class Controller_UnitTest extends Controller_Template
{
/**
* Whether the archive module is available
* @var boolean
*/
protected $cc_archive_available = FALSE;
/**
* Unittest config
* @var Config
*/
protected $config = NULL;
/**
* The uri by which the report uri will be executed
* @var string
*/
protected $report_uri = '';
/**
* The uri by which the run action will be executed
* @var string
*/
protected $run_uri = '';
/**
* Is the XDEBUG extension loaded?
* @var boolean
*/
protected $xdebug_loaded = FALSE;
/**
* Template
* @var string
*/
public $template = 'unittest/layout';
/**
* Loads test suite
*/
public function before()
{
parent::before();
if ( ! Unittest_tests::enabled())
{
// Pretend this is a normal 404 error...
$this->status = 404;
throw new Kohana_Request_Exception('Unable to find a route to match the URI: :uri',
array(':uri' => $this->request->uri()));
}
// Prevent the whitelist from being autoloaded, but allow the blacklist
// to be loaded
Unittest_Tests::configure_environment(FALSE);
$this->config = Kohana::config('unittest');
// This just stops some very very long lines
$route = Route::get('unittest');
$this->report_uri = $route->uri(array('action' => 'report'));
$this->run_uri = $route->uri(array('action' => 'run'));
// Switch used to disable cc settings
$this->xdebug_loaded = extension_loaded('xdebug');
$this->cc_archive_enabled = class_exists('Archive');
Kohana_View::set_global('xdebug_enabled', $this->xdebug_loaded);
Kohana_View::set_global('cc_archive_enabled', $this->cc_archive_enabled);
}
/**
* Handles index page for /unittest/ and /unittest/index/
*/
public function action_index()
{
$this->template->body = View::factory('unittest/index')
->set('run_uri', $this->run_uri)
->set('report_uri', $this->report_uri)
->set('whitelistable_items', $this->get_whitelistable_items())
->set('groups', $this->get_groups_list(Unittest_tests::suite()));
}
/**
* Handles report generation
*/
public function action_report()
{
// Fairly foolproof
if ( ! $this->config->cc_report_path AND ! class_exists('Archive'))
throw new Kohana_Exception('Cannot generate report');
// We don't want to use the HTML layout, we're sending the user 100111011100110010101100
$this->auto_render = FALSE;
$suite = Unittest_tests::suite();
$temp_path = rtrim($this->config->temp_path, '/').'/';
$group = (array) Arr::get($_GET, 'group', array());
// Stop unittest from interpretting "all groups" as "no groups"
if (empty($group) OR empty($group[0]))
{
$group = array();
}
if (Arr::get($_GET, 'use_whitelist', FALSE))
{
$this->whitelist(Arr::get($_GET, 'whitelist', array()));
}
$runner = new Kohana_Unittest_Runner($suite);
// If the user wants to download a report
if ($this->cc_archive_enabled AND Arr::get($_GET, 'archive') === '1')
{
// $report is the actual directory of the report,
// $folder is the name component of directory
list($report, $folder) = $runner->generate_report($group, $temp_path);
$archive = Archive::factory('zip');
// TODO: Include the test results?
$archive->add($report, 'report', TRUE);
$filename = $folder.'.zip';
$archive->save($temp_path.$filename);
// It'd be nice to clear up afterwards but by deleting the report dir we corrupt the archive
// And once the archive has been sent to the user Request stops the script so we can't delete anything
// It'll be up to the user to delete files periodically
$this->request->send_file($temp_path.$filename, $filename);
}
else
{
$folder = trim($this->config->cc_report_path, '/').'/';
$path = DOCROOT.$folder;
if ( ! file_exists($path))
throw new Kohana_Exception('Report directory :dir does not exist', array(':dir' => $path));
if ( ! is_writable($path))
throw new Kohana_Exception('Script doesn\'t have permission to write to report dir :dir ', array(':dir' => $path));
$runner->generate_report($group, $path, FALSE);
$this->request->redirect(URL::site($folder.'index.html', $this->request));
}
}
/**
* Handles test running interface
*/
public function action_run()
{
$this->template->body = View::factory('unittest/results');
// Get the test suite and work out which groups we're testing
$suite = Unittest_tests::suite();
$group = (array) Arr::get($_GET, 'group', array());
// Stop phpunit from interpretting "all groups" as "no groups"
if (empty($group) OR empty($group[0]))
{
$group = array();
}
// Only collect code coverage if the user asked for it
$collect_cc = (bool) Arr::get($_GET, 'collect_cc', FALSE);
if ($collect_cc AND Arr::get($_GET, 'use_whitelist', FALSE))
{
$whitelist = $this->whitelist(Arr::get($_GET, 'whitelist', array()));
}
$runner = new Kohana_Unittest_Runner($suite);
try
{
$runner->run($group, $collect_cc);
if ($collect_cc)
{
$this->template->body->set('coverage', $runner->calculate_cc_percentage());
}
if (isset($whitelist))
{
$this->template->body->set('coverage_explanation', $this->nice_whitelist_explanation($whitelist));
}
}
catch(Kohana_Exception $e)
{
// Code coverage is not allowed, possibly xdebug disabled?
// TODO: Tell the user this?
$runner->run($group);
}
// Show some results
$this->template->body
->set('results', $runner->results)
->set('totals', $runner->totals)
->set('time', $this->nice_time($runner->time))
// Sets group to the currently selected group, or default all groups
->set('group', Arr::get($this->get_groups_list($suite), reset($group), 'All groups'))
->set('groups', $this->get_groups_list($suite))
->set('run_uri', $this->request->uri())
->set('report_uri', $this->report_uri.url::query())
// Whitelist related stuff
->set('whitelistable_items', $this->get_whitelistable_items())
->set('whitelisted_items', isset($whitelist) ? array_keys($whitelist) : array())
->set('whitelist', ! empty($whitelist));
}
/**
* Get the list of groups from the test suite, sorted with 'All groups' prefixed
*
* @return array Array of groups in the test suite
*/
protected function get_groups_list($suite)
{
// Make groups aray suitable for drop down
$groups = $suite->getGroups();
if (count($groups) > 0)
{
sort($groups);
$groups = array_combine($groups, $groups);
}
return array('' => 'All Groups') + $groups;
}
/**
* Gets a list of items that are whitelistable
*
* @return array
*/
protected function get_whitelistable_items()
{
static $whitelist;
if (count($whitelist))
return $whitelist;
$whitelist = array();
$whitelist['k_app'] = 'Application';
$k_modules = array_keys(Kohana::modules());
$whitelist += array_map('ucfirst', array_combine($k_modules, $k_modules));
$whitelist['k_sys'] = 'Kohana Core';
return $whitelist;
}
/**
* Whitelists a specified set of modules specified by the user
*
* @param array $modules
*/
protected function whitelist(array $modules)
{
$k_modules = Kohana::modules();
$whitelist = array();
// Make sure our whitelist is valid
foreach ($modules as $item)
{
if (isset($k_modules[$item]))
{
$whitelist[$item] = $k_modules[$item];
}
elseif ($item === 'k_app')
{
$whitelist[$item] = APPPATH;
}
elseif ($item === 'k_sys')
{
$whitelist[$item] = SYSPATH;
}
}
if (count($whitelist))
{
Unittest_tests::whitelist($whitelist);
}
return $whitelist;
}
/**
* Prettifies the list of whitelisted modules
*
* @param array Array of whitelisted items
* @return string
*/
protected function nice_whitelist_explanation(array $whitelist)
{
$items = array_intersect_key($this->get_whitelistable_items(), $whitelist);
return implode(', ', $items);
}
protected function nice_time($time)
{
$parts = array();
if ($time > DATE::DAY)
{
$parts[] = floor($time/DATE::DAY).'d';
$time = $time % DATE::DAY;
}
if ($time > DATE::HOUR)
{
$parts[] = floor($time/DATE::HOUR).'h';
$time = $time % DATE::HOUR;
}
if ($time > DATE::MINUTE)
{
$parts[] = floor($time/DATE::MINUTE).'m';
$time = $time % DATE::MINUTE;
}
if ($time > 0)
{
$parts[] = round($time, 1).'s';
}
return implode(' ', $parts);
}
} // End Controller_PHPUnit

View File

@@ -1,313 +0,0 @@
<?php
/**
* PHPUnit test runner for kohana
*
* @package Kohana/UnitTest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @author Paul Banks
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_Unittest_Runner implements PHPUnit_Framework_TestListener {
/**
* Results
* @var array
*/
protected $results = array(
'errors' => array(),
'failures' => array(),
'skipped' => array(),
'incomplete' => array(),
);
/**
* Test result totals
* @var array
*/
protected $totals = array(
'tests' => 0,
'passed' => 0,
'errors' => 0,
'failures' => 0,
'skipped' => 0,
'incomplete' => 0,
'assertions' => 0,
);
/**
* Info about the current test running
* @var array
*/
protected $current = array();
/**
* Time for tests to run (seconds)
* @var float
*/
protected $time = 0;
/**
* Result collector
* @var PHPUnit_Framework_TestResult
*/
protected $result = NULL;
/**
* the test suite to run
* @var PHPUnit_Framework_TestSuite
*/
protected $suite = NULL;
/**
* Constructor
*
* @param PHPUnit_Framework_TestSuite $suite The suite to test
* @param PHPUnit_Framework_TestResult $result Optional result object to use
*/
function __construct(PHPUnit_Framework_TestSuite $suite, PHPUnit_Framework_TestResult $result = NULL)
{
if ($result === NULL)
{
$result = new PHPUnit_Framework_TestResult;
}
$result->addListener($this);
$this->suite = $suite;
$this->result = $result;
}
/**
* Magic getter to allow access to member variables
*
* @param string $var Variable to get
* @return mixed
*/
function __get($var)
{
return $this->$var;
}
/**
* Calcualtes stats for each file covered by the code testing
*
* Each member of the returned array is formatted like so:
*
* <code>
* array(
* 'coverage' => $coverage_percent_for_file,
* 'loc' => $lines_of_code,
* 'locExecutable' => $lines_of_executable_code,
* 'locExecuted' => $lines_of_code_executed
* );
* </code>
*
* @return array Statistics for code coverage of each file
*/
public function calculate_cc()
{
if ($this->result->getCollectCodeCoverageInformation())
{
$coverage = $this->result->getCodeCoverageInformation();
$coverage_summary = PHPUnit_Util_CodeCoverage::getSummary($coverage);
$stats = array();
foreach ($coverage_summary as $file => $_lines)
{
$stats[$file] = PHPUnit_Util_CodeCoverage::getStatistics($coverage_summary, $file);
}
return $stats;
}
return FALSE;
}
/**
* Calculates the percentage code coverage information
*
* @return boolean|float FALSE if cc is not enabled, float for coverage percent
*/
public function calculate_cc_percentage()
{
if ($stats = $this->calculate_cc())
{
$executable = 0;
$executed = 0;
foreach ($stats as $stat)
{
$executable += $stat['locExecutable'];
$executed += $stat['locExecuted'];
}
return ($executable > 0) ? ($executed * 100 / $executable) : 100;
}
return FALSE;
}
/**
* Generate a report using the specified $temp_path
*
* @param array $groups Groups to test
* @param string $temp_path Temporary path to use while generating report
*/
public function generate_report(array $groups, $temp_path, $create_sub_dir = TRUE)
{
if ( ! is_writable($temp_path))
throw new Kohana_Exception('Temp path :path does not exist or is not writable by the webserver', array(':path' => $temp_path));
$folder_path = $temp_path;
if ($create_sub_dir === TRUE)
{
// Icky, highly unlikely, but do it anyway
// Basically adds "(n)" to the end of the filename until there's a free file
$count = 0;
do
{
$folder_name = date('Y-m-d_H:i:s')
.(empty($groups) ? '' : ('['.implode(',', $groups).']'))
.(($count > 0) ? ('('.$count.')') : '');
++$count;
}
while (is_dir($folder_path.$folder_name));
$folder_path .= $folder_name;
mkdir($folder_path, 0777);
}
else
{
$folder_name = basename($folder_path);
}
$this->run($groups, TRUE);
require_once 'PHPUnit/Runner/Version.php';
require_once 'PHPUnit/Util/Report.php';
PHPUnit_Util_Report::render($this->result, $folder_path);
return array($folder_path, $folder_name);
}
/**
* Runs the test suite using the result specified in the constructor
*
* @param array $groups Optional array of groups to test
* @param bool $collect_cc Optional, Should code coverage be collected?
* @return Kohana_PHPUnit Instance of $this
*/
public function run(array $groups = array(), $collect_cc = FALSE)
{
if ($collect_cc AND ! extension_loaded('xdebug'))
throw new Kohana_Exception('Code coverage cannot be collected because the xdebug extension is not loaded');
$this->result->collectCodeCoverageInformation( (bool) $collect_cc);
// Run the tests.
$this->suite->run($this->result, FALSE, $groups);
return $this;
}
// @codingStandardsIgnoreStart
public function addError(PHPUnit_Framework_Test $test, Exception $e, $time)
// @codingStandardsIgnoreEnd
{
$this->totals['errors']++;
$this->current['result'] = 'errors';
$this->current['message'] = $test->getStatusMessage();
}
// @codingStandardsIgnoreStart
public function addFailure(PHPUnit_Framework_Test $test, PHPUnit_Framework_AssertionFailedError $e, $time)
// @codingStandardsIgnoreEnd
{
$this->totals['failures']++;
$this->current['result'] = 'failures';
$this->current['message'] = $test->getStatusMessage();
}
// @codingStandardsIgnoreStart
public function addIncompleteTest(PHPUnit_Framework_Test $test, Exception $e, $time)
// @codingStandardsIgnoreEnd
{
$this->totals['incomplete']++;
$this->current['result'] = 'incomplete';
$this->current['message'] = $test->getStatusMessage();
}
// @codingStandardsIgnoreStart
public function addSkippedTest(PHPUnit_Framework_Test $test, Exception $e, $time)
// @codingStandardsIgnoreEnd
{
$this->totals['skipped']++;
$this->current['result'] = 'skipped';
$this->current['message'] = $test->getStatusMessage();
}
// @codingStandardsIgnoreStart
public function startTest(PHPUnit_Framework_Test $test)
// @codingStandardsIgnoreEnd
{
$this->current['name'] = $test->getName(FALSE);
$this->current['description'] = $test->toString();
$this->current['result'] = 'passed';
}
// @codingStandardsIgnoreStart
public function endTest(PHPUnit_Framework_Test $test, $time)
// @codingStandardsIgnoreEnd
{
// Add totals
$this->totals['tests']++;
$this->totals['assertions'] += $test->getNumAssertions();
// Handle passed tests
if ($this->current['result'] == 'passed')
{
// Add to total
$this->totals['passed']++;
}
else
{
// Add to results
$this->results[$this->current['result']][] = $this->current;
}
$this->current = array();
$this->time += $time;
}
// @codingStandardsIgnoreStart
public function startTestSuite(PHPUnit_Framework_TestSuite $suite) {}
// @codingStandardsIgnoreEnd
// @codingStandardsIgnoreStart
public function endTestSuite(PHPUnit_Framework_TestSuite $suite)
// @codingStandardsIgnoreEnd
{
// Parse test descriptions to make them look nicer
foreach ($this->results as $case => $testresults)
{
foreach ($testresults as $type => $result)
{
preg_match('/^(?:([a-z0-9_]+?)::)?([a-z0-9_]+)(?: with data set (#\d+ \(.*?\)))?/i', $result['description'], $m);
$this->results[$case][$type] += array(
'class' => $m[1],
'test' => $m[2],
'data_set' => isset($m[3]) ? $m[3] : FALSE,
);
}
}
}
}

View File

@@ -1,3 +0,0 @@
<?php defined('SYSPATH') or die('No direct script access.');
class Unittest_Runner extends Kohana_Unittest_Runner {}

View File

@@ -1,3 +0,0 @@
<?php defined('SYSPATH') or die('No direct script access.');
class Unittest_TestCase extends Kohana_Unittest_TestCase {}