Kohana v3.3.0

This commit is contained in:
Deon George
2013-04-22 14:09:50 +10:00
commit f96694b18f
1280 changed files with 145034 additions and 0 deletions

View File

@@ -0,0 +1,24 @@
# Kohana-PHPUnit integration
This module integrates PHPUnit with Kohana.
If you look through any of the tests provided in this module you'll probably notice all theHorribleCamelCase.
I've chosen to do this because it's part of the PHPUnit coding conventions and is required for certain features such as auto documentation.
## Requirements
* [PHPUnit](http://www.phpunit.de/) >= 3.4
## Usage
$ phpunit --bootstrap=modules/unittest/bootstrap.php modules/unittest/tests.php
Alternatively you can use a `phpunit.xml` to have a more fine grained control
over which tests are included and which files are whitelisted.
Make sure you only whitelist the highest files in the cascading filesystem, else
you could end up with a lot of "class cannot be redefined" errors.
If you use the `tests.php` testsuite loader then it will only whitelist the
highest files. see `config/unittest.php` for details on configuring the
`tests.php` whitelist.

View File

@@ -0,0 +1,125 @@
<?php
/**
* The directory in which your application specific resources are located.
* The application directory must contain the bootstrap.php file.
*
* @link http://kohanaframework.org/guide/about.install#application
*/
$application = 'application';
/**
* The directory in which your modules are located.
*
* @link http://kohanaframework.org/guide/about.install#modules
*/
$modules = 'modules';
/**
* The directory in which the Kohana resources are located. The system
* directory must contain the classes/kohana.php file.
*
* @link http://kohanaframework.org/guide/about.install#system
*/
$system = 'system';
/**
* The default extension of resource files. If you change this, all resources
* must be renamed to use the new extension.
*
* @link http://kohanaframework.org/guide/about.install#ext
*/
define('EXT', '.php');
/**
* Set the path to the document root
*
* This assumes that this file is stored 2 levels below the DOCROOT, if you move
* this bootstrap file somewhere else then you'll need to modify this value to
* compensate.
*/
define('DOCROOT', realpath(dirname(__FILE__).'/../../').DIRECTORY_SEPARATOR);
/**
* Set the PHP error reporting level. If you set this in php.ini, you remove this.
* @link http://www.php.net/manual/errorfunc.configuration#ini.error-reporting
*
* When developing your application, it is highly recommended to enable notices
* and strict warnings. Enable them by using: E_ALL | E_STRICT
*
* In a production environment, it is safe to ignore notices and strict warnings.
* Disable them by using: E_ALL ^ E_NOTICE
*
* When using a legacy application with PHP >= 5.3, it is recommended to disable
* deprecated notices. Disable with: E_ALL & ~E_DEPRECATED
*/
error_reporting(E_ALL | E_STRICT);
/**
* End of standard configuration! Changing any of the code below should only be
* attempted by those with a working knowledge of Kohana internals.
*
* @link http://kohanaframework.org/guide/using.configuration
*/
// Make the application relative to the docroot
if ( ! is_dir($application) AND is_dir(DOCROOT.$application))
{
$application = DOCROOT.$application;
}
// Make the modules relative to the docroot
if ( ! is_dir($modules) AND is_dir(DOCROOT.$modules))
{
$modules = DOCROOT.$modules;
}
// Make the system relative to the docroot
if ( ! is_dir($system) AND is_dir(DOCROOT.$system))
{
$system = DOCROOT.$system;
}
// Define the absolute paths for configured directories
define('APPPATH', realpath($application).DIRECTORY_SEPARATOR);
define('MODPATH', realpath($modules).DIRECTORY_SEPARATOR);
define('SYSPATH', realpath($system).DIRECTORY_SEPARATOR);
// Clean up the configuration vars
unset($application, $modules, $system);
/**
* Define the start time of the application, used for profiling.
*/
if ( ! defined('KOHANA_START_TIME'))
{
define('KOHANA_START_TIME', microtime(TRUE));
}
/**
* Define the memory usage at the start of the application, used for profiling.
*/
if ( ! defined('KOHANA_START_MEMORY'))
{
define('KOHANA_START_MEMORY', memory_get_usage());
}
// Bootstrap the application
require APPPATH.'bootstrap'.EXT;
// Disable output buffering
if (($ob_len = ob_get_length()) !== FALSE)
{
// flush_end on an empty buffer causes headers to be sent. Only flush if needed.
if ($ob_len > 0)
{
ob_end_flush();
}
else
{
ob_end_clean();
}
}
// Enable the unittest module
Kohana::modules(Kohana::modules() + array('unittest' => MODPATH.'unittest'));

View File

@@ -0,0 +1,20 @@
<?php
include_once('bootstrap.php');
// Enable all modules we can find
$modules_iterator = new DirectoryIterator(MODPATH);
$modules = array();
foreach ($modules_iterator as $module)
{
if ($module->isDir())
{
$modules[$module->getFilename()] = MODPATH.$module->getFilename();
}
}
Kohana::modules(Kohana::modules() + $modules);
unset ($modules_iterator, $modules, $module);

View File

@@ -0,0 +1,311 @@
<?php
/**
* TestCase for testing a database
*
* @package Kohana/UnitTest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
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
* @var boolean
*/
protected static $_assert_type_compatability = NULL;
/**
* Make sure PHPUnit backs up globals
* @var boolean
*/
protected $backupGlobals = FALSE;
/**
* A set of unittest helpers that are shared between normal / database
* testcases
* @var Kohana_Unittest_Helpers
*/
protected $_helpers = NULL;
/**
* A default set of environment to be applied before each test
* @var array
*/
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
*
* Extending classes that have their own setUp() should call
* parent::setUp()
*/
public function setUp()
{
if(self::$_assert_type_compatability === NULL)
{
if( ! class_exists('PHPUnit_Runner_Version'))
{
require_once 'PHPUnit/Runner/Version.php';
}
self::$_assert_type_compatability = version_compare(PHPUnit_Runner_Version::id(), '3.5.0', '<=');
}
$this->_helpers = new Kohana_Unittest_Helpers;
$this->setEnvironment($this->environmentDefault);
return parent::setUp();
}
/**
* Restores the original environment overriden with setEnvironment()
*
* Extending classes that have their own tearDown()
* should call parent::tearDown()
*/
public function tearDown()
{
$this->_helpers->restore_environment();
return parent::tearDown();
}
/**
* Creates a connection to the unittesting database
*
* @return PDO
*/
public function getConnection()
{
// Get the unittesting db connection
$config = Kohana::$config->load('database.'.$this->_database_connection);
if($config['type'] !== 'pdo')
{
$config['connection']['dsn'] = $config['type'].':'.
'host='.$config['connection']['hostname'].';'.
'dbname='.$config['connection']['database'];
}
$pdo = new PDO(
$config['connection']['dsn'],
$config['connection']['username'],
$config['connection']['password']
);
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->load('unittest')->db_connection);
}
/**
* Removes all kohana related cache files in the cache directory
*/
public function cleanCacheDir()
{
return Kohana_Unittest_Helpers::clean_cache_dir();
}
/**
* Helper function that replaces all occurences of '/' with
* the OS-specific directory separator
*
* @param string $path The path to act on
* @return string
*/
public function dirSeparator($path)
{
return Kohana_Unittest_Helpers::dir_separator($path);
}
/**
* Allows easy setting & backing up of enviroment config
*
* Option types are checked in the following order:
*
* * Server Var
* * Static Variable
* * Config option
*
* @param array $environment List of environment to set
*/
public function setEnvironment(array $environment)
{
return $this->_helpers->set_environment($environment);
}
/**
* Check for internet connectivity
*
* @return boolean Whether an internet connection is available
*/
public function hasInternet()
{
return Kohana_Unittest_Helpers::has_internet();
}
/**
* Asserts that a variable is of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertInstanceOf($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInstanceOf($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return parent::assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message);
}
/**
* Asserts that a variable is not of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertNotInstanceOf($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInstanceOf($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertAttributeNotType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message);
}
/**
* Asserts that a variable is of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertInternalType($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInternalType($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeInternalType($expected, $attributeName, $classOrObject, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeInternalType($expected, $attributeName, $classOrObject, $message);
}
/**
* Asserts that a variable is not of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertNotInternalType($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInternalType($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertAttributeNotType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message);
}
}

View File

@@ -0,0 +1,169 @@
<?php
/**
* Unit testing helpers
*/
class Kohana_Unittest_Helpers {
/**
* Static variable used to work out whether we have an internet
* connection
* @see has_internet
* @var boolean
*/
static protected $_has_internet = NULL;
/**
* Check for internet connectivity
*
* @return boolean Whether an internet connection is available
*/
public static function has_internet()
{
if ( ! isset(self::$_has_internet))
{
// The @ operator is used here to avoid DNS errors when there is no connection.
$sock = @fsockopen("www.google.com", 80, $errno, $errstr, 1);
self::$_has_internet = (bool) $sock ? TRUE : FALSE;
}
return self::$_has_internet;
}
/**
* Helper function which replaces the "/" to OS-specific delimiter
*
* @param string $path
* @return string
*/
static public function dir_separator($path)
{
return str_replace('/', DIRECTORY_SEPARATOR, $path);
}
/**
* Removes all cache files from the kohana cache dir
*
* @return void
*/
static public function clean_cache_dir()
{
$cache_dir = opendir(Kohana::$cache_dir);
while ($dir = readdir($cache_dir))
{
// Cache files are split into directories based on first two characters of hash
if ($dir[0] !== '.' AND strlen($dir) === 2)
{
$dir = self::dir_separator(Kohana::$cache_dir.'/'.$dir.'/');
$cache = opendir($dir);
while ($file = readdir($cache))
{
if ($file[0] !== '.')
{
unlink($dir.$file);
}
}
closedir($cache);
rmdir($dir);
}
}
closedir($cache_dir);
}
/**
* Backup of the environment variables
* @see set_environment
* @var array
*/
protected $_environment_backup = array();
/**
* Allows easy setting & backing up of enviroment config
*
* Option types are checked in the following order:
*
* * Server Var
* * Static Variable
* * Config option
*
* @param array $environment List of environment to set
*/
public function set_environment(array $environment)
{
if ( ! count($environment))
return FALSE;
foreach ($environment as $option => $value)
{
$backup_needed = ! array_key_exists($option, $this->_environment_backup);
// Handle changing superglobals
if (in_array($option, array('_GET', '_POST', '_SERVER', '_FILES')))
{
// For some reason we need to do this in order to change the superglobals
global $$option;
if ($backup_needed)
{
$this->_environment_backup[$option] = $$option;
}
// PHPUnit makes a backup of superglobals automatically
$$option = $value;
}
// If this is a static property i.e. Html::$windowed_urls
elseif (strpos($option, '::$') !== FALSE)
{
list($class, $var) = explode('::$', $option, 2);
$class = new ReflectionClass($class);
if ($backup_needed)
{
$this->_environment_backup[$option] = $class->getStaticPropertyValue($var);
}
$class->setStaticPropertyValue($var, $value);
}
// If this is an environment variable
elseif (preg_match('/^[A-Z_-]+$/', $option) OR isset($_SERVER[$option]))
{
if ($backup_needed)
{
$this->_environment_backup[$option] = isset($_SERVER[$option]) ? $_SERVER[$option] : '';
}
$_SERVER[$option] = $value;
}
// Else we assume this is a config option
else
{
if ($backup_needed)
{
$this->_environment_backup[$option] = Kohana::$config->load($option);
}
list($group, $var) = explode('.', $option, 2);
Kohana::$config->load($group)->set($var, $value);
}
}
}
/**
* Restores the environment to the original state
*
* @chainable
* @return Kohana_Unittest_Helpers $this
*/
public function restore_environment()
{
$this->set_environment($this->_environment_backup);
}
}

View File

@@ -0,0 +1,261 @@
<?php defined('SYSPATH') or die('No direct script access.');
/**
* A version of the stock PHPUnit testcase that includes some extra helpers
* and default settings
*/
abstract class Kohana_Unittest_TestCase extends PHPUnit_Framework_TestCase {
/**
* Whether we should enable work arounds to make the tests compatible with phpunit 3.4
* @var boolean
*/
protected static $_assert_type_compatability = NULL;
/**
* Make sure PHPUnit backs up globals
* @var boolean
*/
protected $backupGlobals = FALSE;
/**
* A set of unittest helpers that are shared between normal / database
* testcases
* @var Kohana_Unittest_Helpers
*/
protected $_helpers = NULL;
/**
* A default set of environment to be applied before each test
* @var array
*/
protected $environmentDefault = array();
/**
* Creates a predefined environment using the default environment
*
* Extending classes that have their own setUp() should call
* parent::setUp()
*/
public function setUp()
{
if(self::$_assert_type_compatability === NULL)
{
if( ! class_exists('PHPUnit_Runner_Version'))
{
require_once 'PHPUnit/Runner/Version.php';
}
self::$_assert_type_compatability = version_compare(PHPUnit_Runner_Version::id(), '3.5.0', '<=');
}
$this->_helpers = new Unittest_Helpers;
$this->setEnvironment($this->environmentDefault);
}
/**
* Restores the original environment overriden with setEnvironment()
*
* Extending classes that have their own tearDown()
* should call parent::tearDown()
*/
public function tearDown()
{
$this->_helpers->restore_environment();
}
/**
* Removes all kohana related cache files in the cache directory
*/
public function cleanCacheDir()
{
return Unittest_Helpers::clean_cache_dir();
}
/**
* Helper function that replaces all occurences of '/' with
* the OS-specific directory separator
*
* @param string $path The path to act on
* @return string
*/
public function dirSeparator($path)
{
return Unittest_Helpers::dir_separator($path);
}
/**
* Allows easy setting & backing up of enviroment config
*
* Option types are checked in the following order:
*
* * Server Var
* * Static Variable
* * Config option
*
* @param array $environment List of environment to set
*/
public function setEnvironment(array $environment)
{
return $this->_helpers->set_environment($environment);
}
/**
* Check for internet connectivity
*
* @return boolean Whether an internet connection is available
*/
public function hasInternet()
{
return Unittest_Helpers::has_internet();
}
/**
* Asserts that a variable is of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertInstanceOf($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInstanceOf($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return parent::assertAttributeInstanceOf($expected, $attributeName, $classOrObject, $message);
}
/**
* Asserts that a variable is not of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertNotInstanceOf($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInstanceOf($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertAttributeNotType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeNotInstanceOf($expected, $attributeName, $classOrObject, $message);
}
/**
* Asserts that a variable is of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertInternalType($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertType($expected, $actual, $message);
}
return parent::assertInternalType($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeInternalType($expected, $attributeName, $classOrObject, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertAttributeType($expected, $attributeName, $classOrObject, $message);
}
return self::assertAttributeInternalType($expected, $attributeName, $classOrObject, $message);
}
/**
* Asserts that a variable is not of a given type.
*
* @param string $expected
* @param mixed $actual
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertNotInternalType($expected, $actual, $message = '')
{
if(self::$_assert_type_compatability)
{
return self::assertNotType($expected, $actual, $message);
}
return self::assertNotInternalType($expected, $actual, $message);
}
/**
* Asserts that an attribute is of a given type.
*
* @param string $expected
* @param string $attributeName
* @param mixed $classOrObject
* @param string $message
* @since Method available since Release 3.5.0
*/
public static function assertAttributeNotInternalType($expected, $attributeName, $classOrObject, $message = '')
{
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

@@ -0,0 +1,267 @@
<?php defined('SYSPATH') or die('No direct script access.');
/**
* PHPUnit testsuite for kohana application
*
* @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_Tests {
static protected $cache = array();
/**
* Loads test files if they cannot be found by kohana
* @param <type> $class
*/
static function autoload($class)
{
$file = str_replace('_', '/', $class);
if ($file = Kohana::find_file('tests', $file))
{
require_once $file;
}
}
/**
* Configures the environment for testing
*
* Does the following:
*
* * Loads the phpunit framework (for the web ui)
* * Restores exception phpunit error handlers (for cli)
* * registeres an autoloader to load test files
*/
static public function configure_environment($do_whitelist = TRUE, $do_blacklist = TRUE)
{
restore_exception_handler();
restore_error_handler();
spl_autoload_register(array('Unittest_tests', 'autoload'));
Unittest_tests::$cache = (($cache = Kohana::cache('unittest_whitelist_cache')) === NULL) ? array() : $cache;
}
/**
* Creates the test suite for kohana
*
* @return Unittest_TestSuite
*/
static function suite()
{
static $suite = NULL;
if ($suite instanceof PHPUnit_Framework_TestSuite)
{
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');
self::addTests($suite, $files);
return $suite;
}
/**
* Add files to test suite $suite
*
* Uses recursion to scan subdirectories
*
* @param Unittest_TestSuite $suite The test suite to add to
* @param array $files Array of files to test
*/
static function addTests(Unittest_TestSuite $suite, array $files)
{
foreach ($files as $path => $file)
{
if (is_array($file))
{
if ($path != 'tests'.DIRECTORY_SEPARATOR.'test_data')
{
self::addTests($suite, $file);
}
}
else
{
// Make sure we only include php files
if (is_file($file) AND substr($file, -strlen(EXT)) === EXT)
{
// The default PHPUnit TestCase extension
if ( ! strpos($file, 'TestCase'.EXT))
{
$suite->addTestFile($file);
}
else
{
require_once($file);
}
$suite->addFileToBlacklist($file);
}
}
}
}
/**
* Blacklist a set of files in PHPUnit code coverage
*
* @param array $blacklist_items A set of files to blacklist
* @param Unittest_TestSuite $suite The test suite
*/
static public function blacklist(array $blacklist_items, Unittest_TestSuite $suite = NULL)
{
foreach ($blacklist_items as $item)
{
if (is_dir($item))
{
$suite->addDirectoryToBlacklist($item);
}
else
{
$suite->addFileToBlacklist($item);
}
}
}
/**
* Sets the whitelist
*
* If no directories are provided then the function'll load the whitelist
* 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, Unittest_TestSuite $suite = NULL)
{
if (empty($directories))
{
$directories = self::get_config_whitelist();
}
if (count($directories))
{
foreach ($directories as & $directory)
{
$directory = realpath($directory).'/';
}
// Only whitelist the "top" files in the cascading filesystem
self::set_whitelist(Kohana::list_files('classes', $directories), $suite);
}
}
/**
* Works out the whitelist from the config
* Used only on the CLI
*
* @returns array Array of directories to whitelist
*/
static protected function get_config_whitelist()
{
$config = Kohana::$config->load('unittest');
$directories = array();
if ($config->whitelist['app'])
{
$directories['k_app'] = APPPATH;
}
if ($modules = $config->whitelist['modules'])
{
$k_modules = Kohana::modules();
// Have to do this because kohana merges config...
// If you want to include all modules & override defaults then TRUE must be the first
// value in the modules array of your app/config/unittest file
if (array_search(TRUE, $modules, TRUE) === (count($modules) - 1))
{
$modules = $k_modules;
}
elseif (array_search(FALSE, $modules, TRUE) === FALSE)
{
$modules = array_intersect_key($k_modules, array_combine($modules, $modules));
}
else
{
// modules are disabled
$modules = array();
}
$directories += $modules;
}
if ($config->whitelist['system'])
{
$directories['k_sys'] = SYSPATH;
}
return $directories;
}
/**
* 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, Unittest_TestSuite $suite = NULL)
{
foreach ($files as $file)
{
if (is_array($file))
{
self::set_whitelist($file, $suite);
}
else
{
if ( ! isset(Unittest_tests::$cache[$file]))
{
$relative_path = substr($file, strrpos($file, 'classes'.DIRECTORY_SEPARATOR) + 8, -strlen(EXT));
$cascading_file = Kohana::find_file('classes', $relative_path);
// The theory is that if this file is the highest one in the cascading filesystem
// then it's safe to whitelist
Unittest_tests::$cache[$file] = ($cascading_file === $file);
}
if (Unittest_tests::$cache[$file])
{
if (isset($suite))
{
$suite->addFileToWhitelist($file);
}
else
{
PHPUnit_Util_Filter::addFileToWhitelist($file);
}
}
}
}
}
}

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.');
class Unittest_Helpers extends Kohana_Unittest_Helpers {}

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

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

View File

@@ -0,0 +1,34 @@
<?php defined('SYSPATH') or die('No direct script access.');
return array(
// If you don't use a whitelist then only files included during the request will be counted
// If you do, then only whitelisted items will be counted
'use_whitelist' => TRUE,
// Items to whitelist, only used in cli
'whitelist' => array(
// Should the app be whitelisted?
// Useful if you just want to test your application
'app' => TRUE,
// Set to array(TRUE) to include all modules, or use an array of module names
// (the keys of the array passed to Kohana::modules() in the bootstrap)
// Or set to FALSE to exclude all modules
'modules' => array(TRUE),
// If you don't want the Kohana code coverage reports to pollute your app's,
// then set this to FALSE
'system' => TRUE,
),
// Does what it says on the tin
// Blacklisted files won't be included in code coverage reports
// If you use a whitelist then the blacklist will be ignored
'use_blacklist' => FALSE,
// List of individual files/folders to blacklist
'blacklist' => array(
),
);

View File

@@ -0,0 +1,13 @@
<?php defined('SYSPATH') OR die('No direct script access.');
return array
(
'modules' => array(
'unittest' => array(
'enabled' => TRUE,
'name' => 'Unittest',
'description' => 'Unit testing module',
'copyright' => '&copy; 2009-2011 Kohana Team',
)
)
);

View File

@@ -0,0 +1,16 @@
<!--
This is an example phpunit.xml file to get you started
Copy it to a directory, update the relative paths and rename to phpunit.xml
Then to run tests cd into it's directory and just run
phpunit
(it'll automatically use any phpunit.xml file in the current directory)
Any options you specify when calling phpunit will override the ones in here
-->
<phpunit colors="true" bootstrap="rel/path/to/index.php">
<testsuites>
<testsuite name="Kohana Tests">
<file>rel/path/to/unittest/tests.php</file>
</testsuite>
</testsuites>
</phpunit>

View File

@@ -0,0 +1,3 @@
# UnitTest
Unit tests for Kohana

View File

@@ -0,0 +1,5 @@
## [UnitTest]()
- [Mock Objects](mockobjects)
- [Testing](testing)
- [Testing workflows](testing_workflows)
- [Troubleshooting](troubleshooting)

View File

@@ -0,0 +1,265 @@
# Mock objects
Sometimes when writing tests you need to test something that depends on an object being in a certain state.
Say for example you're testing a model - you want to make sure that the model is running the correct query, but you don't want it to run on a real database server. You can create a mock database connection which responds in the way the model expects, but doesn't actually connect to a physical database.
PHPUnit has a built in mock object creator which can generate mocks for classes (inc. abstract ones) on the fly.
It creates a class that extends the one you want to mock. You can also tell PHPUnit to override certain functions to return set values / assert that they're called in a specific way.
## Creating an instance of a mock class
You create mocks from within testcases using the getMock() function, which is defined in `PHPUnit_Framework_TestCase` like so:
getMock($originalClassName, $methods = array(), array $arguments = array(), $mockClassName = '', $callOriginalConstructor = TRUE, $callOriginalClone = TRUE, $callAutoload = TRUE)
`$originalClassName`
: The name of the class that you want to mock
`$methods`
: The methods of $originalClassName that you want to mock.
You need to tell PHPUnit in advance because PHP doesn't allow you to extend an object once it's been initialised.
`$arguments`
: An array of arguments to pass to the mock's constructor
`$mockClassName`
: Allows you to specify the name that will be given to the mock
`$callOriginalConstructor`
: Should the mock call its parent's constructor automatically?
`$callOriginalClone`
: Should the mock call its parent's clone method?
Most of the time you'll only need to use the first two parameters, i.e.:
$mock = $this->getMock('ORM');
`$mock` now contains a mock of ORM and can be handled as though it were a vanilla instance of `ORM`
$mock = $this->getMock('ORM', array('check'));
`$mock` now contains a mock of ORM, but this time we're also mocking the check() method.
## Mocking methods
Assuming we've created a mock object like so:
$mock = $this->getMock('ORM', array('check'));
We now need to tell PHPUnit how to mock the check function when its called.
### How many times should it be called?
You start off by telling PHPUnit how many times the method should be called by calling expects() on the mock object:
$mock->expects($matcher);
`expects()` takes one argument, an invoker matcher which you can create using factory methods defined in `PHPUnit_Framework_TestCase`:
#### Possible invoker matchers:
`$this->any()`
: Returns a matcher that allows the method to be called any number of times
`$this->never()`
: Returns a matcher that asserts that the method is never called
`$this->once()`
: Returns a matcher that asserts that the method is only called once
`$this->atLeastOnce()`
: Returns a matcher that asserts that the method is called at least once
`$this->exactly($count)`
: Returns a matcher that asserts that the method is called at least `$count` times
`$this->at($index)`
: Returns a matcher that matches when the method it is evaluated for is invoked at the given $index.
In our example we want `check()` to be called once on our mock object, so if we update it accordingly:
$mock = $this->getMock('ORM', array('check'));
$mock->expects($this->once());
### What is the method we're mocking?
Although we told PHPUnit what methods we want to mock, we haven't actually told it what method these rules we're specifiying apply to.
You do this by calling `method()` on the returned from `expects()`:
$mock->expects($matcher)
->method($methodName);
As you can probably guess, `method()` takes one parameter, the name of the method you're mocking.
There's nothing very fancy about this function.
$mock = $this->GetMock('ORM', array('check'));
$mock->expects($this->once())
->method('check');
### What parameters should our mock method expect?
There are two ways to do this, either
* Tell the method to accept any parameters
* Tell the method to accept a specific set of parameters
The former can be achieved by calling `withAnyParameters()` on the object returned from `method()`
$mock->expects($matcher)
->method($methodName)
->withAnyParameters();
To only allow specific parameters you can use the `with()` method which accepts any number of parameters.
The order in which you define the parameters is the order that it expects them to be in when called.
$mock->expects($matcher)
->method($methodName)
->with($param1, $param2);
Calling `with()` without any parameters will force the mock method to accept no parameters.
PHPUnit has a fairly complex way of comparing parameters passed to the mock method with the expected values, which can be summarised like so -
* If the values are identical, they are equal
* If the values are of different types they are not equal
* If the values are numbers they they are considered equal if their difference is equal to zero (this level of accuracy can be changed)
* If the values are objects then they are converted to arrays and are compared as arrays
* If the values are arrays then any sub-arrays deeper than x levels (default 10) are ignored in the comparision
* If the values are arrays and one contains more than elements that the other (at any depth up to the max depth), then they are not equal
#### More advanced parameter comparisions
Sometimes you need to be more specific about how PHPUnit should compare parameters, i.e. if you want to make sure that one of the parameters is an instance of an object, yet isn't necessarily identical to a particular instance.
In PHPUnit, the logic for validating objects and datatypes has been refactored into "constraint objects". If you look in any of the assertX() methods you can see that they are nothing more than wrappers for associating constraint objects with tests.
If a parameter passed to `with()` is not an instance of a constraint object (one which extends `PHPUnit_Framework_Constraint`) then PHPUnit creates a new `IsEqual` comparision object for it.
i.e., the following methods produce the same result:
->with('foo', 1);
->with($this->equalTo('foo'), $this->equalTo(1));
Here are some of the wrappers PHPUnit provides for creating constraint objects:
`$this->arrayHasKey($key)`
: Asserts that the parameter will have an element with index `$key`
`$this->attribute(PHPUnit_Framework_Constraint $constraint, $attributeName)`
: Asserts that object attribute `$attributeName` of the parameter will satisfy `$constraint`, where constraint is an instance of a constraint (i.e. `$this->equalTo()`)
`$this->fileExists()`
: Accepts no parameters, asserts that the parameter is a path to a valid file (i.e. `file_exists() === TRUE`)
`$this->greaterThan($value)`
: Asserts that the parameter is greater than `$value`
`$this->anything()`
: Returns TRUE regardless of what the parameter is
`$this->equalTo($value, $delta = 0, $canonicalizeEOL = FALSE, $ignoreCase = False)`
: Asserts that the parameter is equal to `$value` (same as not passing a constraint object to `with()`)
: `$delta` is the degree of accuracy to use when comparing numbers. i.e. 0 means numbers need to be identical, 1 means numbers can be within a distance of one from each other
: If `$canonicalizeEOL` is TRUE then all newlines in string values will be converted to `\n` before comparision
: If `$ignoreCase` is TRUE then both strings will be converted to lowercase before comparision
`$this->identicalTo($value)`
: Asserts that the parameter is identical to `$value`
`$this->isType($type)`
: Asserts that the parameter is of type `$type`, where `$type` is a string representation of the core PHP data types
`$this->isInstanceOf($className)`
: Asserts that the parameter is an instance of `$className`
`$this->lessThan($value)`
: Asserts that the parameter is less than `$value`
`$this->objectHasAttribute($attribute)`
: Asserts that the paramater (which is assumed to be an object) has an attribute `$attribute`
`$this->matchesRegularExpression($pattern)`
: Asserts that the parameter matches the PCRE pattern `$pattern` (using `preg_match()`)
`$this->stringContains($string, $ignoreCase = FALSE)`
: Asserts that the parameter contains the string `$string`. If `$ignoreCase` is TRUE then a case insensitive comparision is done
`$this->stringEndsWith($suffix)`
: Asserts that the parameter ends with `$suffix` (assumes parameter is a string)
`$this->stringStartsWith($prefix)`
: Asserts that the parameter starts with `$prefix` (assumes parameter is a string)
`$this->contains($value)`
: Asserts that the parameter contains at least one value that is identical to `$value` (assumes parameter is array or `SplObjectStorage`)
`$this->containsOnly($type, $isNativeType = TRUE)`
: Asserts that the parameter only contains items of type `$type`. `$isNativeType` should be set to TRUE when `$type` refers to a built in PHP data type (i.e. int, string etc.) (assumes parameter is array)
There are more constraint objects than listed here, look in `PHPUnit_Framework_Assert` and `PHPUnit/Framework/Constraint` if you need more constraints.
If we continue our example, we have the following:
$mock->expects($this->once())
->method('check')
->with();
So far PHPUnit knows that we want the `check()` method to be called once, with no parameters. Now we just need to get it to return something...
### What should the method return?
This is the final stage of mocking a method.
By default PHPUnit can return either
* A fixed value
* One of the parameters that were passed to it
* The return value of a specified callback
Specifying a return value is easy, just call `will()` on the object returned by either `method()` or `with()`.
The function is defined like so:
public function will(PHPUnit_Framework_MockObject_Stub $stub)
PHPUnit provides some MockObject stubs out of the box, you can access them via (when called from a testcase):
`$this->returnValue($value)`
: Returns `$value` when the mocked method is called
`$this->returnArgument($argumentIndex)`
: Returns the `$argumentIndex`th argument that was passed to the mocked method
`$this->returnCallback($callback)`
: Returns the value of the callback, useful for more complicated mocking.
: `$callback` should a valid callback (i.e. `is_callable($callback) === TRUE`). PHPUnit will pass the callback all of the parameters that the mocked method was passed, in the same order / argument index (i.e. the callback is invoked by `call_user_func_array()`).
: You can usually create the callback in your testcase, as long as doesn't begin with "test"
Obviously if you really want to you can create your own MockObject stub, but these three should cover most situations.
Updating our example gives:
$mock->expects($this->once())
->method('check')
->with()
->will($this->returnValue(TRUE));
And we're done!
If you now call `$mock->check()` the value TRUE should be returned.
If you don't call a mocked method and PHPUnit expects it to be called then the test the mock was generated for will fail.
<!--
### What about if the mocked method should change everytime its called?
-->

View File

@@ -0,0 +1,117 @@
# Usage
$ phpunit --bootstrap=modules/unittest/bootstrap.php modules/unittest/tests.php
Alternatively you can use a phpunit.xml to have a more fine grained control over which tests are included and which files are whitelisted.
Make sure you only whitelist the highest files in the cascading filesystem, else you could end up with a lot of "class cannot be redefined" errors.
If you use the tests.php testsuite loader then it will only whitelist the highest files. see config/unittest.php for details on configuring the tests.php whitelist.
## Writing tests
If you're writing a test for your application, place it in "application/tests". Similarly, if you're writing a test for a module place it in modules/[modulefolder]/tests
Rather than tell you how to write tests I'll point you in the direction of the [PHPUnit Manual](http://www.phpunit.de/manual/3.4/en/index.html). One thing you should bear in mind when writing tests is that testcases should extend Unittest_Testcase rather than PHPUnit_Framework_TestCase, doing so gives you access to useful kohana specific helpers such as `setEnvironment()`.
Here's a taster of some of the cool things you can do with phpunit:
### Data Providers
Sometimes you want to be able to run a specific test with different sets of data to try and test every eventuality
Ordinarily you could use a foreach loop to iterate over an array of test data, however PHPUnit already can take care of this for us rather easily using "Data Providers". A data provider is a function that returns an array of arguments that can be passed to a test.
<?php
Class ReallyCoolTest extends Unittest_TestCase
{
function providerStrLen()
{
return array(
array('One set of testcase data', 24),
array('This is a different one', 23),
);
}
/**
* @dataProvider providerStrLen
*/
function testStrLen($string, $length)
{
$this->assertSame(
$length,
strlen($string)
);
}
}
The key thing to notice is the `@dataProvider` tag in the doccomment, this is what tells PHPUnit to use a data provider. The provider prefix is totally optional but it's a nice standard to identify providers.
For more info see:
* [Data Providers in PHPUnit 3.2](http://sebastian-bergmann.de/archives/702-Data-Providers-in-PHPUnit-3.2.html)
* [Data Providers](http://www.phpunit.de/manual/3.4/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers)
### Grouping tests
To allow users to selectively run tests you need to organise your tests into groups. Here's an example test showing how to do this:
<?php
/**
* This is a description for my testcase
*
* @group somegroup
* @group somegroup.morespecific
*/
Class AnotherReallyCoolTest extends Unittest_TestCase
{
/**
* Tests can also be grouped too!
*
* @group somegroup.morespecific.annoyingstuff
*/
function testSomeAnnoyingCase()
{
// CODE!!
}
}
Our convention is to use lowercase group names, with more specific levels in a group seperated by periods. i.e. The Validate helper tests are part of the following groups:
kohana
kohana.validation
kohana.validation.helpers
To actually limit your testing to the "somegroup" group, use:
$ phpunit --boostrap=index.php --group=somegroup modules/unittest/tests.php
This functionality can be used to record which bug reports a test is for:
/**
*
* @group bugs.1477
*/
function testAccountCannotGoBelowZero()
{
// Some arbitary code
}
To see all groups that are available in your code run:
$ phpunit --boostrap=modules/unittest/bootstrap.php --list-groups modules/unittest/tests.php
*Note:* the `--list-groups` switch should appear before the path to the test suite loader
You can also exclude groups while testing using the `--exclude-group` switch. This can be useful if you want to ignore all kohana tests:
$ phpunit --bootstrap=modules/unittest/bootstrap.php --exclude-group=kohana modules/unittest/tests.php
For more info see:
* [Better PHPUnit Group Annotations](http://mikenaberezny.com/2007/09/04/better-phpunit-group-annotations/)
* [TestNG style Grouping of Tests in PHPUnit 3.2](http://sebastian-bergmann.de/archives/697-TestNG-style-Grouping-of-Tests.html)

View File

@@ -0,0 +1,41 @@
# Testing workflows
Having unittests for your application is a nice idea, but unless you actually use them they're about as useful as a chocolate firegaurd. There are quite a few ways of getting tests "into" your development process and this guide aims to cover a few of them.
## Integrating with IDEs
Modern IDEs have come a long way in the last couple of years and ones like netbeans have pretty decent PHP / PHPUnit support.
### Netbeans (6.8+)
*Note:* Netbeans runs under the assumption that you only have one tests folder per project.
If you want to run tests across multiple modules it might be best creating a separate project for each module.
0. Install the unittest module
1. Open the project which you want to enable phpunit testing for.
2. Now open the project's properties dialouge and in the "Tests Dir" field enter the path to your module's (or application's) test directory.
In this case the only tests in this project are within the unittest module
3. Select the phpunit section from the left hand pane and in the area labelled bootstrap enter the path to your app's index.php file
You can also specify a custom test suite loader (enter the path to your tests.php file) and/or a custom configuration file (enter the path to your phpunit.xml file)
## Looping shell
If you're developing in a text editor such as textmate, vim, gedit etc. chances are phpunit support isn't natively supported by your editor.
In such situations you can run a simple bash script to loop over the tests every X seconds, here's an example script:
while(true) do clear; phpunit; sleep 8; done;
You will probably need to adjust the timeout (`sleep 8`) to suit your own workflow, but 8 seconds seems to be about enough time to see what's erroring before the tests are re-run.
In the above example we're using a phpunit.xml config file to specify all the unit testing settings & to reduce the complexity of the looping script.
## Continuous Integration (CI)
Continuous integration is a team based tool which enables developers to keep tabs on whether changes committed to a project break the application. If a commit causes a test to fail then the build is classed as "broken" and the CI server then alerts developers by email, RSS, IM or glowing (bears|lava lamps) to the fact that someone has broken the build and that all hell's broken lose.
The two more popular CI servers are [Hudson](https://hudson.dev.java.net/) and [phpUnderControl](http://www.phpundercontrol.org/about.html), both of which use [Phing](http://phing.info/) to run the build tasks for your application.

View File

@@ -0,0 +1,21 @@
# Troubleshooting
## I get the error "Class Kohana_Tests could not be found" when testing from the CLI
You need to running PHPUnit >= 3.4, there is a bug in 3.3 which causes this.
## Some of my classes aren't getting whitelisted for code coverage even though their module is
Only the "highest" files in the cascading filesystem are whitelisted for code coverage.
To test your module's file, remove the higher file from the cascading filesystem by disabling their respective module.
A good way of testing is to create a "vanilla" testing environment for your module, devoid of anything that isn't required by the module.
## I get a blank page when trying to generate a code coverage report
Try the following:
1. Generate a html report from the command line using `phpunit {bootstrap info} --coverage-html ./report {insert path to tests.php}`. If any error messages show up, fix them and try to generate the report again
2. Increase the php memory limit
3. Make sure that display_errors is set to "on" in your php.ini config file (this value can sometimes be overriden in a .htaccess file)

View File

@@ -0,0 +1,20 @@
<?php
if ( ! class_exists('Kohana'))
{
die('Please include the kohana bootstrap file (see README.markdown)');
}
if ($file = Kohana::find_file('classes', 'Unittest/Tests'))
{
require_once $file;
// PHPUnit requires a test suite class to be in this file,
// so we create a faux one that uses the kohana base
class TestSuite extends Unittest_Tests
{}
}
else
{
die('Could not include the test suite');
}