Added Kohana v3.0.8

This commit is contained in:
Deon George
2010-08-21 14:43:03 +10:00
parent 27aee719b0
commit 64bdbdc981
558 changed files with 58712 additions and 0 deletions

View File

@@ -0,0 +1,461 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests the Arr lib that's shipped with kohana
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_ArrTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_callback()
*
* @return array
*/
public function provider_callback()
{
return array(
// Tests....
// That no parameters returns null
array('function', array('function', NULL)),
// That we can get an array of parameters values
array('function(1,2,3)', array('function', array('1', '2', '3'))),
// That it's not just using the callback "function"
array('different_name(harry,jerry)', array('different_name', array('harry', 'jerry'))),
// That static callbacks are parsed into arrays
array('kohana::appify(this)', array(array('kohana', 'appify'), array('this'))),
// Spaces are preserved in parameters
array('deal::make(me, my mate )', array(array('deal', 'make'), array('me', ' my mate ')))
// TODO: add more cases
);
}
/**
* Tests Arr::callback()
*
* @test
* @dataProvider provider_callback
* @param string $str String to parse
* @param array $expected Callback and its parameters
*/
public function test_callback($str, $expected)
{
$result = Arr::callback($str);
$this->assertSame(2, count($result));
$this->assertSame($expected, $result);
}
/**
* Provides test data for test_extract
*
* @return array
*/
public function provider_extract()
{
return array(
array(
array('kohana' => 'awesome', 'blueflame' => 'was'),
array('kohana', 'cakephp', 'symfony'),
NULL,
array('kohana' => 'awesome', 'cakephp' => NULL, 'symfony' => NULL)
),
// I realise noone should EVER code like this in real life,
// but unit testing is very very very very boring
array(
array('chocolate cake' => 'in stock', 'carrot cake' => 'in stock'),
array('carrot cake', 'humble pie'),
'not in stock',
array('carrot cake' => 'in stock', 'humble pie' => 'not in stock'),
),
);
}
/**
* Tests Arr::extract()
*
* @test
* @dataProvider provider_extract
* @param array $array
* @param array $keys
* @param mixed $default
* @param array $expected
*/
public function test_extract(array $array, array $keys, $default, $expected)
{
$array = Arr::extract($array, $keys, $default);
$this->assertSame(count($expected), count($array));
$this->assertSame($expected, $array);
}
/**
* Provides test data for test_get()
*
* @return array
*/
public function provider_get()
{
return array(
array(array('uno', 'dos', 'tress'), 1, NULL, 'dos'),
array(array('we' => 'can', 'make' => 'change'), 'we', NULL, 'can'),
array(array('uno', 'dos', 'tress'), 10, NULL, NULL),
array(array('we' => 'can', 'make' => 'change'), 'he', NULL, NULL),
array(array('we' => 'can', 'make' => 'change'), 'he', 'who', 'who'),
array(array('we' => 'can', 'make' => 'change'), 'he', array('arrays'), array('arrays')),
);
}
/**
* Tests Arr::get()
*
* @test
* @dataProvider provider_get()
* @param array $array Array to look in
* @param string|integer $key Key to look for
* @param mixed $default What to return if $key isn't set
* @param mixed $expected The expected value returned
*/
public function test_get(array $array, $key, $default, $expected)
{
$this->assertSame(
$expected,
Arr::get($array, $key, $default)
);
}
/**
* Provides test data for test_is_assoc()
*
* @return array
*/
public function provider_is_assoc()
{
return array(
array(array('one', 'two', 'three'), FALSE),
array(array('one' => 'o clock', 'two' => 'o clock', 'three' => 'o clock'), TRUE),
);
}
/**
* Tests Arr::is_assoc()
*
* @test
* @dataProvider provider_is_assoc
* @param array $array Array to check
* @param boolean $expected Is $array assoc
*/
public function test_is_assoc(array $array, $expected)
{
$this->assertSame(
$expected,
Arr::is_assoc($array)
);
}
public function provider_merge()
{
return array(
// Test how it merges arrays and sub arrays with assoc keys
array(
array('name' => 'mary', 'children' => array('fred', 'paul', 'sally', 'jane')),
array('name' => 'john', 'children' => array('fred', 'paul', 'sally', 'jane')),
array('name' => 'mary', 'children' => array('jane')),
),
// See how it merges sub-arrays with numerical indexes
array(
array(array('test1','test3'), array('test2','test4')),
array(array('test1'), array('test2')),
array(array('test3'), array('test4')),
),
array(
array('digits' => array(0, 1, 2, 3)),
array('digits' => array(0, 1)),
array('digits' => array(2, 3)),
),
// See how it manages merging items with numerical indexes
array(
array(0, 1, 2, 3),
array(0, 1),
array(2, 3),
),
// Try and get it to merge assoc. arrays recursively
array(
array('foo' => 'bar', array('temp' => 'life')),
array('foo' => 'bin', array('temp' => 'name')),
array('foo' => 'bar', array('temp' => 'life')),
),
// Bug #3139
array(
array('foo' => array('bar')),
array('foo' => 'bar'),
array('foo' => array('bar')),
),
array(
array('foo' => 'bar'),
array('foo' => array('bar')),
array('foo' => 'bar'),
),
);
}
/**
*
* @test
* @dataProvider provider_merge
*/
public function test_merge($expected, $array1, $array2)
{
$this->assertSame(
$expected,
Arr::merge($array1,$array2)
);
}
/**
* Provides test data for test_get()
*
* @return array
*/
public function provider_path()
{
$array = array(
'foobar' => array('definition' => 'lost'),
'kohana' => 'awesome',
'users' => array(
1 => array('name' => 'matt'),
2 => array('name' => 'john', 'interests' => array('hocky' => array('length' => 2), 'football' => array())),
),
);
return array(
// Tests returns normal values
array($array['foobar'], $array, 'foobar'),
array($array['kohana'], $array, 'kohana'),
array($array['foobar']['definition'], $array, 'foobar.definition'),
// Custom delimiters
array($array['foobar']['definition'], $array, 'foobar/definition', NULL, '/'),
// We should be able to use NULL as a default, returned if the key DNX
array(NULL, $array, 'foobar.alternatives', NULL),
array(NULL, $array, 'kohana.alternatives', NULL),
// Try using a string as a default
array('nothing', $array, 'kohana.alternatives', 'nothing'),
// Make sure you can use arrays as defaults
array(array('far', 'wide'), $array, 'cheese.origins', array('far', 'wide')),
// Ensures path() casts ints to actual integers for keys
array($array['users'][1]['name'], $array, 'users.1.name'),
// Test that a wildcard returns the entire array at that "level"
array($array['users'], $array, 'users.*'),
// Now we check that keys after a wilcard will be processed
array(array(0 => array(0 => 2)), $array, 'users.*.interests.*.length'),
// See what happens when it can't dig any deeper from a wildcard
array(NULL, $array, 'users.*.fans'),
);
}
/**
* Tests Arr::get()
*
* @test
* @dataProvider provider_path
* @param string $path The path to follow
* @param mixed $default The value to return if dnx
* @param boolean $expected The expected value
* @param string $delimiter The path delimiter
*/
public function test_path($expected, $array, $path, $default = NULL, $delimiter = NULL)
{
$this->assertSame(
$expected,
Arr::path($array, $path, $default, $delimiter)
);
}
/**
* Provides test data for test_range()
*
* @return array
*/
public function provider_range()
{
return array(
array(1, 2),
array(1, 100),
array(25, 10),
);
}
/**
* Tests Arr::range()
*
* @dataProvider provider_range
* @param integer $step The step between each value in the array
* @param integer $max The max value of the range (inclusive)
*/
public function test_range($step, $max)
{
$range = Arr::range($step, $max);
$this->assertSame((int) floor($max / $step), count($range));
$current = $step;
foreach($range as $key => $value)
{
$this->assertSame($key, $value);
$this->assertSame($current, $key);
$this->assertLessThanOrEqual($max, $key);
$current += $step;
}
}
/**
* Provides test data for test_unshift()
*
* @return array
*/
public function provider_unshift()
{
return array(
array(array('one' => '1', 'two' => '2',), 'zero', '0'),
array(array('step 1', 'step 2', 'step 3'), 'step 0', 'wow')
);
}
/**
* Tests Arr::unshift()
*
* @test
* @dataProvider provider_unshift
* @param array $array
* @param string $key
* @param mixed $value
*/
public function test_unshift(array $array, $key, $value)
{
$original = $array;
Arr::unshift($array, $key, $value);
$this->assertNotSame($original, $array);
$this->assertSame(count($original) + 1, count($array));
$this->assertArrayHasKey($key, $array);
$this->assertSame($value, reset($array));
$this->assertSame(key($array), $key);
}
/**
* Provies test data for test_overwrite
*
* @return array Test Data
*/
public function provider_overwrite()
{
return array(
array(
array('name' => 'Henry', 'mood' => 'tired', 'food' => 'waffles', 'sport' => 'checkers'),
array('name' => 'John', 'mood' => 'bored', 'food' => 'bacon', 'sport' => 'checkers'),
array('name' => 'Matt', 'mood' => 'tired', 'food' => 'waffles'),
array('name' => 'Henry', 'age' => 18,),
),
);
}
/**
*
* @test
* @dataProvider provider_overwrite
*/
public function test_overwrite($expected, $arr1, $arr2, $arr3 = array(), $arr4 = array())
{
$this->assertSame(
$expected,
Arr::overwrite($arr1, $arr2, $arr3, $arr4)
);
}
/**
* Provides test data for test_binary_search
*
* @return array Test Data
*/
public function provider_binary_search()
{
return array(
array(2, 'john', array('mary', 'louise', 'john', 'kent'))
);
}
/**
*
* @test
* @dataProvider provider_binary_search
*/
public function test_binary_search($expected, $needle, $haystack, $sort = FALSE)
{
$this->assertSame(
$expected,
Arr::binary_search($needle, $haystack, $sort)
);
}
/**
* Provides test data for test_map
*
* @return array Test Data
*/
public function provider_map()
{
return array(
array('strip_tags', array('<p>foobar</p>'), array('foobar')),
array('strip_tags', array(array('<p>foobar</p>'), array('<p>foobar</p>')), array(array('foobar'), array('foobar'))),
);
}
/**
*
* @test
* @dataProvider provider_map
*/
public function test_map($method, $source, $expected)
{
$this->assertSame(
$expected,
Arr::map($method, $source)
);
}
/**
* Provides test data for test_flatten
*
* @return array Test Data
*/
public function provider_flatten()
{
return array(
array(array('set' => array('one' => 'something'), 'two' => 'other'), array('one' => 'something', 'two' => 'other')),
);
}
/**
*
* @test
* @dataProvider provider_flatten
*/
public function test_flatten($source, $expected)
{
$this->assertSame(
$expected,
Arr::flatten($source)
);
}
}

View File

@@ -0,0 +1,167 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Unit tests for CLI
*
* Based on the Kohana-unittest test
*
* @group kohana
* @group kohana.cli
*
* @see CLI
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_CLITest extends Kohana_Unittest_TestCase
{
/**
* Tell PHPUnit to isolate globals during tests
* @var boolean
*/
protected $backupGlobals = TRUE;
/**
* An array of arguments to put in $_SERVER['argv']
* @var array
*/
protected $options = array(
'--uri' => 'test/something',
'--we_are_cool',
'invalid option',
'--version' => '2.23',
'--important' => 'something=true',
'--name' => 'Jeremy Taylor',
);
/**
* Setup the enviroment for each test
*
* PHPUnit automatically backups up & restores global variables
*/
public function setUp()
{
parent::setUp();
$_SERVER['argv'] = array('index.php');
foreach($this->options as $option => $value)
{
if(is_string($option))
{
$_SERVER['argv'][] = $option.'='.$value;
}
else
{
$_SERVER['argv'][] = $value;
}
}
$_SERVER['argc'] = count($_SERVER['argv']);
}
/**
* If for some reason arc != count(argv) then we need
* to fail gracefully.
*
* This test ensures it will
*
* @test
*/
public function test_only_loops_over_available_arguments()
{
++$_SERVER['argc'];
$options = CLI::options('uri');
$this->assertSame(1, count($options));
}
/**
* Options should only parse arguments requested
*
* @test
*/
public function test_only_parses_wanted_arguments()
{
$options = CLI::options('uri');
$this->assertSame(1, count($options));
$this->assertArrayHasKey('uri', $options);
$this->assertSame($options['uri'], $this->options['--uri']);
}
/**
* Options should not parse invalid arguments (i.e. not starting with --_
*
* @test
*/
public function test_does_not_parse_invalid_arguments()
{
$options = CLI::options('uri', 'invalid');
$this->assertSame(1, count($options));
$this->assertArrayHasKey('uri', $options);
$this->assertArrayNotHasKey('invalid', $options);
}
/**
* Options should parse multiple arguments & values correctly
*
* @test
*/
public function test_parses_multiple_arguments()
{
$options = CLI::options('uri', 'version');
$this->assertSame(2, count($options));
$this->assertArrayHasKey('uri', $options);
$this->assertArrayHasKey('version', $options);
$this->assertSame($this->options['--uri'], $options['uri']);
$this->assertSame($this->options['--version'], $options['version']);
}
/**
* Options should parse arguments without specified values as NULL
*
* @test
*/
public function test_parses_arguments_without_value_as_null()
{
$options = CLI::options('uri', 'we_are_cool');
$this->assertSame(2, count($options));
$this->assertSame(NULL, $options['we_are_cool']);
}
/**
* If the argument contains an equals sign then it shouldn't be split
*
* @test
* @ticket 2642
*/
public function test_cli_only_splits_on_the_first_equals()
{
$options = CLI::options('important');
$this->assertSame(1, count($options));
$this->assertSame('something=true', reset($options));
}
/**
* Arguments enclosed with quote marks should be allowed to contain
* spaces
*
* @test
*/
public function test_value_includes_spaces_when_enclosed_with_quotes()
{
$options = CLI::options('name');
$this->assertSame(array('name' => 'Jeremy Taylor'), $options);
}
}

View File

@@ -0,0 +1,243 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests the Config lib that's shipped with kohana
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @author Matt Button <matthew@sigswitch.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_ConfigTest extends Kohana_Unittest_TestCase
{
/**
* Calling Kohana_Config::instance() should return the global singleton
* which should persist
*
* @test
* @covers Kohana_Config::instance
*/
public function test_instance_returns_singleton_instance()
{
$this->assertSame(Kohana_Config::instance(), Kohana_Config::instance());
$this->assertNotSame(new Kohana_Config, Kohana_Config::instance());
}
/**
* When a config object is initially created there should be
* no readers attached
*
* @test
* @covers Kohana_Config
*/
public function test_initially_there_are_no_readers()
{
$config = new Kohana_Config;
$this->assertAttributeSame(array(), '_readers', $config);
}
/**
* Test that calling attach() on a kohana config object
* adds the specified reader to the config object
*
* @test
* @covers Kohana_Config::attach
*/
public function test_attach_adds_reader_and_returns_this()
{
$config = new Kohana_Config;
$reader = $this->getMock('Kohana_Config_Reader');
$this->assertSame($config, $config->attach($reader));
$this->assertAttributeContains($reader, '_readers', $config);
}
/**
* By default (or by passing TRUE as the second parameter) the config object
* should prepend the reader to the front of the readers queue
*
* @test
* @covers Kohana_Config::attach
*/
public function test_attach_adds_reader_to_front_of_queue()
{
$config = new Kohana_Config;
$reader1 = $this->getMock('Kohana_Config_Reader');
$reader2 = $this->getMock('Kohana_Config_Reader');
$config->attach($reader1);
$config->attach($reader2);
// Rather than do two assertContains we'll do an assertSame to assert
// the order of the readers
$this->assertAttributeSame(array($reader2, $reader1), '_readers', $config);
// Now we test using the second parameter
$config = new Kohana_Config;
$config->attach($reader1);
$config->attach($reader2, TRUE);
$this->assertAttributeSame(array($reader2, $reader1), '_readers', $config);
}
/**
* Test that attaching a new reader (and passing FALSE as second param) causes
* phpunit to append the reader rather than prepend
*
* @test
* @covers Kohana_Config::attach
*/
public function test_attach_can_add_reader_to_end_of_queue()
{
$config = new Kohana_Config;
$reader1 = $this->getMock('Kohana_Config_Reader');
$reader2 = $this->getMock('Kohana_Config_Reader');
$config->attach($reader1);
$config->attach($reader2, FALSE);
$this->assertAttributeSame(array($reader1, $reader2), '_readers', $config);
}
/**
* Calling detach() on a config object should remove it from the queue of readers
*
* @test
* @covers Kohana_Config::detach
*/
public function test_detach_removes_reader_and_returns_this()
{
$config = new Kohana_Config;
// Due to the way phpunit mock generator works if you try and mock a class
// that has already been used then it just re-uses the first's name
//
// To get around this we have to specify a totally random name for the second mock object
$reader1 = $this->getMock('Kohana_Config_Reader');
$reader2 = $this->getMock('Kohana_Config_Reader', array(), array(), 'MY_AWESOME_READER');
$config->attach($reader1);
$config->attach($reader2);
$this->assertSame($config, $config->detach($reader1));
$this->assertAttributeNotContains($reader1, '_readers', $config);
$this->assertAttributeContains($reader2, '_readers', $config);
$this->assertSame($config, $config->detach($reader2));
$this->assertAttributeNotContains($reader2, '_readers', $config);
}
/**
* detach() should return $this even if the specified reader does not exist
*
* @test
* @covers Kohana_Config::detach
*/
public function test_detach_returns_this_even_when_reader_dnx()
{
$config = new Kohana_Config;
$reader = $this->getMock('Kohana_Config_Reader');
$this->assertSame($config, $config->detach($reader));
}
/**
* If load() is called and there are no readers present then it should throw
* a kohana exception
*
* @test
* @covers Kohana_Config::load
* @expectedException Kohana_Exception
*/
public function test_load_throws_exception_if_there_are_no_readers()
{
// The following code should throw an exception and phpunit will catch / handle it
// (see the @expectedException doccomment)
$config = new Kohana_config;
$config->load('random');
}
/**
* When load() is called it should interrogate each reader in turn until a match
* is found
*
* @test
* @covers Kohana_Config::load
*/
public function test_load_interrogates_each_reader_until_group_found()
{
$config = new Kohana_Config;
$config_group = 'groupy';
$reader1 = $this->getMock('Kohana_Config_Reader', array('load'));
$reader1
->expects($this->once())
->method('load')
->with($config_group)
->will($this->returnValue(FALSE));
$reader2 = $this->getMock('Kohana_Config_Reader', array('load'));
$reader2
->expects($this->once())
->method('load')
->with($config_group)
->will($this->returnValue($reader2));
$reader3 = $this->getMock('Kohana_Config_Reader', array('load'));
$reader3->expects($this->never())->method('load');
$config->attach($reader1, FALSE);
$config->attach($reader2, FALSE);
$config->attach($reader3, FALSE);
// By asserting a return type we're making the test a little less brittle / less likely
// to break due to minor modifications
$this->assertType('Kohana_Config_Reader', $config->load($config_group));
}
/**
* Calling load() with a group that doesn't exist, should get it to use the last reader
* to create a new config group
*
* @test
* @covers Kohana_Config::load
*/
public function test_load_returns_new_config_group_if_one_dnx()
{
$config = new Kohana_Config;
$group = 'my_group';
$reader1 = $this->getMock('Kohana_Config_Reader');
$reader2 = $this->getMock('Kohana_Config_Reader', array('load'), array(), 'Kohana_Config_Waffles');
// This is a slightly hacky way of doing it, but it works
$reader2
->expects($this->exactly(2))
->method('load')
->with($group)
->will($this->onConsecutiveCalls(
$this->returnValue(FALSE),
$this->returnValue(clone $reader2)
));
$config->attach($reader1)->attach($reader2);
$new_config = $config->load('my_group');
$this->assertType('Kohana_Config_Waffles', $new_config);
// Slightly taboo, testing a different api!!
$this->assertSame(array(), $new_config->as_array());
}
}

View File

@@ -0,0 +1,130 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests the cookie class
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_CookieTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_set()
*
* @return array
*/
public function provider_set()
{
return array(
array('foo', 'bar', NULL, TRUE),
array('foo', 'bar', 10, TRUE),
);
}
/**
* Tests cookie::set()
*
* @test
* @dataProvider provider_set
* @covers cookie::set
* @param mixed $key key to use
* @param mixed $value value to set
* @param mixed $exp exp to set
* @param boolean $expected Output for cookie::set()
*/
public function test_set($key, $value, $exp, $expected)
{
$this->assertSame($expected, cookie::set($key, $value, $exp));
}
/**
* Provides test data for test_get()
*
* @return array
*/
public function provider_get()
{
return array(
array('foo', Cookie::salt('foo', 'bar').'~bar', 'bar'),
array('bar', Cookie::salt('foo', 'bar').'~bar', NULL),
array(NULL, Cookie::salt('foo', 'bar').'~bar', NULL),
);
}
/**
* Tests cookie::set()
*
* @test
* @dataProvider provider_get
* @covers cookie::get
* @param mixed $key key to use
* @param mixed $value value to set
* @param boolean $expected Output for cookie::get()
*/
public function test_get($key, $value, $expected)
{
// Force $_COOKIE
if ($key !== NULL)
$_COOKIE[$key] = $value;
$this->assertSame($expected, cookie::get($key));
}
/**
* Provides test data for test_delete()
*
* @return array
*/
public function provider_delete()
{
return array(
array('foo', TRUE),
);
}
/**
* Tests cookie::delete()
*
* @test
* @dataProvider provider_delete
* @covers cookie::delete
* @param mixed $key key to use
* @param boolean $expected Output for cookie::delete()
*/
public function test_delete($key, $expected)
{
$this->assertSame($expected, cookie::delete($key));
}
/**
* Provides test data for test_salt()
*
* @return array
*/
public function provider_salt()
{
return array(
array('foo', 'bar', '795317c9df04d8061e6e134a9b3487dc9ad69117'),
);
}
/**
* Tests cookie::salt()
*
* @test
* @dataProvider provider_salt
* @covers cookie::salt
* @param mixed $key key to use
* @param mixed $value value to salt with
* @param boolean $expected Output for cookie::delete()
*/
public function test_salt($key, $value, $expected)
{
$this->assertSame($expected, cookie::salt($key, $value));
}
}

View File

@@ -0,0 +1,462 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana Core
*
* @TODO Use a virtual filesystem (see phpunit doc on mocking fs) for find_file etc.
*
* @group kohana
* @group kohana.core
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_CoreTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_sanitize()
*
* @return array
*/
public function provider_sanitize()
{
return array(
// $value, $result
array('foo', 'foo'),
array("foo\r\nbar", "foo\nbar"),
array("foo\rbar", "foo\nbar"),
array("Is your name O\'reilly?", "Is your name O'reilly?")
);
}
/**
* Tests Kohana::santize()
*
* @test
* @dataProvider provider_sanitize
* @covers Kohana::sanitize
* @param boolean $value Input for Kohana::sanitize
* @param boolean $result Output for Kohana::sanitize
*/
public function test_sanitize($value, $result)
{
$this->setEnvironment(array('Kohana::$magic_quotes' => TRUE));
$this->assertSame($result, Kohana::sanitize($value));
}
/**
* If a file can't be found then find_file() should return FALSE if
* only a single file was requested, or an empty array if multiple files
* (i.e. configuration files) were requested
*
* @test
* @covers Kohana::find_file
*/
public function test_find_file_returns_false_or_array_on_failure()
{
$this->assertFalse(Kohana::find_file('configy', 'zebra'));
$this->assertSame(array(), Kohana::find_file('configy', 'zebra', NULL, TRUE));
}
/**
* Kohana::list_files() should return an array on success and an empty array on failure
*
* @test
* @covers Kohana::list_files
*/
public function test_list_files_returns_array_on_success_and_failure()
{
$files = Kohana::list_files('config');
$this->assertType('array', $files);
$this->assertGreaterThan(3, count($files));
$this->assertSame(array(), Kohana::list_files('geshmuck'));
}
/**
* Tests Kohana::globals()
*
* @test
* @covers Kohana::globals
*/
public function test_globals_removes_user_def_globals()
{
$GLOBALS = array('hackers' => 'foobar','name' => array('','',''), '_POST' => array());
Kohana::globals();
$this->assertEquals(array('_POST' => array()), $GLOBALS);
}
/**
* Provides test data for testCache()
*
* @return array
*/
public function provider_cache()
{
return array(
// $value, $result
array('foo', 'hello, world', 10),
array('bar', NULL, 10),
array('bar', NULL, -10),
);
}
/**
* Tests Kohana::cache()
*
* @test
* @dataProvider provider_cache
* @covers Kohana::cache
* @param boolean $key Key to cache/get for Kohana::cache
* @param boolean $value Output from Kohana::cache
* @param boolean $lifetime Lifetime for Kohana::cache
*/
public function test_cache($key, $value, $lifetime)
{
Kohana::cache($key, $value, $lifetime);
$this->assertEquals($value, Kohana::cache($key));
}
/**
* Provides test data for test_message()
*
* @return array
*/
public function provider_message()
{
return array(
// $value, $result
array(':field must not be empty', 'validate', 'not_empty'),
array(
array(
'alpha' => ':field must contain only letters',
'alpha_dash' => ':field must contain only letters and dashes',
'alpha_numeric' => ':field must contain only letters and numbers',
'color' => ':field must be a color',
'credit_card' => ':field must be a credit card number',
'date' => ':field must be a date',
'decimal' => ':field must be a decimal with :param1 places',
'digit' => ':field must be a digit',
'email' => ':field must be a email address',
'email_domain' => ':field must contain a valid email domain',
'exact_length' => ':field must be exactly :param1 characters long',
'in_array' => ':field must be one of the available options',
'ip' => ':field must be an ip address',
'matches' => ':field must be the same as :param1',
'min_length' => ':field must be at least :param1 characters long',
'max_length' => ':field must be less than :param1 characters long',
'phone' => ':field must be a phone number',
'not_empty' => ':field must not be empty',
'range' => ':field must be within the range of :param1 to :param2',
'regex' => ':field does not match the required format',
'url' => ':field must be a url',
),
'validate', NULL,
),
);
}
/**
* Tests Kohana::message()
*
* @test
* @dataProvider provider_message
* @covers Kohana::message
* @param boolean $expected Output for Kohana::message
* @param boolean $file File to look in for Kohana::message
* @param boolean $key Key for Kohana::message
*/
public function test_message($expected, $file, $key)
{
$this->assertEquals($expected, Kohana::message($file, $key));
}
/**
* Provides test data for test_error_handler()
*
* @return array
*/
public function provider_error_handler()
{
return array(
array(1, 'Foobar', 'foobar.php', __LINE__),
);
}
/**
* Tests Kohana::error_handler()
*
* @test
* @dataProvider provider_error_handler
* @covers Kohana::error_handler
* @param boolean $code Input for Kohana::sanitize
* @param boolean $error Input for Kohana::sanitize
* @param boolean $file Input for Kohana::sanitize
* @param boolean $line Output for Kohana::sanitize
*/
public function test_error_handler($code, $error, $file, $line)
{
$error_level = error_reporting();
error_reporting(E_ALL);
try
{
Kohana::error_handler($code, $error, $file, $line);
}
catch (Exception $e)
{
$this->assertEquals($code, $e->getCode());
$this->assertEquals($error, $e->getMessage());
}
error_reporting($error_level);
}
/**
* Provides test data for testExceptionHandler()
*
* @return array
*/
public function provider_exception_handler()
{
return array(
// $exception_type, $message, $is_cli, $expected
array('Kohana_Exception', 'hello, world!', TRUE, TRUE, 'hello, world!'),
array('ErrorException', 'hello, world!', TRUE, TRUE, 'hello, world!'),
// #3016
array('Kohana_Exception', '<hello, world!>', FALSE, TRUE, '&lt;hello, world!&gt;'),
);
}
/**
* Tests Kohana::exception_handler()
*
* @test
* @dataProvider provider_exception_handler
* @covers Kohana::exception_handler
* @param boolean $exception_type Exception type to throw
* @param boolean $message Message to pass to exception
* @param boolean $is_cli Use cli mode?
* @param boolean $expected Output for Kohana::exception_handler
* @param string $expexcted_message What to look for in the output string
*/
public function teste_exception_handler($exception_type, $message, $is_cli, $expected, $expected_message)
{
try
{
Kohana::$is_cli = $is_cli;
throw new $exception_type($message);
}
catch (Exception $e)
{
ob_start();
$this->assertEquals($expected, Kohana::exception_handler($e));
$view = ob_get_contents();
ob_clean();
$this->assertContains($expected_message, $view);
}
Kohana::$is_cli = TRUE;
}
/**
* Provides test data for test_debug()
*
* @return array
*/
public function provider_debug()
{
return array(
// $exception_type, $message, $is_cli, $expected
array(array('foobar'), "<pre class=\"debug\"><small>array</small><span>(1)</span> <span>(\n 0 => <small>string</small><span>(6)</span> \"foobar\"\n)</span></pre>"),
);
}
/**
* Tests Kohana::debug()
*
* @test
* @dataProvider provider_debug
* @covers Kohana::debug
* @param boolean $thing The thing to debug
* @param boolean $expected Output for Kohana::debug
*/
public function testdebug($thing, $expected)
{
$this->assertEquals($expected, Kohana::debug($thing));
}
/**
* Provides test data for testDebugPath()
*
* @return array
*/
public function provider_debug_path()
{
return array(
array(
Kohana::find_file('classes', 'kohana'),
'SYSPATH'.DIRECTORY_SEPARATOR.'classes'.DIRECTORY_SEPARATOR.'kohana.php'
),
array(
Kohana::find_file('classes', $this->dirSeparator('kohana/unittest/runner')),
$this->dirSeparator('MODPATH/unittest/classes/kohana/unittest/runner.php')
),
);
}
/**
* Tests Kohana::debug_path()
*
* @test
* @dataProvider provider_debug_path
* @covers Kohana::debug_path
* @param boolean $path Input for Kohana::debug_path
* @param boolean $expected Output for Kohana::debug_path
*/
public function testDebugPath($path, $expected)
{
$this->assertEquals($expected, Kohana::debug_path($path));
}
/**
* Provides test data for test_modules_sets_and_returns_valid_modules()
*
* @return array
*/
public function provider_modules_sets_and_returns_valid_modules()
{
return array(
array(array(), array()),
array(array('unittest' => MODPATH.'fo0bar'), array()),
array(array('unittest' => MODPATH.'unittest'), array('unittest' => $this->dirSeparator(MODPATH.'unittest/'))),
);
}
/**
* Tests Kohana::modules()
*
* @test
* @dataProvider provider_modules_sets_and_returns_valid_modules
* @covers Kohana::modules
* @param boolean $source Input for Kohana::modules
* @param boolean $expected Output for Kohana::modules
*/
public function test_modules_sets_and_returns_valid_modules($source, $expected)
{
$modules = Kohana::modules();
$this->assertEquals($expected, Kohana::modules($source));
Kohana::modules($modules);
}
/**
* To make the tests as portable as possible this just tests that
* you get an array of modules when you can Kohana::modules() and that
* said array contains unittest
*
* @test
* @covers Kohana::modules
*/
public function test_modules_returns_array_of_modules()
{
$modules = Kohana::modules();
$this->assertType('array', $modules);
$this->assertArrayHasKey('unittest', $modules);
}
/**
* Tests Kohana::include_paths()
*
* The include paths must contain the apppath and syspath
* @test
* @covers Kohana::include_paths
*/
public function test_include_paths()
{
$include_paths = Kohana::include_paths();
$modules = Kohana::modules();
$this->assertType('array', $include_paths);
// We must have at least 2 items in include paths (APP / SYS)
$this->assertGreaterThan(2, count($include_paths));
// Make sure said paths are in the include paths
// And make sure they're in the correct positions
$this->assertSame(APPPATH, reset($include_paths));
$this->assertSame(SYSPATH, end($include_paths));
foreach($modules as $module)
{
$this->assertContains($module, $include_paths);
}
}
/**
* Provides test data for test_exception_text()
*
* @return array
*/
public function provider_exception_text()
{
return array(
array(new Kohana_Exception('foobar'), $this->dirSeparator('Kohana_Exception [ 0 ]: foobar ~ SYSPATH/tests/kohana/CoreTest.php [ '.__LINE__.' ]')),
);
}
/**
* Tests Kohana::exception_text()
*
* @test
* @dataProvider provider_exception_text
* @covers Kohana::exception_text
* @param object $exception exception to test
* @param string $expected expected output
*/
public function test_exception_text($exception, $expected)
{
$this->assertEquals($expected, Kohana::exception_text($exception));
}
/**
* Provides test data for test_dump()
*
* @return array
*/
public function provider_dump()
{
return array(
array('foobar', 128, '<small>string</small><span>(6)</span> "foobar"'),
array('foobar', 2, '<small>string</small><span>(6)</span> "fo&nbsp;&hellip;"'),
array(NULL, 128, '<small>NULL</small>'),
array(TRUE, 128, '<small>bool</small> TRUE'),
array(array('foobar'), 128, "<small>array</small><span>(1)</span> <span>(\n 0 => <small>string</small><span>(6)</span> \"foobar\"\n)</span>"),
array(new StdClass, 128, "<small>object</small> <span>stdClass(0)</span> <code>{\n}</code>"),
array("fo\x6F\xFF\x00bar\x8F\xC2\xB110", 128, '<small>string</small><span>(10)</span> "foobar±10"'),
);
}
/**
* Tests Kohana::dump()
*
* @test
* @dataProvider provider_dump
* @covers Kohana::dump
* @covers Kohana::_dump
* @param object $exception exception to test
* @param string $expected expected output
*/
public function test_dump($input, $length, $expected)
{
$this->assertEquals($expected, Kohana::dump($input, $length));
}
}

View File

@@ -0,0 +1,679 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Date class
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_DateTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_offset()
*
* @return array
*/
public function provider_offset()
{
return array(
array(
-18000,
'America/Chicago',
'GMT',
),
);
}
/**
* Tests Date::offset()
*
* @test
* @dataProvider provider_offset
* @covers Date::offset
* @param integer $expected Expected offset
* @param string $remote Remote TZ
* @param string $local Local TZ
* @param integer $now Current timestamp
*/
public function test_offset($expected, $remote, $local, $now = NULL)
{
$this->assertSame($expected, Date::offset($remote, $local, $now));
}
/**
* Provides test data for test_date()
*
* @return array
*/
public function provider_am_pm()
{
return array(
// All possible values
array(0, 'AM'),
array(1, 'AM'),
array(2, 'AM'),
array(3, 'AM'),
array(4, 'AM'),
array(5, 'AM'),
array(6, 'AM'),
array(7, 'AM'),
array(8, 'AM'),
array(9, 'AM'),
array(10, 'AM'),
array(11, 'AM'),
array(12, 'PM'),
array(13, 'PM'),
array(14, 'PM'),
array(15, 'PM'),
array(16, 'PM'),
array(17, 'PM'),
array(18, 'PM'),
array(19, 'PM'),
array(20, 'PM'),
array(21, 'PM'),
array(22, 'PM'),
array(23, 'PM'),
array(24, 'PM'),
// ampm doesn't validate the hour, so I don't think we should test it..
// test strings are converted
array('0', 'AM'),
array('12', 'PM'),
);
}
/**
* Tests Date::ampm()
*
* @test
* @covers Date::ampm
* @dataProvider provider_am_pm
* @param <type> $hour
* @param <type> $expected
*/
public function test_am_pm($hour, $expected)
{
$this->assertSame(
$expected,
Date::ampm($hour)
);
}
/**
* Provides test data for test_adjust()
*
* @return array
*/
public function provider_adjust()
{
return array(
// Might as well test all possibilities
array(1, 'am', '01'),
array(2, 'am', '02'),
array(3, 'am', '03'),
array(4, 'am', '04'),
array(5, 'am', '05'),
array(6, 'am', '06'),
array(7, 'am', '07'),
array(8, 'am', '08'),
array(9, 'am', '09'),
array(10, 'am', '10'),
array(11, 'am', '11'),
array(12, 'am', '00'),
array(1, 'pm', '13'),
array(2, 'pm', '14'),
array(3, 'pm', '15'),
array(4, 'pm', '16'),
array(5, 'pm', '17'),
array(6, 'pm', '18'),
array(7, 'pm', '19'),
array(8, 'pm', '20'),
array(9, 'pm', '21'),
array(10, 'pm', '22'),
array(11, 'pm', '23'),
array(12, 'pm', '12'),
// It should also work with strings instead of ints
array('10', 'pm', '22'),
array('10', 'am', '10'),
);
}
/**
* Tests Date::ampm()
*
* @test
* @dataProvider provider_adjust
* @param integer $hour Hour in 12 hour format
* @param string $ampm Either am or pm
* @param string $expected Expected result
*/
public function test_adjust($hour, $ampm, $expected)
{
$this->assertSame(
$expected,
Date::adjust($hour, $ampm)
);
}
/**
* Provides test data for test_days()
*
* @return array
*/
public function provider_days()
{
return array(
// According to "the rhyme" these should be the same every year
array(9, FALSE, 30),
array(4, FALSE, 30),
array(6, FALSE, 30),
array(11, FALSE, 30),
array(1, FALSE, 31),
array(3, FALSE, 31),
array(5, FALSE, 31),
array(7, FALSE, 31),
array(8, FALSE, 31),
array(10, FALSE, 31),
// February is such a pain
array(2, 2001, 28),
array(2, 2000, 29),
array(2, 2012, 29),
);
}
/**
* Tests Date::days()
*
* @test
* @covers Date::days
* @dataProvider provider_days
* @param integer $month
* @param integer $year
* @param integer $expected
*/
public function test_days($month, $year, $expected)
{
$days = Date::days($month, $year);
$this->assertSame(
$expected,
count($days)
);
// This should be a mirrored array, days => days
for($i = 1; $i <= $expected; ++$i)
{
$this->assertArrayHasKey($i, $days);
// Combining the type check into this saves about 400-500 assertions!
$this->assertSame((string) $i, $days[$i]);
}
}
/**
* Provides test data for test_formatted_time()
*
* @return array
*/
public function provider_formatted_time()
{
return array(
// Test the default format
array('2010-04-16 17:00:00', '5:00PM 16th April 2010'),
// Now we use our own format
// Binary date!
array('01/01/2010 01:00', '1AM 1st January 2010', 'd/m/Y H:i'),
);
}
/**
* Tests Date::formatted_time()
*
* @test
* @dataProvider provider_formatted_time
* @covers Date::formatted_time
* @ticket 3035
* @param string $expected Expected output
* @param string|integer $datetime_str The datetime timestamp / string
* @param string|null $timestamp_format The output format
*/
public function test_formatted_time($expected, $datetime_str, $timestamp_format = NULL)
{
$timestamp = Date::formatted_time($datetime_str, $timestamp_format);
$this->assertSame($expected, $timestamp);
}
/**
* Tests Date::months()
*
* @test
* @covers Date::months
*/
public function test_months()
{
$months = Date::months();
$this->assertSame(12, count($months));
for($i = 1; $i <= 12; ++$i)
{
$this->assertArrayHasKey($i, $months);
$this->assertSame((string) $i, $months[$i]);
}
}
/**
* Provides test data for test_span()
*
* @return array
*/
public function provider_span()
{
$time = time();
return array(
// Test that it must specify an output format
array(
$time,
$time,
'',
FALSE
),
// Test that providing only one output just returns that output
array(
$time - 30,
$time,
'seconds',
30
),
// Random tests
array(
$time - 30,
$time,
'years,months,weeks,days,hours,minutes,seconds',
array('years' => 0, 'months' => 0, 'weeks' => 0, 'days' => 0, 'hours' => 0, 'minutes' => 0, 'seconds' => 30),
),
array(
$time - (60 * 60 * 24 * 782) + (60 * 25),
$time,
'years,months,weeks,days,hours,minutes,seconds',
array('years' => 2, 'months' => 1, 'weeks' => 3, 'days' => 0, 'hours' => 1, 'minutes' => 28, 'seconds' => 24),
),
// Should be able to compare with the future & that it only uses formats specified
array(
$time + (60 * 60 * 24 * 15) + (60 * 5),
$time,
'weeks,days,hours,minutes,seconds',
array('weeks' => 2, 'days' => 1, 'hours' => 0, 'minutes' => 5, 'seconds' => 0),
),
array(
// Add a bit of extra time to account for phpunit processing
$time + (14 * 31 * 24* 60 * 60) + (79 * 80),
NULL,
'months,years',
array('months' => 2, 'years' => 1),
),
);
}
/**
* Tests Date::span()
*
* @test
* @covers Date::span
* @dataProvider provider_span
* @param integer $time1 Time in the past
* @param integer $time2 Time to compare against
* @param string $output Units to output
* @param array $expected Array of $outputs => values
*/
public function test_span($time1, $time2, $output, $expected)
{
$this->assertSame(
$expected,
Date::span($time1, $time2, $output)
);
}
/**
* Provides test data to test_fuzzy_span
*
* This test data is provided on the assumption that it
* won't take phpunit more than 30 seconds to get the
* data from this provider to the test... ;)
*
* @return array Test Data
*/
public function provider_fuzzy_span()
{
return array(
array('moments ago', time() - 30),
array('in moments', time() + 30),
array('a few minutes ago', time() - 10*60),
array('in a few minutes', time() + 10*60),
array('less than an hour ago', time() - 45*60),
array('in less than an hour', time() + 45*60),
array('a couple of hours ago', time() - 2*60*60),
array('in a couple of hours', time() + 2*60*60),
array('less than a day ago', time() - 12*60*60),
array('in less than a day', time() + 12*60*60),
array('about a day ago', time() - 30*60*60),
array('in about a day', time() + 30*60*60),
array('a couple of days ago', time() - 3*24*60*60),
array('in a couple of days', time() + 3*24*60*60),
array('less than a week ago', time() - 5*24*60*60),
array('in less than a week', time() + 5*24*60*60),
array('about a week ago', time() - 9*24*60*60),
array('in about a week', time() + 9*24*60*60),
array('less than a month ago', time() - 20*24*60*60),
array('in less than a month', time() + 20*24*60*60),
array('about a month ago', time() - 40*24*60*60),
array('in about a month', time() + 40*24*60*60),
array('a couple of months ago', time() - 3*30*24*60*60),
array('in a couple of months', time() + 3*30*24*60*60),
array('less than a year ago', time() - 7*31*24*60*60),
array('in less than a year', time() + 7*31*24*60*60),
array('about a year ago', time() - 18*31*24*60*60),
array('in about a year', time() + 18*31*24*60*60),
array('a couple of years ago', time() - 3*12*31*24*60*60),
array('in a couple of years', time() + 3*12*31*24*60*60),
array('a few years ago', time() - 5*12*31*24*60*60),
array('in a few years', time() + 5*12*31*24*60*60),
array('about a decade ago', time() - 11*12*31*24*60*60),
array('in about a decade', time() + 11*12*31*24*60*60),
array('a couple of decades ago', time() - 20*12*31*24*60*60),
array('in a couple of decades', time() + 20*12*31*24*60*60),
array('several decades ago', time() - 50*12*31*24*60*60),
array('in several decades', time() + 50*12*31*24*60*60),
array('a long time ago', time() - pow(10,10)),
array('in a long time', time() + pow(10,10)),
);
}
/**
* Test of Date::fuzy_span()
*
* @test
* @dataProvider provider_fuzzy_span
* @param string $expected Expected output
* @param integer $timestamp Timestamp to use
*/
public function test_fuzzy_span($expected, $timestamp)
{
$this->assertSame(
$expected,
Date::fuzzy_span($timestamp)
);
}
/**
* Provides test data for test_years()
*
* @return array Test Data
*/
public function provider_years()
{
return array(
array(
array (
2005 => '2005',
2006 => '2006',
2007 => '2007',
2008 => '2008',
2009 => '2009',
2010 => '2010',
2011 => '2011',
2012 => '2012',
2013 => '2013',
2014 => '2014',
2015 => '2015',
),
2005,
2015
),
);
}
/**
* Tests Data::years()
*
* @test
* @dataProvider provider_years
*/
public function test_years($expected, $start = FALSE, $end = FALSE)
{
$this->assertSame(
$expected,
Date::years($start, $end)
);
}
public function provider_hours()
{
return array(
array(
array(
1 => '1',
2 => '2',
3 => '3',
4 => '4',
5 => '5',
6 => '6',
7 => '7',
8 => '8',
9 => '9',
10 => '10',
11 => '11',
12 => '12',
),
),
);
}
/**
* Test for Date::hours
*
* @test
* @dataProvider provider_hours
*/
public function test_hours($expected, $step = 1, $long = FALSE, $start = NULL)
{
$this->assertSame(
$expected,
Date::hours($step, $long, $start)
);
}
/**
* Provides test data for test_seconds
*
* @return array Test data
*/
public function provider_seconds()
{
return array(
array(
// Thank god for var_export()
array (
0 => '00', 1 => '01', 2 => '02', 3 => '03', 4 => '04',
5 => '05', 6 => '06', 7 => '07', 8 => '08', 9 => '09',
10 => '10', 11 => '11', 12 => '12', 13 => '13', 14 => '14',
15 => '15', 16 => '16', 17 => '17', 18 => '18', 19 => '19',
20 => '20', 21 => '21', 22 => '22', 23 => '23', 24 => '24',
25 => '25', 26 => '26', 27 => '27', 28 => '28', 29 => '29',
30 => '30', 31 => '31', 32 => '32', 33 => '33', 34 => '34',
35 => '35', 36 => '36', 37 => '37', 38 => '38', 39 => '39',
40 => '40', 41 => '41', 42 => '42', 43 => '43', 44 => '44',
45 => '45', 46 => '46', 47 => '47', 48 => '48', 49 => '49',
50 => '50', 51 => '51', 52 => '52', 53 => '53', 54 => '54',
55 => '55', 56 => '56', 57 => '57', 58 => '58', 59 => '59',
),
1,
0,
60
),
);
}
/**
*
* @test
* @dataProvider provider_seconds
* @covers Date::seconds
*/
public function test_seconds($expected, $step = 1, $start = 0, $end = 60)
{
$this->assertSame(
$expected,
Date::seconds($step, $start, $end)
);
}
/**
* Provides test data for test_minutes
*
* @return array Test data
*/
public function provider_minutes()
{
return array(
array(
array(
0 => '00', 5 => '05', 10 => '10',
15 => '15', 20 => '20', 25 => '25',
30 => '30', 35 => '35', 40 => '40',
45 => '45', 50 => '50', 55 => '55',
),
5,
),
);
}
/**
*
* @test
* @dataProvider provider_minutes
*/
public function test_minutes($expected, $step)
{
$this->assertSame(
$expected,
Date::minutes($step)
);
}
/**
* This tests that the minutes helper defaults to using a $step of 5
* and thus returns an array of 5 minute itervals
*
* @test
* @covers Date::minutes
*/
public function test_minutes_defaults_to_using_step_of5()
{
$minutes = array(
0 => '00', 5 => '05', 10 => '10',
15 => '15', 20 => '20', 25 => '25',
30 => '30', 35 => '35', 40 => '40',
45 => '45', 50 => '50', 55 => '55',
);
$this->assertSame(
$minutes,
Date::minutes()
);
}
/**
* Provids for test_unix2dos
*
* @return array Test Data
*/
public function provider_unix2dos()
{
return array(
array(
1024341746,
1281786936
),
array(
2162688,
315554400
)
);
}
/**
* Test Date::unix2dos()
*
* You should always pass a timestamp as otherwise the current
* date/time would be used and that's oviously variable
*
* Geert seems to be the only person who knows how unix2dos() works
* so we just throw in some random values and see what happens
*
* @test
* @dataProvider provider_unix2dos
* @covers Date::unix2dos
* @param integer $expected Expected output
* @param integer $timestamp Input timestamp
*/
public function test_unix2dos($expected, $timestamp)
{
$this->assertSame($expected, Date::unix2dos($timestamp));
}
/**
* Provides test data for test_dos2unix
*
* @return array Test data
*/
public function provider_dos2unix()
{
return array(
array(
1281786936,
1024341746,
),
array(
315554400,
2162688,
),
);
}
/**
* Tests Date::dos2unix
*
* @test
* @dataProvider provider_dos2unix
* @param integer $expected Expected output
* @param integer $timestamp Input timestamp
*/
public function test_dos2unix($expected, $timestamp)
{
$this->assertEquals($expected, Date::dos2unix($timestamp));
}
}

View File

@@ -0,0 +1,121 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Test for feed helper
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_FeedTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_parse()
*
* @return array
*/
public function provider_parse()
{
return array(
// $source, $expected
array('http://dev.kohanaframework.org/projects/kohana3/activity.atom', 15),
);
}
/**
* Tests that Feed::parse gets the correct number of elements
*
* @test
* @dataProvider provider_parse
* @covers feed::parse
* @param string $source URL to test
* @param integer $expected Count of items
*/
public function test_parse($source, $expected)
{
if ( ! $this->hasInternet())
$this->markTestSkipped('An internet connection is required for this test');
$this->assertEquals($expected, count(feed::parse($source)));
}
/**
* Provides test data for test_create()
*
* @return array
*/
public function provider_create()
{
$info = array('pubDate' => 123, 'image' => array('link' => 'http://kohanaframework.org/image.png', 'url' => 'http://kohanaframework.org/', 'title' => 'title'));
return array(
// $source, $expected
array($info, array('foo' => array('foo' => 'bar', 'pubDate' => 123, 'link' => 'foo')), array('_SERVER' => array('HTTP_HOST' => 'localhost')+$_SERVER),
array(
'tag' => 'channel',
'descendant' => array(
'tag' => 'item',
'child' => array(
'tag' => 'foo',
'content' => 'bar'
)
)
),
array(
$this->matcher_composer($info, 'image', 'link'),
$this->matcher_composer($info, 'image', 'url'),
$this->matcher_composer($info, 'image', 'title')
)
),
);
}
/**
* Helper for handy matcher composing
*
* @param array $data
* @param string $tag
* @param string $child
* @return array
*/
private function matcher_composer($data, $tag, $child)
{
return array(
'tag' => 'channel',
'descendant' => array(
'tag' => $tag,
'child' => array(
'tag' => $child,
'content' => $data[$tag][$child]
)
)
);
}
/**
* @test
*
* @dataProvider provider_create
*
* @covers feed::create
*
* @param string $info info to pass
* @param integer $items items to add
* @param integer $matcher output
*/
public function test_create($info, $items, $enviroment, $matcher_item, $matchers_image)
{
$this->setEnvironment($enviroment);
$this->assertTag($matcher_item, feed::create($info, $items), '', FALSE);
foreach ($matchers_image as $matcher_image)
{
$this->assertTag($matcher_image, feed::create($info, $items), '', FALSE);
}
}
}

View File

@@ -0,0 +1,73 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana File helper
*
* @group kohana
* @group kohana.url
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_FileTest extends Kohana_Unittest_Testcase
{
/**
* Provides test data for test_sanitize()
*
* @return array
*/
public function provider_mime()
{
return array(
// $value, $result
array(Kohana::find_file('classes', 'file')),
array(Kohana::find_file('tests', 'test_data/github', 'png')),
);
}
/**
* Tests File::mime()
*
* @test
* @dataProvider provider_mime
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_mime($input)
{
$this->assertSame(1, preg_match('/^(?:application|audio|image|message|multipart|text|video)\/[a-z.+0-9-]+$/i', File::mime($input)));
}
/**
* Provides test data for test_split_join()
*
* @return array
*/
public function provider_split_join()
{
return array(
// $value, $result
array(Kohana::find_file('tests', 'test_data/github', 'png'), .01, 1),
);
}
/**
* Tests File::mime()
*
* @test
* @dataProvider provider_split_join
* @param boolean $input Input for File::split
* @param boolean $peices Input for File::split
* @param boolean $expected Output for File::splut
*/
public function test_split_join($input, $peices, $expected)
{
$this->assertSame($expected, File::split($input, $peices));
$this->assertSame($expected, File::join($input));
foreach (glob(Kohana::find_file('tests', 'test_data/github', 'png') . '.*') as $file) unlink($file);
}
}

View File

@@ -0,0 +1,372 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana Form helper
*
* @group kohana
* @group kohana.form
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_FormTest extends Kohana_Unittest_Testcase
{
/**
* Defaults for this test
* @var array
*/
protected $environmentDefault = array(
'Kohana::$base_url' => '/',
'HTTP_HOST' => 'kohanaframework.org',
);
/**
* Provides test data for test_open()
*
* @return array
*/
public function provider_open()
{
return array(
// $value, $result
#array(NULL, NULL, '<form action="/" method="post" accept-charset="utf-8">'), // Fails because of Request::$current
array('foo', NULL),
array('', NULL),
array('foo', array('method' => 'get')),
);
}
/**
* Tests Form::open()
*
* @test
* @dataProvider provider_open
* @param boolean $input Input for Form::open
* @param boolean $expected Output for Form::open
*/
public function test_open($action, $attributes)
{
$tag = Form::open($action, $attributes);
$matcher = array(
'tag' => 'form',
'attributes' => array(
'method' => 'post',
'accept-charset' => 'utf-8',
),
);
if($attributes !== NULL)
$matcher['attributes'] = $attributes + $matcher['attributes'];
$this->assertTag($matcher, $tag);
}
/**
* Tests Form::close()
*
* @test
*/
public function test_close()
{
$this->assertSame('</form>', Form::close());
}
/**
* Provides test data for test_input()
*
* @return array
*/
public function provider_input()
{
return array(
// $value, $result
array('input', 'foo', 'bar', NULL, 'input'),
array('input', 'foo', NULL, NULL, 'input'),
array('hidden', 'foo', 'bar', NULL, 'hidden'),
array('password', 'foo', 'bar', NULL, 'password'),
);
}
/**
* Tests Form::input()
*
* @test
* @dataProvider provider_input
* @param boolean $input Input for Form::input
* @param boolean $expected Output for Form::input
*/
public function test_input($type, $name, $value, $attributes)
{
$matcher = array(
'tag' => 'input',
'attributes' => array('name' => $name, 'type' => $type)
);
// Form::input creates a text input
if($type === 'input')
$matcher['attributes']['type'] = 'text';
// NULL just means no value
if($value !== NULL)
$matcher['attributes']['value'] = $value;
// Add on any attributes
if(is_array($attributes))
$matcher['attributes'] = $attributes + $matcher['attributes'];
$tag = Form::$type($name, $value, $attributes);
$this->assertTag($matcher, $tag, $tag);
}
/**
* Provides test data for test_file()
*
* @return array
*/
public function provider_file()
{
return array(
// $value, $result
array('foo', NULL, '<input type="file" name="foo" />'),
);
}
/**
* Tests Form::file()
*
* @test
* @dataProvider provider_file
* @param boolean $input Input for Form::file
* @param boolean $expected Output for Form::file
*/
public function test_file($name, $attributes, $expected)
{
$this->assertSame($expected, Form::file($name, $attributes));
}
/**
* Provides test data for test_check()
*
* @return array
*/
public function provider_check()
{
return array(
// $value, $result
array('checkbox', 'foo', NULL, FALSE, NULL),
array('checkbox', 'foo', NULL, TRUE, NULL),
array('checkbox', 'foo', 'bar', TRUE, NULL),
array('radio', 'foo', NULL, FALSE, NULL),
array('radio', 'foo', NULL, TRUE, NULL),
array('radio', 'foo', 'bar', TRUE, NULL),
);
}
/**
* Tests Form::check()
*
* @test
* @dataProvider provider_check
* @param boolean $input Input for Form::check
* @param boolean $expected Output for Form::check
*/
public function test_check($type, $name, $value, $checked, $attributes)
{
$matcher = array('tag' => 'input', 'attributes' => array('name' => $name, 'type' => $type));
if($value !== NULL)
$matcher['attributes']['value'] = $value;
if(is_array($attributes))
$matcher['attributes'] = $attributes + $matcher['attributes'];
if($checked === TRUE)
$matcher['attributes']['checked'] = 'checked';
$tag = Form::$type($name, $value, $checked, $attributes);
$this->assertTag($matcher, $tag, $tag);
}
/**
* Provides test data for test_text()
*
* @return array
*/
public function provider_text()
{
return array(
// $value, $result
array('textarea', 'foo', 'bar', NULL),
array('textarea', 'foo', 'bar', array('rows' => 20, 'cols' => 20)),
array('button', 'foo', 'bar', NULL),
array('label', 'foo', 'bar', NULL),
array('label', 'foo', NULL, NULL),
);
}
/**
* Tests Form::textarea()
*
* @test
* @dataProvider provider_text
* @param boolean $input Input for Form::textarea
* @param boolean $expected Output for Form::textarea
*/
public function test_text($type, $name, $body, $attributes)
{
$matcher = array(
'tag' => $type,
'attributes' => array(),
'content' => $body,
);
if($type !== 'label')
$matcher['attributes'] = array('name' => $name);
else
$matcher['attributes'] = array('for' => $name);
if(is_array($attributes))
$matcher['attributes'] = $attributes + $matcher['attributes'];
$tag = Form::$type($name, $body, $attributes);
$this->assertTag($matcher, $tag, $tag);
}
/**
* Provides test data for test_select()
*
* @return array
*/
public function provider_select()
{
return array(
// $value, $result
array('foo', NULL, NULL, "<select name=\"foo\"></select>"),
array('foo', array('bar' => 'bar'), NULL, "<select name=\"foo\">\n<option value=\"bar\">bar</option>\n</select>"),
array('foo', array('bar' => 'bar'), 'bar', "<select name=\"foo\">\n<option value=\"bar\" selected=\"selected\">bar</option>\n</select>"),
array('foo', array('bar' => array('foo' => 'bar')), NULL, "<select name=\"foo\">\n<optgroup label=\"bar\">\n<option value=\"foo\">bar</option>\n</optgroup>\n</select>"),
array('foo', array('bar' => array('foo' => 'bar')), 'foo', "<select name=\"foo\">\n<optgroup label=\"bar\">\n<option value=\"foo\" selected=\"selected\">bar</option>\n</optgroup>\n</select>"),
// #2286
array('foo', array('bar' => 'bar', 'unit' => 'test', 'foo' => 'foo'), array('bar', 'foo'), "<select name=\"foo\" multiple=\"multiple\">\n<option value=\"bar\" selected=\"selected\">bar</option>\n<option value=\"unit\">test</option>\n<option value=\"foo\" selected=\"selected\">foo</option>\n</select>"),
);
}
/**
* Tests Form::select()
*
* @test
* @dataProvider provider_select
* @param boolean $input Input for Form::select
* @param boolean $expected Output for Form::select
*/
public function test_select($name, $options, $selected, $expected)
{
// Much more efficient just to assertSame() rather than assertTag() on each element
$this->assertSame($expected, Form::select($name, $options, $selected));
}
/**
* Provides test data for test_submit()
*
* @return array
*/
public function provider_submit()
{
return array(
// $value, $result
array('foo', 'Foobar!', '<input type="submit" name="foo" value="Foobar!" />'),
);
}
/**
* Tests Form::submit()
*
* @test
* @dataProvider provider_submit
* @param boolean $input Input for Form::submit
* @param boolean $expected Output for Form::submit
*/
public function test_submit($name, $value, $expected)
{
$matcher = array(
'tag' => 'input',
'attributes' => array('name' => $name, 'type' => 'submit', 'value' => $value)
);
$this->assertTag($matcher, Form::submit($name, $value));
}
/**
* Provides test data for test_image()
*
* @return array
*/
public function provider_image()
{
return array(
// $value, $result
array('foo', 'bar', array('src' => 'media/img/login.png'), '<input type="image" name="foo" value="bar" src="/media/img/login.png" />'),
);
}
/**
* Tests Form::image()
*
* @test
* @dataProvider provider_image
* @param boolean $name Input for Form::image
* @param boolean $value Input for Form::image
* @param boolean $attributes Input for Form::image
* @param boolean $expected Output for Form::image
*/
public function test_image($name, $value, $attributes, $expected)
{
$this->assertSame($expected, Form::image($name, $value, $attributes));
}
/**
* Provides test data for testLabel()
*
* @return array
*/
function providerLabel()
{
return array(
// $value, $result
// Single for provided
array('email', NULL, NULL, '<label for="email">Email</label>'),
array('email_address', NULL, NULL, '<label for="email_address">Email Address</label>'),
array('email-address', NULL, NULL, '<label for="email-address">Email Address</label>'),
// For and text values provided
array('name', 'First name', NULL, '<label for="name">First name</label>'),
// with attributes
array('lastname', 'Last name', array('class' => 'text'), '<label class="text" for="lastname">Last name</label>'),
array('lastname', 'Last name', array('class' => 'text', 'id'=>'txt_lastname'), '<label id="txt_lastname" class="text" for="lastname">Last name</label>'),
);
}
/**
* Tests Form::label()
*
* @test
* @dataProvider providerLabel
* @param boolean $for Input for Form::label
* @param boolean $text Input for Form::label
* @param boolean $attributes Input for Form::label
* @param boolean $expected Output for Form::label
*/
function testLabel($for, $text, $attributes, $expected)
{
$this->assertSame($expected, Form::label($for, $text, $attributes));
}
}

View File

@@ -0,0 +1,227 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests HTML
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_HTMLTest extends Kohana_Unittest_TestCase
{
protected $environmentDefault = array(
'Kohana::$base_url' => '/kohana/',
'HTTP_HOST' => 'www.kohanaframework.org',
);
/**
* Provides test data for test_attributes()
*
* @return array
*/
public function provider_attributes()
{
return array(
array(
array('name' => 'field', 'random' => 'not_quite', 'id' => 'unique_field'),
' id="unique_field" name="field" random="not_quite"'
),
array(
array('invalid' => NULL),
''
),
array(
array(),
''
)
);
}
/**
* Tests HTML::attributes()
*
* @test
* @dataProvider provider_attributes
* @param array $attributes Attributes to use
* @param string $expected Expected output
*/
public function test_attributes($attributes, $expected)
{
$this->assertSame(
$expected,
HTML::attributes($attributes)
);
}
/**
* Provides test data for test_script
*
* @return array Array of test data
*/
public function provider_script()
{
return array(
array(
'<script type="text/javascript" src="http://google.com/script.js"></script>',
'http://google.com/script.js',
),
);
}
/**
* Tests HTML::script()
*
* @test
* @dataProvider provider_script
* @param string $expected Expected output
* @param string $file URL to script
* @param array $attributes HTML attributes for the anchor
* @param bool $index Should the index file be included in url?
*/
public function test_script($expected, $file, array $attributes = NULL, $index = FALSE)
{
$this->assertSame(
$expected,
HTML::script($file, $attributes, $index)
);
}
/**
* Data provider for the style test
*
* @return array Array of test data
*/
public function provider_style()
{
return array(
array(
'<link type="text/css" href="http://google.com/style.css" rel="stylesheet" />',
'http://google.com/style.css',
array(),
FALSE
),
);
}
/**
* Tests HTML::style()
*
* @test
* @dataProvider provider_style
* @param string $expected The expected output
* @param string $file The file to link to
* @param array $attributes Any extra attributes for the link
* @param bool $index Whether the index file should be added to the link
*/
public function test_style($expected, $file, array $attributes = NULL, $index = FALSE)
{
$this->assertSame(
$expected,
HTML::style($file, $attributes, $index)
);
}
/**
* Provides test data for test_obfuscate
*
* @return array Array of test data
*/
public function provider_obfuscate()
{
return array(
array('something crazy'),
array('me@google.com'),
);
}
/**
* Tests HTML::obfuscate
*
* @test
* @dataProvider provider_obfuscate
* @param string $string The string to obfuscate
*/
public function test_obfuscate($string)
{
$this->assertNotSame(
$string,
HTML::obfuscate($string)
);
}
/**
* Provides test data for test_anchor
*
* @return array Test data
*/
public function provider_anchor()
{
return array(
array(
'<a href="http://kohanaframework.org">Kohana</a>',
array(),
'http://kohanaframework.org',
'Kohana',
),
array(
'<a href="http://google.com" target="_blank">GOOGLE</a>',
array(),
'http://google.com',
'GOOGLE',
array('target' => '_blank'),
),
);
}
/**
* Tests HTML::anchor
*
* @test
* @dataProvider provider_anchor
*/
public function test_anchor($expected, array $options, $uri, $title = NULL, array $attributes = NULL, $protocol = NULL)
{
//$this->setEnvironment($options);
$this->assertSame(
$expected,
HTML::anchor($uri, $title, $attributes, $protocol)
);
}
/**
* Data provider for test_file_anchor
*
* @return array
*/
public function provider_file_anchor()
{
return array(
array(
'<a href="/kohana/mypic.png">My picture file</a>',
array(),
'mypic.png',
'My picture file',
)
);
}
/**
* Test for HTML::file_anchor()
*
* @test
* @covers HTML::file_anchor
* @dataProvider provider_file_anchor
*/
public function test_file_anchor($expected, array $options, $file, $title = NULL, array $attributes = NULL, $protocol = NULL)
{
$this->assertSame(
$expected,
HTML::file_anchor($file, $title, $attributes, $protocol)
);
}
}

View File

@@ -0,0 +1,73 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana i18n class
*
* @group kohana
* @group kohana.i18n
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_I18nTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_lang()
*
* @return array
*/
public function provider_lang()
{
return array(
// $value, $result
array(NULL, 'en-us'),
array('es-es', 'es-es'),
array(NULL, 'es-es'),
);
}
/**
* Tests i18n::lang()
*
* @test
* @dataProvider provider_lang
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_open($input, $expected)
{
$this->assertSame($expected, I18n::lang($input));
}
/**
* Provides test data for test_get()
*
* @return array
*/
public function provider_get()
{
return array(
// $value, $result
array('en-us', 'Hello, world!', 'Hello, world!'),
array('es-es', 'Hello, world!', '¡Hola, mundo!'),
array('fr-fr', 'Hello, world!', 'Bonjour, monde!'),
);
}
/**
* Tests i18n::get()
*
* @test
* @dataProvider provider_get
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_get($lang, $input, $expected)
{
I18n::lang($lang);
$this->assertSame($expected, I18n::get($input));
}
}

View File

@@ -0,0 +1,142 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana inflector class
*
* @group kohana
* @group kohana.inflector
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_InflectorTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_lang()
*
* @return array
*/
public function provider_uncountable()
{
return array(
// $value, $result
array('fish', TRUE),
array('cat', FALSE),
);
}
/**
* Tests Inflector::uncountable
*
* @test
* @dataProvider provider_uncountable
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_uncountable($input, $expected)
{
$this->assertSame($expected, Inflector::uncountable($input));
}
/**
* Provides test data for test_lang()
*
* @return array
*/
public function provider_singular()
{
return array(
// $value, $result
array('fish', NULL, 'fish'),
array('cats', NULL, 'cat'),
array('cats', 2, 'cats'),
array('cats', '2', 'cats'),
array('children', NULL, 'child'),
array('meters', 0.6, 'meters'),
array('meters', 1.6, 'meters'),
array('meters', 1.0, 'meter'),
array('status', NULL, 'status'),
array('statuses', NULL, 'status'),
);
}
/**
* Tests Inflector::singular
*
* @test
* @dataProvider provider_singular
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_singular($input, $count, $expected)
{
$this->assertSame($expected, Inflector::singular($input, $count));
}
/**
* Provides test data for test_lang()
*
* @return array
*/
public function provider_plural()
{
return array(
// $value, $result
array('fish', NULL, 'fish'),
array('cat', NULL, 'cats'),
array('cats', 1, 'cats'),
array('cats', '1', 'cats'),
array('movie', NULL, 'movies'),
array('meter', 0.6, 'meters'),
array('meter', 1.6, 'meters'),
array('meter', 1.0, 'meter'),
);
}
/**
* Tests Inflector::plural
*
* @test
* @dataProvider provider_plural
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_plural($input, $count, $expected)
{
$this->assertSame($expected, Inflector::plural($input, $count));
}
/**
* Provides test data for test_camelize()
*
* @return array
*/
public function provider_camelize()
{
return array(
// $value, $result
array('mother cat', 'camelize', 'motherCat'),
array('kittens in bed', 'camelize', 'kittensInBed'),
array('mother cat', 'underscore', 'mother_cat'),
array('kittens in bed', 'underscore', 'kittens_in_bed'),
array('kittens-are-cats', 'humanize', 'kittens are cats'),
array('dogs_as_well', 'humanize', 'dogs as well'),
);
}
/**
* Tests Inflector::camelize
*
* @test
* @dataProvider provider_camelize
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_camelize($input, $method, $expected)
{
$this->assertSame($expected, Inflector::$method($input));
}
}

View File

@@ -0,0 +1,87 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana Logging API
*
* @group kohana
* @group kohana.logging
*
* @package Unittest
* @author Kohana Team
* @author Matt Button <matthew@sigswitch.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_LogTest extends Kohana_Unittest_TestCase
{
/**
* Tests that when a new logger is created the list of messages is initially
* empty
*
* @test
* @covers Kohana_Log
*/
public function test_messages_is_initially_empty()
{
$logger = new Kohana_Log;
$this->assertAttributeSame(array(), '_messages', $logger);
}
/**
* Tests that when a new logger is created the list of writers is initially
* empty
*
* @test
* @covers Kohana_Log
*/
public function test_writers_is_initially_empty()
{
$logger = new Kohana_Log;
$this->assertAttributeSame(array(), '_writers', $logger);
}
/**
* Test that attaching a log writer adds it to the array of log writers
*
* @TODO Is this test too specific?
*
* @test
* @covers Kohana_Log::attach
*/
public function test_attach_attaches_log_writer_and_returns_this()
{
$logger = new Kohana_Log;
$writer = $this->getMockForAbstractClass('Kohana_Log_Writer');
$this->assertSame($logger, $logger->attach($writer));
$this->assertAttributeSame(
array(spl_object_hash($writer) => array('object' => $writer, 'types' => NULL)),
'_writers',
$logger
);
}
/**
* When we call detach() we expect the specified log writer to be removed
*
* @test
* @covers Kohana_Log::detach
*/
public function test_detach_removes_log_writer_and_returns_this()
{
$logger = new Kohana_Log;
$writer = $this->getMockForAbstractClass('Kohana_Log_Writer');
$logger->attach($writer);
$this->assertSame($logger, $logger->detach($writer));
$this->assertAttributeSame(array(), '_writers', $logger);
}
}

View File

@@ -0,0 +1,30 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* This test only really exists for code coverage. No tests really apply to base model.
* We can't even test Model because database doesn't exist!
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_ModelTest extends Kohana_Unittest_TestCase
{
/**
* @test
*/
public function test_construct()
{
#$model = new Model_Foobar('foo');
#$model = Model::factory('Foobar', 'foo');
}
}
class Model_Foobar extends Model
{
}

View File

@@ -0,0 +1,95 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Num
*
* @group kohana
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_NumTest extends Kohana_Unittest_TestCase
{
protected $default_locale;
/**
* SetUp test enviroment
*/
public function setUp()
{
parent::setUp();
setlocale(LC_ALL, 'English');
}
/**
* Tear down environment
*/
public function tearDown()
{
parent::tearDown();
setlocale(LC_ALL, $this->default_locale);
}
/**
* Provides test data for test_ordinal()
* @return array
*/
public function provider_ordinal()
{
return array(
array(0, 'th'),
array(1, 'st'),
array(21, 'st'),
array(112, 'th'),
array(23, 'rd'),
array(42, 'nd'),
);
}
/**
*
* @test
* @dataProvider provider_ordinal
* @param integer $number
* @param <type> $expected
*/
public function test_ordinal($number, $expected)
{
$this->assertSame($expected, Num::ordinal($number));
}
/**
* Provides test data for test_format()
* @return array
*/
public function provider_format()
{
return array(
// English
array(10000, 2, FALSE, '10,000.00'),
array(10000, 2, TRUE, '10,000.00'),
// Additional dp's should be removed
array(123.456, 2, FALSE, '123.46'),
array(123.456, 2, TRUE, '123.46'),
);
}
/**
* @todo test locales
* @test
* @dataProvider provider_format
* @param integer $number
* @param integer $places
* @param boolean $monetary
* @param string $expected
*/
public function test_format($number, $places, $monetary, $expected)
{
$this->assertSame($expected, Num::format($number, $places, $monetary));
}
}

View File

@@ -0,0 +1,77 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana remote class
*
* @group kohana
* @group kohana.remote
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_RemoteTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_get()
*
* @return array
*/
public function provider_get()
{
return array(
// $value, $result
array('', TRUE),
array('cat', FALSE),
);
}
/**
* Tests Remote::get
*
* @test
* @dataProvider provider_get
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_get($input, $expected)
{
if ( ! $this->hasInternet())
$this->markTestSkipped('An internet connection is required for this test');
#$this->assertSame($expected, Remote::get($input));
}
/**
* Provides test data for test_status()
*
* @return array
*/
public function provider_status()
{
return array(
// $value, $result
array('http://kohanaframework.org/', 200),
array('http://kohanaframework.org', 200),
array('http://kohanaframework.org/foobar', 500),
);
}
/**
* Tests Remote::status
*
* @test
* @dataProvider provider_status
* @param boolean $input Input for File::mime
* @param boolean $expected Output for File::mime
*/
public function test_status($input, $expected)
{
if ( ! $this->hasInternet())
$this->markTestSkipped('An internet connection is required for this test');
$this->assertSame($expected, Remote::status($input));
}
}

View File

@@ -0,0 +1,191 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Unit tests for request class
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_RequestTest extends Kohana_Unittest_TestCase
{
/**
* Route::matches() should return false if the route doesn't match against a uri
*
* @test
*/
public function test_create()
{
$request = Request::factory('foo/bar')->execute();
$this->assertEquals(200, $request->status);
$this->assertEquals('foo', $request->response);
try
{
$request = new Request('bar/foo');
$request->execute();
}
catch (Exception $e)
{
$this->assertEquals(TRUE, $e instanceof ReflectionException);
$this->assertEquals('404', $request->status);
}
}
/**
* Tests Request::accept_type()
*
* @test
* @covers Request::accept_type
*/
public function test_accept_type()
{
$this->assertEquals(array('*/*' => 1), Request::accept_type());
}
/**
* Provides test data for test_instance()
*
* @return array
*/
public function provider_instance()
{
return array(
// $route, $is_cli, $_server, $status, $response
array('foo/bar', TRUE, array(), 200, ''), // Shouldn't this be 'foo' ?
array('foo/foo', TRUE, array(), 200, ''), // Shouldn't this be a 404?
array(
'foo/bar',
FALSE,
array(
'REQUEST_METHOD' => 'get',
'HTTP_REFERER' => 'http://www.kohanaframework.org',
'HTTP_USER_AGENT' => 'Kohana Unit Test',
'REMOTE_ADDR' => '127.0.0.1',
), 200, ''), // Shouldn't this be 'foo' ?
);
}
/**
* Tests Request::instance()
*
* @test
* @dataProvider provider_instance
* @covers Request::instance
* @param boolean $value Input for Kohana::sanitize
* @param boolean $result Output for Kohana::sanitize
*/
public function test_instance($route, $is_cli, $server, $status, $response)
{
$this->setEnvironment(array(
'_SERVER' => $server+array('argc' => $_SERVER['argc']),
'Kohana::$is_cli' => $is_cli,
'Request::$instance' => NULL
));
$request = Request::instance($route);
$this->assertEquals($status, $request->status);
$this->assertEquals($response, $request->response);
$this->assertEquals($route, $request->uri);
if ( ! $is_cli)
{
$this->assertEquals($server['REQUEST_METHOD'], Request::$method);
$this->assertEquals($server['HTTP_REFERER'], Request::$referrer);
$this->assertEquals($server['HTTP_USER_AGENT'], Request::$user_agent);
}
}
/**
* Provides test data for Request::accept_lang()
* @return array
*/
public function provider_accept_lang()
{
return array(
array('en-us', 1, array('_SERVER' => array('HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5'))),
array('en-us', 1, array('_SERVER' => array('HTTP_ACCEPT_LANGUAGE' => 'en-gb'))),
array('en-us', 1, array('_SERVER' => array('HTTP_ACCEPT_LANGUAGE' => 'sp-sp;q=0.5')))
);
}
/**
* Tests Request::accept_lang()
*
* @test
* @covers Request::accept_lang
* @dataProvider provider_accept_lang
* @param array $params Query string
* @param string $expected Expected result
* @param array $enviroment Set environment
*/
public function test_accept_lang($params, $expected, $enviroment)
{
$this->setEnvironment($enviroment);
$this->assertEquals(
$expected,
Request::accept_lang($params)
);
}
/**
* Provides test data for Request::url()
* @return array
*/
public function provider_url()
{
return array(
array(
'foo/bar',
array(),
'http',
TRUE,
'http://localhost/kohana/foo/bar'
),
array(
'foo',
array('action' => 'bar'),
'http',
TRUE,
'http://localhost/kohana/foo/bar'
),
);
}
/**
* Tests Request::url()
*
* @test
* @dataProvider provider_url
* @covers Request::url
* @param string $route the route to use
* @param array $params params to pass to route::uri
* @param string $protocol the protocol to use
* @param array $expected The string we expect
*/
public function test_url($uri, $params, $protocol, $is_cli, $expected)
{
$this->setEnvironment(array(
'Kohana::$base_url' => '/kohana/',
'_SERVER' => array('HTTP_HOST' => 'localhost', 'argc' => $_SERVER['argc']),
'Kohana::$index_file' => FALSE,
'Kohana::$is_cli' => $is_cli,
));
$this->assertEquals(Request::instance($uri)->url($params, $protocol), $expected);
}
}
class Controller_Foo extends Controller {
public function action_bar()
{
$this->request->response = 'foo';
}
}

View File

@@ -0,0 +1,416 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Description of RouteTest
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_RouteTest extends Kohana_Unittest_TestCase
{
/**
* Remove all caches
*/
public function setUp()
{
parent::setUp();
$this->cleanCacheDir();
}
/**
* Removes cache files created during tests
*/
public function tearDown()
{
parent::tearDown();
$this->cleanCacheDir();
}
/**
* If Route::get() is asked for a route that does not exist then
* it should throw a Kohana_Exception
*
* Note use of @expectedException
*
* @test
* @covers Route::get
* @expectedException Kohana_Exception
*/
public function test_get_throws_exception_if_route_dnx()
{
Route::get('HAHAHAHAHAHAHAHAHA');
}
/**
* Route::all() should return all routes defined via Route::set()
* and not through new Route()
*
* @test
* @covers Route::all
*/
public function test_all_returns_all_defined_routes()
{
$defined_routes = self::readAttribute('Route', '_routes');
$this->assertSame($defined_routes, Route::all());
}
/**
* Route::name() should fetch the name of a passed route
* If route is not found then it should return FALSE
*
* @TODO: This test needs to segregate the Route::$_routes singleton
* @test
* @covers Route::name
*/
public function test_name_returns_routes_name_or_false_if_dnx()
{
$route = Route::set('flamingo_people', 'flamingo/dance');
$this->assertSame('flamingo_people', Route::name($route));
$route = new Route('dance/dance');
$this->assertFalse(Route::name($route));
}
/**
* If Route::cache() was able to restore routes from the cache then
* it should return TRUE and load the cached routes
*
* @test
* @covers Route::cache
*/
public function test_cache_stores_route_objects()
{
$routes = Route::all();
// First we create the cache
Route::cache(TRUE);
// Now lets modify the "current" routes
Route::set('nonsensical_route', 'flabbadaga/ding_dong');
// Then try and load said cache
$this->assertTrue(Route::cache());
// And if all went ok the nonsensical route should be gone...
$this->assertEquals($routes, Route::all());
}
/**
* Route::cache() should return FALSE if cached routes could not be found
*
* The cache is cleared before and after each test in setUp tearDown
* by cleanCacheDir()
*
* @test
* @covers Route::cache
*/
public function test_cache_returns_false_if_cache_dnx()
{
$this->assertSame(FALSE, Route::cache(), 'Route cache was not empty');
}
/**
* If the constructor is passed a NULL uri then it should assume it's
* being loaded from the cache & therefore shouldn't override the cached attributes
*
* @test
* @covers Route::__construct
*/
public function test_constructor_returns_if_uri_is_null()
{
// We use a mock object to make sure that the route wasn't recompiled
$route = $this->getMock('Route', array('_compile'), array(), '', FALSE);
$route
->expects($this->never())
->method('_compile');
$route->__construct(NULL,NULL);
$this->assertAttributeSame('', '_uri', $route);
$this->assertAttributeSame(array(), '_regex', $route);
$this->assertAttributeSame(array('action' => 'index'), '_defaults', $route);
$this->assertAttributeSame(NULL, '_route_regex', $route);
}
/**
* The constructor should only use custom regex if passed a non-empty array
*
* Technically we can't "test" this as the default regex is an empty array, this
* is purely for improving test coverage
*
* @test
* @covers Route::__construct
*/
public function test_constructor_only_changes_custom_regex_if_passed()
{
$route = new Route('<controller>/<action>', array());
$this->assertAttributeSame(array(), '_regex', $route);
$route = new Route('<controller>/<action>', NULL);
$this->assertAttributeSame(array(), '_regex', $route);
}
/**
* When we pass custom regex to the route's constructor it should it
* in leu of the default
*
* @test
* @covers Route::__construct
* @covers Route::_compile
*/
public function test_route_uses_custom_regex_passed_to_constructor()
{
$regex = array('id' => '[0-9]{1,2}');
$route = new Route('<controller>(/<action>(/<id>))', $regex);
$this->assertAttributeSame($regex, '_regex', $route);
$this->assertAttributeContains(
$regex['id'],
'_route_regex',
$route
);
}
/**
* Route::matches() should return false if the route doesn't match against a uri
*
* @test
* @covers Route::matches
*/
public function test_matches_returns_false_on_failure()
{
$route = new Route('projects/(<project_id>/(<controller>(/<action>(/<id>))))');
$this->assertSame(FALSE, $route->matches('apple/pie'));
}
/**
* Route::matches() should return an array of parameters when a match is made
* An parameters that are not matched should not be present in the array of matches
*
* @test
* @covers Route::matches
*/
public function test_matches_returns_array_of_parameters_on_successful_match()
{
$route = new Route('(<controller>(/<action>(/<id>)))');
$matches = $route->matches('welcome/index');
$this->assertType('array', $matches);
$this->assertArrayHasKey('controller', $matches);
$this->assertArrayHasKey('action', $matches);
$this->assertArrayNotHasKey('id', $matches);
$this->assertSame(2, count($matches));
$this->assertSame('welcome', $matches['controller']);
$this->assertSame('index', $matches['action']);
}
/**
* Defaults specified with defaults() should be used if their values aren't
* present in the uri
*
* @test
* @covers Route::matches
*/
public function test_defaults_are_used_if_params_arent_specified()
{
$route = new Route('(<controller>(/<action>(/<id>)))');
$route->defaults(array('controller' => 'welcome', 'action' => 'index'));
$matches = $route->matches('');
$this->assertType('array', $matches);
$this->assertArrayHasKey('controller', $matches);
$this->assertArrayHasKey('action', $matches);
$this->assertArrayNotHasKey('id', $matches);
$this->assertSame(2, count($matches));
$this->assertSame('welcome', $matches['controller']);
$this->assertSame('index', $matches['action']);
$this->assertSame('unit/test/1', $route->uri(array(
'controller' => 'unit',
'action' => 'test',
'id' => '1'
)));
$this->assertSame('welcome/index', $route->uri());
}
/**
* This tests that routes with required parameters will not match uris without them present
*
* @test
* @covers Route::matches
*/
public function test_required_parameters_are_needed()
{
$route = new Route('admin(/<controller>(/<action>(/<id>)))');
$this->assertFalse($route->matches(''));
$matches = $route->matches('admin');
$this->assertType('array', $matches);
$matches = $route->matches('admin/users/add');
$this->assertType('array', $matches);
$this->assertSame(2, count($matches));
$this->assertArrayHasKey('controller', $matches);
$this->assertArrayHasKey('action', $matches);
}
/**
* This tests the reverse routing returns the uri specified in the route
* if it's a static route
*
* A static route is a route without any parameters
*
* @test
* @covers Route::uri
*/
public function test_reverse_routing_returns_routes_uri_if_route_is_static()
{
$route = new Route('info/about_us');
$this->assertSame('info/about_us', $route->uri(array('some' => 'random', 'params' => 'to confuse')));
}
/**
* When Route::uri is working on a uri that requires certain parameters to be present
* (i.e. <controller> in '<controller(/<action)') then it should throw an exception
* if the param was not provided
*
* @test
* @covers Route::uri
*/
public function test_uri_throws_exception_if_required_params_are_missing()
{
$route = new Route('<controller>(/<action)');
try
{
$route->uri(array('action' => 'awesome-action'));
$this->fail('Route::uri should throw exception if required param is not provided');
}
catch(Exception $e)
{
$this->assertType('Kohana_Exception', $e);
// Check that the error in question is about the controller param
$this->assertContains('controller', $e->getMessage());
}
}
/**
* The logic for replacing required segments is separate (but similar) to that for
* replacing optional segments.
*
* This test asserts that Route::uri will replace required segments with provided
* params
*
* @test
* @covers Route::uri
*/
public function test_uri_fills_required_uri_segments_from_params()
{
$route = new Route('<controller>/<action>(/<id>)');
$this->assertSame(
'users/edit',
$route->uri(array(
'controller' => 'users',
'action' => 'edit',
))
);
$this->assertSame(
'users/edit/god',
$route->uri(array(
'controller' => 'users',
'action' => 'edit',
'id' => 'god',
))
);
}
/**
* Provides test data for test_composing_url_from_route()
* @return array
*/
public function provider_composing_url_from_route()
{
return array(
array('/welcome'),
array('/news/view/42', array('controller' => 'news', 'action' => 'view', 'id' => 42)),
array('http://kohanaframework.org/news', array('controller' => 'news'), true)
);
}
/**
* Tests Route::url()
*
* Checks the url composing from specific route via Route::url() shortcut
*
* @test
* @dataProvider provider_composing_url_from_route
* @param string $expected
* @param array $params
* @param boolean $protocol
*/
public function test_composing_url_from_route($expected, $params = NULL, $protocol = NULL)
{
Route::set('foobar', '(<controller>(/<action>(/<id>)))')
->defaults(array(
'controller' => 'welcome',
)
);
$this->setEnvironment(array(
'_SERVER' => array('HTTP_HOST' => 'kohanaframework.org'),
'Kohana::$base_url' => '/',
'Request::$protocol' => 'http',
'Kohana::$index_file' => '',
));
$this->assertSame($expected, Route::url('foobar', $params, $protocol));
}
/**
* Tests Route::_compile()
*
* Makes sure that compile will use custom regex if specified
*
* @test
* @covers Route::_compile
*/
public function test_compile_uses_custom_regex_if_specificed()
{
$route = new Route(
'<controller>(/<action>(/<id>))',
array(
'controller' => '[a-z]+',
'id' => '\d+',
)
);
$this->assertAttributeSame(
'#^(?P<controller>[a-z]+)(?:/(?P<action>[^/.,;?\n]++)(?:/(?P<id>\d+))?)?$#uD',
'_route_regex',
$route
);
}
}

View File

@@ -0,0 +1,105 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana_Security
*
* @group kohana
*/
Class Kohana_SecurityTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_envode_php_tags()
*
* @return array Test data sets
*/
public function provider_encode_php_tags()
{
return array(
array("&lt;?php echo 'helloo'; ?&gt;", "<?php echo 'helloo'; ?>"),
);
}
/**
* Tests Security::encode_php_tags()
*
* @test
* @dataProvider provider_encode_php_tags
* @covers Security::encode_php_tags
*/
public function test_encode_php_tags($expected, $input)
{
$this->assertSame($expected, Security::encode_php_tags($input));
}
/**
* Provides test data for test_strip_image_tags()
*
* @return array Test data sets
*/
public function provider_strip_image_tags()
{
return array(
array('foo', '<img src="foo" />'),
);
}
/**
* Tests Security::strip_image_tags()
*
* @test
* @dataProvider provider_strip_image_tags
* @covers Security::strip_image_tags
*/
public function test_strip_image_tags($expected, $input)
{
$this->assertSame($expected, Security::strip_image_tags($input));
}
/**
* Provides test data for Security::token()
*
* @return array Test data sets
*/
public function provider_csrf_token()
{
$array = array();
for ($i = 0; $i <= 4; $i++)
{
Security::$token_name = 'token_'.$i;
$array[] = array(Security::token(TRUE), Security::check(Security::token(FALSE)), $i);
}
return $array;
}
/**
* Tests Security::token()
*
* @test
* @dataProvider provider_csrf_token
* @covers Security::token
*/
public function test_csrf_token($expected, $input, $iteration)
{
Security::$token_name = 'token_'.$iteration;
$this->assertSame(TRUE, $input);
$this->assertSame($expected, Security::token(FALSE));
Session::instance()->delete(Security::$token_name);
}
/**
* Tests that Security::xss_clean() removes null bytes
*
*
* @test
* @covers Security::xss_clean
* @ticket 2676
* @see http://www.hakipedia.com/index.php/Poison_Null_Byte#Perl_PHP_Null_Byte_Injection
*/
public function test_xss_clean_removes_null_bytes()
{
$input = "<\0script>alert('XSS');<\0/script>";
$this->assertSame("alert('XSS');", Security::xss_clean($input));
}
}

View File

@@ -0,0 +1,497 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests the cookie class
*
* @group kohana
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_SessionTest extends Kohana_Unittest_TestCase
{
/**
* Gets a mock of the session class
*
* @return Session
*/
public function getMockSession(array $config = array())
{
return $this->getMockForAbstractClass('Session', array($config));
}
/**
* Provides test data for
*
* test_constructor_uses_name_from_config_and_casts()
*
* @return array
*/
public function provider_constructor_uses_settings_from_config_and_casts()
{
return array(
// array(expected, input)
// data set 0
array(
array(
'name' => 'awesomeness',
'lifetime' => 1231456421,
'encrypted' => FALSE
),
array(
'name' => 'awesomeness',
'lifetime' => '1231456421',
'encrypted' => FALSE,
),
),
// data set 1
array(
array(
'name' => '123',
'encrypted' => 'default',
),
array(
'name' => 123,
'encrypted' => TRUE,
),
),
);
}
/**
* The constructor should change its attributes based on config
* passed as the first parameter
*
* @test
* @dataProvider provider_constructor_uses_settings_from_config_and_casts
* @covers Session::__construct
*/
public function test_constructor_uses_settings_from_config_and_casts($expected, $config)
{
$session = $this->getMockForAbstractClass('Session', array($config));
foreach($expected as $var => $value)
{
$this->assertAttributeSame($value, '_'.$var, $session);
}
}
/**
* Check that the constructor will load a session if it's provided
* witha session id
*
* @test
* @covers Session::__construct
* @covers Session::read
*/
public function test_constructor_loads_session_with_session_id()
{
$this->markTestIncomplete(
'Need to work out why constructor is not being called'
);
$config = array();
$session_id = 'lolums';
// Don't auto-call constructor, we need to setup the mock first
$session = $this->getMockForAbstractClass(
'Session',
array(),
'',
FALSE
);
$session
->expects($this->once())
->method('read')
->with($session_id);
$session->__construct($config, $session_id);
}
/**
* Calling $session->bind() should allow you to bind a variable
* to a session variable
*
* @test
* @covers Session::bind
* @ticket 3164
*/
public function test_bind_actually_binds_variable()
{
$session = $this->getMockForAbstractClass('Session');
$var = 'asd';
$session->bind('our_var', $var);
$var = 'foobar';
$this->assertSame('foobar', $session->get('our_var'));
}
/**
* When a session is initially created it should have no data
*
*
* @test
* @covers Session::__construct
* @covers Session::set
*/
public function test_initially_session_has_no_data()
{
$session = $this->getMockSession();
$this->assertAttributeSame(array(), '_data', $session);
}
/**
* Make sure that the default session name (the one used if the
* driver does not set one) is 'session'
*
* @test
* @covers Session::__construct
*/
public function test_default_session_name_is_set()
{
$session = $this->getMockSession();
$this->assertAttributeSame('session', '_name', $session);
}
/**
* By default sessions are unencrypted
*
* @test
* @covers Session::__construct
*/
public function test_default_session_is_unencrypted()
{
$session = $this->getMockSession();
$this->assertAttributeSame(FALSE, '_encrypted', $session);
}
/**
* A new session should not be classed as destroyed
*
* @test
* @covers Session::__construct
*/
public function test_default_session_is_not_classed_as_destroyed()
{
$session = $this->getMockSession();
$this->assertAttributeSame(FALSE, '_destroyed', $session);
}
/**
* Provides test data for test_get_returns_default_if_var_dnx()
*
* @return array
*/
public function provider_get_returns_default_if_var_dnx()
{
return array(
array('something_crazy', FALSE),
array('a_true', TRUE),
array('an_int', 158163158),
);
}
/**
* Make sure that get() is using the default value we provide and
* isn't tampering with it
*
* @test
* @dataProvider provider_get_returns_default_if_var_dnx
* @covers Session::get
*/
public function test_get_returns_default_if_var_dnx($var, $default)
{
$session = $this->getMockSession();
$this->assertSame($default, $session->get($var, $default));
}
/**
* By default get() should be using null as the var DNX return value
*
* @test
* @covers Session::get
*/
public function test_get_uses_null_as_default_return_value()
{
$session = $this->getMockSession();
$this->assertSame(NULL, $session->get('level_of_cool'));
}
/**
* This test makes sure that session is using array_key_exists
* as isset will return FALSE if the value is NULL
*
* @test
* @covers Session::get
*/
public function test_get_returns_value_if_it_equals_null()
{
$session = $this->getMockSession();
$session->set('arkward', NULL);
$this->assertSame(NULL, $session->get('arkward', 'uh oh'));
}
/**
* as_array() should return the session data by reference.
*
* i.e. if we modify the returned data, the session data also changes
*
* @test
* @covers Session::as_array
*/
public function test_as_array_returns_data_by_ref_or_copy()
{
$session = $this->getMockSession();
$data_ref =& $session->as_array();
$data_ref['something'] = 'pie';
$this->assertAttributeSame($data_ref, '_data', $session);
$data_copy = $session->as_array();
$data_copy['pie'] = 'awesome';
$this->assertAttributeNotSame($data_copy, '_data', $session);
}
/**
* set() should add new session data and modify existing ones
*
* Also makes sure that set() returns $this
*
* @test
* @covers Session::set
*/
public function test_set_adds_and_modifies_to_session_data()
{
$session = $this->getMockSession();
$this->assertSame($session, $session->set('pork', 'pie'));
$this->assertAttributeSame(
array('pork' => 'pie'),
'_data',
$session
);
$session->set('pork', 'delicious');
$this->assertAttributeSame(
array('pork' => 'delicious'),
'_data',
$session
);
}
/**
* This tests that delete() removes specified session data
*
* @test
* @covers Session::delete
*/
public function test_delete_removes_select_session_data()
{
$session = $this->getMockSession();
// Bit of a hack for mass-loading session data
$data =& $session->as_array();
$data += array(
'a' => 'A',
'b' => 'B',
'c' => 'C',
'easy' => '123'
);
// Make a copy of $data for testing purposes
$copy = $data;
// First we make sure we can delete one item
// Also, check that delete returns $this
$this->assertSame($session, $session->delete('a'));
unset($copy['a']);
// We could test against $data but then we'd be testing
// that as_array() is returning by ref
$this->assertAttributeSame($copy, '_data', $session);
// Now we make sure we can delete multiple items
// We're checking $this is returned just in case
$this->assertSame($session, $session->delete('b', 'c'));
unset($copy['b'], $copy['c']);
$this->assertAttributeSame($copy, '_data', $session);
}
/**
* Provides test data for test_read_loads_session_data()
*
* @return array
*/
public function provider_read_loads_session_data()
{
return array(
// If driver returns array then just load it up
array(
array(),
'wacka_wacka',
array()
),
array(
array('the it' => 'crowd'),
'the_it_crowd',
array('the it' => 'crowd'),
),
// If it's a string an encrpytion is disabled (by default) base64decode and unserialize
array(
array('dead' => 'arrival'),
'lolums',
'YToxOntzOjQ6ImRlYWQiO3M6NzoiYXJyaXZhbCI7fQ=='
),
);
}
/**
* This is one of the "big" tests for the session lib
*
* The test makes sure that
*
* 1. Session asks the driver for the data relating to $session_id
* 2. That it will load the returned data into the session
*
* @test
* @dataProvider provider_read_loads_session_data
* @covers Session::read
*/
public function test_read_loads_session_data($expected_data, $session_id, $driver_data, array $config = array())
{
$session = $this->getMockSession($config);
$session->expects($this->once())
->method('_read')
->with($session_id)
->will($this->returnValue($driver_data));
$session->read($session_id);
$this->assertAttributeSame($expected_data, '_data', $session);
}
/**
* regenerate() should tell the driver to regenerate its id
*
* @test
* @covers Session::regenerate
*/
public function test_regenerate_tells_driver_to_regenerate()
{
$session = $this->getMockSession();
$new_session_id = 'asdnoawdnoainf';
$session->expects($this->once())
->method('_regenerate')
->with()
->will($this->returnValue($new_session_id));
$this->assertSame($new_session_id, $session->regenerate());
}
/**
* If the driver destroys the session then all session data should be
* removed
*
* @test
* @covers Session::destroy
*/
public function test_destroy_deletes_data_if_driver_destroys_session()
{
$session = $this->getMockSession();
$session
->set('asd', 'dsa')
->set('dog', 'god');
$session
->expects($this->once())
->method('_destroy')
->with()
->will($this->returnValue(TRUE));
$this->assertTrue($session->destroy());
$this->assertAttributeSame(array(), '_data', $session);
}
/**
* The session data should only be deleted if the driver reports
* that the session was destroyed ok
*
* @test
* @covers Session::destroy
*/
public function test_destroy_only_deletes_data_if_driver_destroys_session()
{
$session = $this->getMockSession();
$session
->set('asd', 'dsa')
->set('dog', 'god');
$session
->expects($this->once())
->method('_destroy')
->with()
->will($this->returnValue(FALSE));
$this->assertFalse($session->destroy());
$this->assertAttributeSame(
array('asd' => 'dsa', 'dog' => 'god'),
'_data',
$session
);
}
/**
* If a session variable exists then get_once should get it then remove it.
* If the variable does not exist then it should return the default
*
* @test
* @covers Session::get_once
*/
public function test_get_once_gets_once_or_returns_default()
{
$session = $this->getMockSession();
$session->set('foo', 'bar');
// Test that a default is returned
$this->assertSame('mud', $session->get_once('fud', 'mud'));
// Now test that it actually removes the value
$this->assertSame('bar', $session->get_once('foo'));
$this->assertAttributeSame(array(), '_data', $session);
$this->assertSame('maybe', $session->get_once('foo', 'maybe'));
}
}

View File

@@ -0,0 +1,572 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests the kohana text class (Kohana_Text)
*
* @group kohana
*/
Class Kohana_TextTest extends Kohana_Unittest_TestCase
{
/**
* Sets up the test enviroment
*/
public function setUp()
{
parent::setUp();
Text::alternate();
}
/**
* This test makes sure that auto_p returns an empty string if
* an empty input was provided
*
* @test
*/
public function test_auto_para_returns_empty_string_on_empty_input()
{
$this->assertSame('', Text::auto_p(''));
}
/**
*
* @return array Test Data
*/
public function provider_auto_para_does_not_enclose_html_tags_in_paragraphs()
{
return array(
array(
array('div'),
'<div>Pick a plum of peppers</div>',
),
array(
array('div'),
'<div id="awesome">Tangas</div>',
),
);
}
/**
* This test makes sure that auto_p doesn't enclose HTML tags
* in paragraphs
*
* @test
* @dataProvider provider_auto_para_does_not_enclose_html_tags_in_paragraphs
*/
public function test_auto_para_does_not_enclose_html_tags_in_paragraphs(array $tags, $text)
{
$output = Text::auto_p($text);
foreach($tags as $tag)
{
$this->assertNotTag(
array('tag' => $tag, 'ancestor' => array('tag' => 'p')),
$output
);
}
}
/**
* This test makes sure that auto_p surrounds a single line of text
* with paragraph tags
*
* @test
*/
public function test_auto_para_encloses_slot_in_paragraph()
{
$text = 'Pick a pinch of purple pepper';
$this->assertSame('<p>'.$text.'</p>', Text::auto_p($text));
}
/**
* Data provider for test_limit_words
*
* @return array Array of test data
*/
public function provider_limit_words()
{
return array
(
array('', '', 100, NULL),
array('…', 'The rain in spain', -10, NULL),
array('The rain…', 'The rain in spain', 2, NULL),
array('The rain...', 'The rain in spain', 2, '...'),
);
}
/**
*
* @test
* @dataProvider provider_limit_words
*/
public function test_limit_words($expected, $str, $limit, $end_char)
{
$this->assertSame($expected, Text::limit_words($str, $limit, $end_char));
}
/**
* Provides test data for test_limit_chars()
*
* @return array Test data
*/
public function provider_limit_chars()
{
return array
(
array('', '', 100, NULL, FALSE),
array('…', 'BOO!', -42, NULL, FALSE),
array('making php bet…', 'making php better for the sane', 14, NULL, FALSE),
array('Garçon! Un café s.v.p.', 'Garçon! Un café s.v.p.', 50, '__', FALSE),
array('Garçon!__', 'Garçon! Un café s.v.p.', 8, '__', FALSE),
// @issue 3238
array('making php…', 'making php better for the sane', 14, NULL, TRUE),
array('Garçon!__', 'Garçon! Un café s.v.p.', 9, '__', TRUE),
array('Garçon!__', 'Garçon! Un café s.v.p.', 7, '__', TRUE),
array('__', 'Garçon! Un café s.v.p.', 5, '__', TRUE),
);
}
/**
* Tests Text::limit_chars()
*
* @test
* @dataProvider provider_limit_chars
*/
public function test_limit_chars($expected, $str, $limit, $end_char, $preserve_words)
{
$this->assertSame($expected, Text::limit_chars($str, $limit, $end_char, $preserve_words));
}
/**
* Test Text::alternate()
*
* @test
*/
public function test_alternate_alternates_between_parameters()
{
list($val_a, $val_b, $val_c) = array('good', 'bad', 'ugly');
$this->assertSame('good', Text::alternate($val_a, $val_b, $val_c));
$this->assertSame('bad', Text::alternate($val_a, $val_b, $val_c));
$this->assertSame('ugly', Text::alternate($val_a, $val_b, $val_c));
$this->assertSame('good', Text::alternate($val_a, $val_b, $val_c));
}
/**
* Tests Text::alternate()
*
* @test
* @covers Text::alternate
*/
public function test_alternate_resets_when_called_with_no_params_and_returns_empty_string()
{
list($val_a, $val_b, $val_c) = array('yes', 'no', 'maybe');
$this->assertSame('yes', Text::alternate($val_a, $val_b, $val_c));
$this->assertSame('', Text::alternate());
$this->assertSame('yes', Text::alternate($val_a, $val_b, $val_c));
}
/**
* Provides test data for test_reducde_slashes()
*
* @returns array Array of test data
*/
public function provider_reduce_slashes()
{
return array
(
array('/', '//'),
array('/google/php/kohana/', '//google/php//kohana//'),
);
}
/**
* Covers Text::reduce_slashes()
*
* @test
* @dataProvider provider_reduce_slashes
*/
public function test_reduce_slashes($expected, $str)
{
$this->assertSame($expected, Text::reduce_slashes($str));
}
/**
* Provides test data for test_censor()
*
* @return array Test data
*/
public function provider_censor()
{
return array
(
// If the replacement is 1 character long it should be repeated for the length of the removed word
array("A donkey is also an ***", 'A donkey is also an ass', array('ass'), '*', TRUE),
array("Cake### isn't nearly as good as kohana###", "CakePHP isn't nearly as good as kohanaphp", array('php'), '#', TRUE),
// If it's > 1 then it's just replaced straight out
array("If you're born out of wedlock you're a --expletive--", "If you're born out of wedlock you're a child", array('child'), '--expletive--', TRUE),
array('class', 'class', array('ass'), '*', FALSE),
);
}
/**
* Tests Text::censor
*
* @test
* @dataProvider provider_censor
*/
public function test_censor($expected, $str, $badwords, $replacement, $replace_partial_words)
{
$this->assertSame($expected, Text::censor($str, $badwords, $replacement, $replace_partial_words));
}
/**
* Provides test data for test_random
*
* @return array Test Data
*/
public function provider_random()
{
return array(
array('alnum', 8),
array('alpha', 10),
array('hexdec', 20),
array('nozero', 5),
array('numeric', 14),
array('distinct', 12),
array('aeiou', 4),
);
}
/**
* Tests Text::random() as well as possible
*
* Obviously you can't compare a randomly generated string against a
* pre-generated one and check that they are the same as this goes
* against the whole ethos of random.
*
* This test just makes sure that the value returned is of the correct
* values and length
*
* @test
* @dataProvider provider_random
*/
public function test_random($type, $length)
{
$pool = (string) $type;
switch ($pool)
{
case 'alnum':
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'alpha':
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'hexdec':
$pool = '0123456789abcdef';
break;
case 'numeric':
$pool = '0123456789';
break;
case 'nozero':
$pool = '123456789';
break;
case 'distinct':
$pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
break;
}
$this->assertRegExp('/^['.$pool.']{'.$length.'}$/', Text::random($type, $length));
}
/**
* Provides test data for test_similar
*
* @return array
*/
public function provider_similar()
{
return array
(
// TODO: add some more cases
array('foo', array('foobar', 'food', 'fooberry')),
);
}
/**
* Tests Text::similar()
*
* @test
* @dataProvider provider_similar
* @covers Text::similar
*/
public function test_similar($expected, $words)
{
$this->assertSame($expected, Text::similar($words));
}
/**
* Provides test data for test_bytes
*
* @return array
*/
public function provider_bytes()
{
return array
(
// TODO: cover the other units
array('256.00 B', 256, NULL, NULL, TRUE),
array('1.02 kB', 1024, NULL, NULL, TRUE),
// In case you need to know the size of a floppy disk in petabytes
array('0.00147 GB', 1.44 * 1000 * 1024, 'GB', '%01.5f %s', TRUE),
// SI is the standard, but lets deviate slightly
array('1.00 MiB', 1024 * 1024, 'MiB', NULL, FALSE),
);
}
/**
* Tests Text::bytes()
*
* @test
* @dataProvider provider_bytes
*/
public function test_bytes($expected, $bytes, $force_unit, $format, $si)
{
$this->assertSame($expected, Text::bytes($bytes, $force_unit, $format, $si));
}
/**
* Provides test data for test_widont()
*
* @return array Test data
*/
public function provider_widont()
{
return array
(
array('No gain, no&nbsp;pain', 'No gain, no pain'),
array("spaces?what'rethey?", "spaces?what'rethey?"),
array('', ''),
);
}
/**
* Tests Text::widont()
*
* @test
* @dataProvider provider_widont
*/
public function test_widont($expected, $string)
{
$this->assertSame($expected, Text::widont($string));
}
/**
* This checks that auto_link_emails() respects word boundaries and does not
* just blindly replace all occurences of the email address in the text.
*
* In the sample below the algorithm was replacing all occurences of voorzitter@xxxx.com
* inc the copy in the second list item.
*
* It was updated in 6c199366efc1115545ba13108b876acc66c54b2d to respect word boundaries
*
* @test
* @covers Text::auto_link_emails
* @ticket 2772
*/
public function test_auto_link_emails_respects_word_boundaries()
{
$original = '<ul>
<li>voorzitter@xxxx.com</li>
<li>vicevoorzitter@xxxx.com</li>
</ul>';
$this->assertFalse(strpos('vice', Text::auto_link_emails($original)));
}
/**
* Provides some test data for test_number()
*
* @return array
*/
public function provider_number()
{
return array(
array('one', 1),
array('twenty-three', 23),
array('fourty-two', 42),
array('five million, six hundred and thirty-two', 5000632),
array('five million, six hundred and thirty', 5000630),
array('nine hundred million', 900000000),
array('thirty-seven thousand', 37000),
array('one thousand and twenty-four', 1024),
);
}
/**
* Checks that Text::number formats a number into english text
*
* @test
* @dataProvider provider_number
*/
public function test_number($expected, $number)
{
$this->assertSame($expected, Text::number($number));
}
/**
* Provides test data for test_auto_link_urls()
*
* @return array
*/
public function provider_auto_link_urls()
{
return array(
// First we try with the really obvious url
array(
'Some random text <a href="http://www.google.com">http://www.google.com</a>',
'Some random text http://www.google.com',
),
// Then we try with varying urls
array(
'Some random <a href="http://www.google.com">www.google.com</a>',
'Some random www.google.com',
),
array(
'Some random google.com',
'Some random google.com',
),
// Check that it doesn't link urls in a href
array(
'Look at me <a href="http://google.com">Awesome stuff</a>',
'Look at me <a href="http://google.com">Awesome stuff</a>',
),
array(
'Look at me <a href="http://www.google.com">http://www.google.com</a>',
'Look at me <a href="http://www.google.com">http://www.google.com</a>',
),
// @issue 3190
array(
'<a href="http://www.google.com/">www.google.com</a>',
'<a href="http://www.google.com/">www.google.com</a>',
),
array(
'<a href="http://www.google.com/">www.google.com</a> <a href="http://www.google.com/">http://www.google.com/</a>',
'<a href="http://www.google.com/">www.google.com</a> http://www.google.com/',
),
);
}
/**
* Runs tests for Test::auto_link_urls
*
* @test
* @dataProvider provider_auto_link_urls
*/
public function test_auto_link_urls($expected, $text)
{
$this->assertSame($expected, Text::auto_link_urls($text));
}
/**
* Provides test data for test_auto_link_emails()
*
* @return array
*/
public function provider_auto_link_emails()
{
return array(
// @issue 3162
array(
'<span class="broken"><a href="mailto:info@test.com">info@test.com</a></span>',
'<span class="broken">info@test.com</span>',
),
array(
'<a href="mailto:info@test.com">info@test.com</a>',
'<a href="mailto:info@test.com">info@test.com</a>',
),
// @issue 3189
array(
'<a href="mailto:email@address.com">email@address.com</a> <a href="mailto:email@address.com">email@address.com</a>',
'<a href="mailto:email@address.com">email@address.com</a> email@address.com',
),
);
}
/**
* Runs tests for Test::auto_link_emails
*
* @test
* @dataProvider provider_auto_link_emails
*/
public function test_auto_link_emails($expected, $text)
{
// Use html_entity_decode because emails will be randomly encoded by HTML::mailto
$this->assertSame($expected, html_entity_decode(Text::auto_link_emails($text)));
}
/**
* Provides test data for test_auto_link
*
* @return array Test data
*/
public function provider_auto_link()
{
return array(
array(
'Hi there, my site is kohanaframework.org and you can email me at nobody@kohanaframework.org',
array('kohanaframework.org'),
),
array(
'Hi my.domain.com@domain.com you came from',
FALSE,
array('my.domain.com@domain.com'),
),
);
}
/**
* Tests Text::auto_link()
*
* @test
* @dataProvider provider_auto_link
*/
public function test_auto_link($text, $urls = array(), $emails = array())
{
$linked_text = Text::auto_link($text);
if($urls === FALSE)
{
$this->assertNotContains('http://', $linked_text);
}
elseif(count($urls))
{
foreach($urls as $url)
{
// Assert that all the urls have been caught by text auto_link_urls()
$this->assertContains(Text::auto_link_urls($url), $linked_text);
}
}
foreach($emails as $email)
{
$this->assertNotContains($email, $linked_text);
}
}
}

View File

@@ -0,0 +1,223 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests URL
*
* @group kohana
* @group kohana.url
*
* @package Unittest
* @author Kohana Team
* @author BRMatt <matthew@sigswitch.com>
* @copyright (c) 2008-2009 Kohana Team
* @license http://kohanaphp.com/license
*/
Class Kohana_URLTest extends Kohana_Unittest_TestCase
{
/**
* Default values for the environment, see setEnvironment
* @var array
*/
protected $environmentDefault = array(
'Kohana::$base_url' => '/kohana/',
'Kohana::$index_file'=> 'index.php',
'Request::$protocol' => 'http',
'HTTP_HOST' => 'example.com',
'_GET' => array(),
);
/**
* Provides test data for test_base()
*
* @return array
*/
public function provider_base()
{
return array(
// $index, $protocol, $expected, $enviroment
//
// Test with different combinations of parameters for max code coverage
array(FALSE, FALSE, '/kohana/'),
array(FALSE, TRUE, 'http://example.com/kohana/'),
array(TRUE, FALSE, '/kohana/index.php/'),
array(TRUE, FALSE, '/kohana/index.php/'),
array(TRUE, TRUE, 'http://example.com/kohana/index.php/'),
array(TRUE, 'http', 'http://example.com/kohana/index.php/'),
array(TRUE, 'https','https://example.com/kohana/index.php/'),
array(TRUE, 'ftp', 'ftp://example.com/kohana/index.php/'),
//
// These tests make sure that the protocol changes when the global setting changes
array(TRUE, TRUE, 'https://example.com/kohana/index.php/', array('Request::$protocol' => 'https')),
array(FALSE, TRUE, 'https://example.com/kohana/', array('Request::$protocol' => 'https')),
// Change base url'
array(FALSE, 'https', 'https://example.com/kohana/', array('Kohana::$base_url' => 'omglol://example.com/kohana/')),
// Use protocol from base url if none specified
array(FALSE, FALSE, 'http://www.example.com/', array('Kohana::$base_url' => 'http://www.example.com/')),
// Use HTTP_HOST before SERVER_NAME
array(FALSE, 'http', 'http://example.com/kohana/', array('HTTP_HOST' => 'example.com', 'SERVER_NAME' => 'example.org')),
// Use SERVER_NAME if HTTP_HOST DNX
array(FALSE, 'http', 'http://example.org/kohana/', array('HTTP_HOST' => NULL, 'SERVER_NAME' => 'example.org')),
);
}
/**
* Tests URL::base()
*
* @test
* @dataProvider provider_base
* @param boolean $index Parameter for Url::base()
* @param boolean $protocol Parameter for Url::base()
* @param string $expected Expected url
* @param array $enviroment Array of enviroment vars to change @see Kohana_URLTest::setEnvironment()
*/
public function test_base($index, $protocol, $expected, array $enviroment = array())
{
$this->setEnvironment($enviroment);
$this->assertSame(
$expected,
URL::base($index, $protocol)
);
}
/**
* Provides test data for test_site()
*
* @return array
*/
public function provider_site()
{
return array(
array('', FALSE, '/kohana/index.php/'),
array('', TRUE, 'http://example.com/kohana/index.php/'),
array('my/site', FALSE, '/kohana/index.php/my/site'),
array('my/site', TRUE, 'http://example.com/kohana/index.php/my/site'),
// @ticket #3110
array('my/site/page:5', FALSE, '/kohana/index.php/my/site/page:5'),
array('my/site/page:5', TRUE, 'http://example.com/kohana/index.php/my/site/page:5'),
array('my/site?var=asd&kohana=awesome', FALSE, '/kohana/index.php/my/site?var=asd&kohana=awesome'),
array('my/site?var=asd&kohana=awesome', TRUE, 'http://example.com/kohana/index.php/my/site?var=asd&kohana=awesome'),
array('?kohana=awesome&life=good', FALSE, '/kohana/index.php/?kohana=awesome&life=good'),
array('?kohana=awesome&life=good', TRUE, 'http://example.com/kohana/index.php/?kohana=awesome&life=good'),
array('?kohana=awesome&life=good#fact', FALSE, '/kohana/index.php/?kohana=awesome&life=good#fact'),
array('?kohana=awesome&life=good#fact', TRUE, 'http://example.com/kohana/index.php/?kohana=awesome&life=good#fact'),
array('some/long/route/goes/here?kohana=awesome&life=good#fact', FALSE, '/kohana/index.php/some/long/route/goes/here?kohana=awesome&life=good#fact'),
array('some/long/route/goes/here?kohana=awesome&life=good#fact', TRUE, 'http://example.com/kohana/index.php/some/long/route/goes/here?kohana=awesome&life=good#fact'),
array('/route/goes/here?kohana=awesome&life=good#fact', 'https', 'https://example.com/kohana/index.php/route/goes/here?kohana=awesome&life=good#fact'),
array('/route/goes/here?kohana=awesome&life=good#fact', 'ftp', 'ftp://example.com/kohana/index.php/route/goes/here?kohana=awesome&life=good#fact'),
);
}
/**
* Tests URL::site()
*
* @test
* @dataProvider provider_site
* @param string $uri URI to use
* @param boolean|string $protocol Protocol to use
* @param string $expected Expected result
* @param array $enviroment Array of enviroment vars to set
*/
public function test_site($uri, $protocol, $expected, array $enviroment = array())
{
$this->setEnvironment($enviroment);
$this->assertSame(
$expected,
URL::site($uri, $protocol)
);
}
/**
* Provides test data for test_title()
* @return array
*/
public function provider_title()
{
return array(
// Tests that..
// Title is converted to lowercase
array('we-shall-not-be-moved', 'WE SHALL NOT BE MOVED', '-'),
// Excessive white space is removed and replaced with 1 char
array('thissssss-is-it', 'THISSSSSS IS IT ', '-'),
// separator is either - (dash) or _ (underscore) & others are converted to underscores
array('some-title', 'some title', '-'),
array('some_title', 'some title', '_'),
array('some!title', 'some title', '!'),
array('some:title', 'some title', ':'),
// Numbers are preserved
array('99-ways-to-beat-apple', '99 Ways to beat apple', '-'),
// ... with lots of spaces & caps
array('99_ways_to_beat_apple', '99 ways TO beat APPLE', '_'),
array('99-ways-to-beat-apple', '99 ways TO beat APPLE', '-'),
// Invalid characters are removed
array('each-gbp-is-now-worth-32-usd', 'Each GBP(£) is now worth 32 USD($)', '-'),
// ... inc. separator
array('is-it-reusable-or-re-usable', 'Is it reusable or re-usable?', '-'),
// Doing some crazy UTF8 tests
array('espana-wins', 'España-wins', '-', TRUE),
);
}
/**
* Tests URL::title()
*
* @test
* @dataProvider provider_title
* @param string $title Input to convert
* @param string $separator Seperate to replace invalid characters with
* @param string $expected Expected result
*/
public function test_Title($expected, $title, $separator, $ascii_only = FALSE)
{
$this->assertSame(
$expected,
URL::title($title, $separator, $ascii_only)
);
}
/**
* Provides test data for URL::query()
* @return array
*/
public function provider_Query()
{
return array(
array(NULL, '', array()),
array(NULL, '?test=data', array('_GET' => array('test' => 'data'))),
array(array('test' => 'data'), '?test=data', array()),
array(array('test' => 'data'), '?more=data&test=data', array('_GET' => array('more' => 'data')))
);
}
/**
* Tests URL::query()
*
* @test
* @dataProvider provider_query
* @param array $params Query string
* @param string $expected Expected result
* @param array $enviroment Set environment
*/
public function test_query($params, $expected, $enviroment)
{
$this->setEnvironment($enviroment);
$this->assertSame(
$expected,
URL::query($params)
);
}
}

View File

@@ -0,0 +1,156 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana_UTF8 class
*
* @group kohana
* @group kohana.utf8
*
* @package Unittest
* @author Kohana Team
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_UTF8Test extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_clean()
*/
public function provider_clean()
{
return array(
array("\0", ''),
array("→foo\021", '→foo'),
array("\x7Fbar", 'bar'),
array("\xFF", ''),
array("\x41", 'A'),
);
}
/**
* Tests UTF8::clean
*
* @test
* @dataProvider provider_clean
*/
public function test_clean($input, $expected)
{
$this->assertSame($expected, UTF8::clean($input));
}
/**
* Provides test data for test_is_ascii()
*/
public function provider_is_ascii()
{
return array(
array("\0", TRUE),
array("\$eno\r", TRUE),
array('Señor', FALSE),
array(array('Se', 'nor'), TRUE),
array(array('Se', 'ñor'), FALSE),
);
}
/**
* Tests UTF8::is_ascii
*
* @test
* @dataProvider provider_is_ascii
*/
public function test_is_ascii($input, $expected)
{
$this->assertSame($expected, UTF8::is_ascii($input));
}
/**
* Provides test data for test_strip_ascii_ctrl()
*/
public function provider_strip_ascii_ctrl()
{
return array(
array("\0", ''),
array("→foo\021", '→foo'),
array("\x7Fbar", 'bar'),
array("\xFF", "\xFF"),
array("\x41", 'A'),
);
}
/**
* Tests UTF8::strip_ascii_ctrl
*
* @test
* @dataProvider provider_strip_ascii_ctrl
*/
public function test_strip_ascii_ctrl($input, $expected)
{
$this->assertSame($expected, UTF8::strip_ascii_ctrl($input));
}
/**
* Provides test data for test_strip_non_ascii()
*/
public function provider_strip_non_ascii()
{
return array(
array("\0\021\x7F", "\0\021\x7F"),
array('I ♥ cocoñùт', 'I coco'),
);
}
/**
* Tests UTF8::strip_non_ascii
*
* @test
* @dataProvider provider_strip_non_ascii
*/
public function test_strip_non_ascii($input, $expected)
{
$this->assertSame($expected, UTF8::strip_non_ascii($input));
}
/**
* Provides test data for test_str_ireplace()
*/
public function provider_str_ireplace()
{
return array(
array('т', 't', 'cocoñuт', 'cocoñut'),
array('Ñ', 'N', 'cocoñuт', 'cocoNuт'),
array(array('т', 'Ñ'), array('t', 'N'), 'cocoñuт', 'cocoNut'),
);
}
/**
* Tests UTF8::str_ireplace
*
* @test
* @dataProvider provider_str_ireplace
*/
public function test_str_ireplace($search, $replace, $subject, $expected)
{
$this->assertSame($expected, UTF8::str_ireplace($search, $replace, $subject));
}
/**
* Provides test data for test_strip_non_ascii()
*/
public function provider_ucwords()
{
return array(
array('ExAmple', 'ExAmple'),
array('i ♥ Cocoñùт', 'I ♥ Cocoñùт'),
);
}
/**
* Tests UTF8::ucwords
*
* @test
* @dataProvider provider_ucwords
*/
public function test_ucwords($input, $expected)
{
$this->assertSame($expected, UTF8::ucwords($input));
}
}

View File

@@ -0,0 +1,223 @@
<?php defined('SYSPATH') OR die('Kohana bootstrap needs to be included before tests run');
/**
* Tests Kohana upload class
*
* @group kohana
* @group kohana.upload
*
* @package Unittest
* @author Kohana Team
* @author Jeremy Bush <contractfrombelow@gmail.com>
* @copyright (c) 2008-2010 Kohana Team
* @license http://kohanaphp.com/license
*/
class Kohana_UploadTest extends Kohana_Unittest_TestCase
{
/**
* Provides test data for test_size()
*
* @return array
*/
public function provider_size()
{
return array(
// $field, $bytes, $environment, $expected
array(
'unit_test',
5,
array('_FILES' => array('unit_test' => array('error' => UPLOAD_ERR_INI_SIZE))),
FALSE
),
array(
'unit_test',
5,
array('_FILES' => array('unit_test' => array('error' => UPLOAD_ERR_NO_FILE))),
TRUE
),
array(
'unit_test',
'6K',
array('_FILES' => array(
'unit_test' => array(
'error' => UPLOAD_ERR_OK,
'name' => 'Unit_Test File',
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
)
),
TRUE
),
array(
'unit_test',
'1B',
array('_FILES' => array(
'unit_test' => array(
'error' => UPLOAD_ERR_OK,
'name' => 'Unit_Test File',
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
)
),
FALSE
),
);
}
/**
* Tests Upload::size
*
* @test
* @dataProvider provider_size
* @covers upload::size
* @param string $field the files field to test
* @param string $bytes valid bite size
* @param array $environment set the $_FILES array
* @param $expected what to expect
*/
public function test_size($field, $bytes, $environment, $expected)
{
$this->setEnvironment($environment);
$this->assertSame($expected, Upload::size($_FILES[$field], $bytes));
}
/**
* size() should throw an exception of the supplied max size is invalid
*
* @test
* @covers upload::size
* @expectedException Kohana_Exception
*/
public function test_size_throws_exception_for_invalid_size()
{
$this->setEnvironment(array(
'_FILES' => array(
'unit_test' => array(
'error' => UPLOAD_ERR_OK,
'name' => 'Unit_Test File',
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
)
));
Upload::size($_FILES['unit_test'], '1DooDah');
}
/**
* Provides test data for test_vali()
*
* @test
* @return array
*/
public function provider_valid()
{
return array(
array(
TRUE,
array(
'error' => UPLOAD_ERR_OK,
'name' => 'Unit_Test File',
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
),
array(
FALSE,
array(
'name' => 'Unit_Test File',
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
),
array(
FALSE,
array(
'error' => UPLOAD_ERR_OK,
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
),
array(
FALSE,
array(
'name' => 'Unit_Test File',
'error' => UPLOAD_ERR_OK,
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
),
array(
FALSE,
array(
'error' => UPLOAD_ERR_OK,
'name' => 'Unit_Test File',
'type' => 'image/png',
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
),
array(
FALSE,
array(
'error' => UPLOAD_ERR_OK,
'name' => 'Unit_Test File',
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
)
),
);
}
/**
* Test Upload::valid
*
* @test
* @dataProvider provider_valid
* @covers Upload::valid
*/
public function test_valid($expected, $file)
{
$this->setEnvironment(array(
'_FILES' => array(
'unit_test' => $file,
),
));
$this->assertSame($expected, Upload::valid($_FILES['unit_test']));
}
/**
* Tests Upload::type
*
* @test
* @covers Upload::type
*/
public function test_type()
{
$this->setEnvironment(array(
'_FILES' => array(
'unit_test' => array(
'error' => UPLOAD_ERR_OK,
'name' => 'github.png',
'type' => 'image/png',
'tmp_name' => Kohana::find_file('tests', 'test_data/github', 'png'),
'size' => filesize(Kohana::find_file('tests', 'test_data/github', 'png')),
)
)
));
$this->assertTrue(Upload::type($_FILES['unit_test'], array('jpg', 'png', 'gif')));
$this->assertFalse(Upload::type($_FILES['unit_test'], array('docx')));
}
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.0 KiB