diff options
Diffstat (limited to 'tests')
53 files changed, 2097 insertions, 978 deletions
diff --git a/tests/RUNNING_TESTS.txt b/tests/RUNNING_TESTS.txt index 74a0635c1a..59197acc0f 100644 --- a/tests/RUNNING_TESTS.txt +++ b/tests/RUNNING_TESTS.txt @@ -7,7 +7,7 @@ Prerequisites PHPUnit ------- -phpBB unit tests use PHPUnit framework. Version 3.3 or better is required +phpBB unit tests use PHPUnit framework. Version 3.5 or better is required to run the tests. PHPUnit prefers to be installed via PEAR; refer to http://www.phpunit.de/ for more information. @@ -41,14 +41,23 @@ will run phpunit with the same parameters as in the shown test_config.php file: $ PHPBB_TEST_DBMS='mysqli' PHPBB_TEST_DBHOST='localhost' \ PHPBB_TEST_DBNAME='database' PHPBB_TEST_DBUSER='user' \ - PHPBB_TEST_DBPASSWD='password' phpunit all_tests.php + PHPBB_TEST_DBPASSWD='password' phpunit Running ======= -Once the prerequisites are installed, run the tests from tests directory: +Once the prerequisites are installed, run the tests from the project root directory (above phpBB): - $ phpunit all_tests.php + $ phpunit + +Slow tests +-------------- +Certain tests, such as the UTF-8 normalizer or the DNS tests tend to be slow. +Thus these tests are in the `slow` group, which is excluded by default. You can +enable slow tests by copying the phpunit.xml.all file to phpunit.xml. If you only +want the slow tests, run: + + $ phpunit --group slow More Information ================ diff --git a/tests/all_tests.php b/tests/all_tests.php deleted file mode 100644 index d1d711c4d7..0000000000 --- a/tests/all_tests.php +++ /dev/null @@ -1,69 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2008 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -error_reporting(E_ALL); - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'utf/all_tests.php'; -require_once 'request/all_tests.php'; -require_once 'security/all_tests.php'; -require_once 'template/all_tests.php'; -require_once 'text_processing/all_tests.php'; -require_once 'dbal/all_tests.php'; -require_once 'regex/all_tests.php'; -require_once 'network/all_tests.php'; -require_once 'random/all_tests.php'; - -// exclude the test directory from code coverage reports -if (version_compare(PHPUnit_Runner_Version::id(), '3.5.0') >= 0) -{ - PHP_CodeCoverage_Filter::getInstance()->addDirectoryToBlacklist('./'); -} -else -{ - PHPUnit_Util_Filter::addDirectoryToFilter('./'); -} - -class phpbb_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB'); - - $suite->addTest(phpbb_utf_all_tests::suite()); - $suite->addTest(phpbb_request_all_tests::suite()); - $suite->addTest(phpbb_security_all_tests::suite()); - $suite->addTest(phpbb_template_all_tests::suite()); - $suite->addTest(phpbb_text_processing_all_tests::suite()); - $suite->addTest(phpbb_dbal_all_tests::suite()); - $suite->addTest(phpbb_regex_all_tests::suite()); - $suite->addTest(phpbb_network_all_tests::suite()); - $suite->addTest(phpbb_random_all_tests::suite()); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_all_tests::main') -{ - phpbb_all_tests::main(); -} - diff --git a/tests/bbcode/url_bbcode_test.php b/tests/bbcode/url_bbcode_test.php new file mode 100644 index 0000000000..cd85dbd0d9 --- /dev/null +++ b/tests/bbcode/url_bbcode_test.php @@ -0,0 +1,63 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2010 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions_content.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/bbcode.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/message_parser.php'; +require_once dirname(__FILE__) . '/../mock_user.php'; + +class phpbb_url_bbcode_test extends phpbb_test_case +{ + public function url_bbcode_test_data() + { + return array( + array( + 'url only', + '[url]http://www.phpbb.com/community/[/url]', + '[url:]http://www.phpbb.com/community/[/url:]' + ), + array( + 'url with title', + '[url=http://www.phpbb.com/community/]One line URL text[/url]', + '[url=http://www.phpbb.com/community/:]One line URL text[/url:]' + ), + array( + 'url with multiline title', + "[url=http://www.phpbb.com/community/]Multiline\x0AURL\x0Atext[/url]", + "[url=http://www.phpbb.com/community/:]Multiline\x0AURL\x0Atext[/url:]" + ), + array( + 'unclosed url with multiline', + "test [url] test \x0A test [url=http://www.phpbb.com/]test[/url] test", + "test [url] test \x0A test [url=http://www.phpbb.com/:]test[/url:] test" + ), + array( + 'unclosed url with multiline and title', + "test [url=http://www.phpbb.com/]test \x0A [url]http://phpbb.com[/url] test", + "test [url=http://www.phpbb.com/:]test \x0A [url]http://phpbb.com[/url:] test" + ), + ); + } + + /** + * @dataProvider url_bbcode_test_data + */ + public function test_url($description, $message, $expected) + { + global $user; + $user = new phpbb_mock_user; + + $bbcode = new bbcode_firstpass(); + $bbcode->message = $message; + $bbcode->bbcode_init(false); + $bbcode->parse_bbcode(); + $this->assertEquals($expected, $bbcode->message); + } +} diff --git a/tests/test_framework/framework.php b/tests/bootstrap.php index 3a11cc6df9..6f3c93a374 100644 --- a/tests/test_framework/framework.php +++ b/tests/bootstrap.php @@ -8,9 +8,15 @@ */ define('IN_PHPBB', true); -$phpbb_root_path = '../phpBB/'; +$phpbb_root_path = 'phpBB/'; $phpEx = 'php'; -$table_prefix = ''; +$table_prefix = 'phpbb_'; + +if (!defined('E_DEPRECATED')) +{ + define('E_DEPRECATED', 8192); +} +error_reporting(E_ALL & ~E_DEPRECATED); // If we are on PHP >= 6.0.0 we do not need some code if (version_compare(PHP_VERSION, '6.0.0-dev', '>=')) @@ -25,19 +31,7 @@ else require_once $phpbb_root_path . 'includes/constants.php'; -// require at least PHPUnit 3.3.0 -require_once 'PHPUnit/Runner/Version.php'; -if (version_compare(PHPUnit_Runner_Version::id(), '3.3.0', '<')) -{ - trigger_error('PHPUnit >= 3.3.0 required'); -} - -if (version_compare(PHPUnit_Runner_Version::id(), '3.5.0', '<')) -{ - require_once 'PHPUnit/Framework.php'; - require_once 'PHPUnit/Extensions/Database/TestCase.php'; -} - require_once 'test_framework/phpbb_test_case_helpers.php'; require_once 'test_framework/phpbb_test_case.php'; require_once 'test_framework/phpbb_database_test_case.php'; +require_once 'test_framework/phpbb_database_test_connection_manager.php'; diff --git a/tests/dbal/all_tests.php b/tests/dbal/all_tests.php deleted file mode 100644 index cfa8176246..0000000000 --- a/tests/dbal/all_tests.php +++ /dev/null @@ -1,42 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2008 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_dbal_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'dbal/select.php'; -require_once 'dbal/write.php'; - -class phpbb_dbal_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Database Abstraction Layer'); - - $suite->addTestSuite('phpbb_dbal_select_test'); - $suite->addTestSuite('phpbb_dbal_write_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_dbal_all_tests::main') -{ - phpbb_dbal_all_tests::main(); -} diff --git a/tests/dbal/db_tools_test.php b/tests/dbal/db_tools_test.php new file mode 100644 index 0000000000..ddea500f83 --- /dev/null +++ b/tests/dbal/db_tools_test.php @@ -0,0 +1,276 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/db/db_tools.php'; + +class phpbb_dbal_db_tools_test extends phpbb_database_test_case +{ + protected $db; + protected $tools; + protected $table_exists; + protected $table_data; + + public function getDataSet() + { + return $this->createXMLDataSet(dirname(__FILE__).'/fixtures/config.xml'); + } + + protected function setUp() + { + parent::setUp(); + + $this->db = $this->new_dbal(); + $this->tools = new phpbb_db_tools($this->db); + + $this->table_data = array( + 'COLUMNS' => array( + 'c_id' => array('UINT', NULL, 'auto_increment'), + 'c_int_size' => array('INT:4', 4), + 'c_bint' => array('BINT', 4), + 'c_uint' => array('UINT', 4), + 'c_uint_size' => array('UINT:4', 4), + 'c_tint_size' => array('TINT:2', 4), + 'c_usint' => array('USINT', 4), + 'c_bool' => array('BOOL', 1), + 'c_vchar' => array('VCHAR', 'foo'), + 'c_vchar_size' => array('VCHAR:4', 'foo'), + 'c_char_size' => array('CHAR:4', 'foo'), + 'c_xstext' => array('XSTEXT', 'foo'), + 'c_stext' => array('STEXT', 'foo'), + 'c_text' => array('TEXT', 'foo'), + 'c_mtext' => array('MTEXT', 'foo'), + 'c_xstext_uni' => array('XSTEXT_UNI', 'foo'), + 'c_stext_uni' => array('STEXT_UNI', 'foo'), + 'c_text_uni' => array('TEXT_UNI', 'foo'), + 'c_mtext_uni' => array('MTEXT_UNI', 'foo'), + 'c_timestamp' => array('TIMESTAMP', 4), + 'c_decimal' => array('DECIMAL', 4.2), + 'c_decimal_size' => array('DECIMAL:6', 4.2), + 'c_pdecimal' => array('PDECIMAL', 4.2), + 'c_pdecimal_size' => array('PDECIMAL:7', 4.2), + 'c_vchar_uni' => array('VCHAR_UNI', 'foo'), + 'c_vchar_uni_size' => array('VCHAR_UNI:4', 'foo'), + 'c_vchar_ci' => array('VCHAR_CI', 'foo'), + 'c_varbinary' => array('VARBINARY', 'foo'), + ), + 'PRIMARY_KEY' => 'c_id', + 'KEYS' => array( + 'i_simple' => array('INDEX', 'c_uint'), + 'i_uniq' => array('UNIQUE', 'c_vchar'), + 'i_comp' => array('INDEX', array('c_vchar_uni', 'c_bool')), + 'i_comp_uniq' => array('UNIQUE', array('c_vchar_size', 'c_usint')), + ), + ); + $this->tools->sql_create_table('prefix_table_name', $this->table_data); + $this->table_exists = true; + } + + protected function tearDown() + { + if ($this->table_exists) + { + $this->tools->sql_table_drop('prefix_table_name'); + } + + parent::tearDown(); + } + + public function test_created_and_drop_table() + { + // table is empty after creation and queryable + $sql = 'SELECT * FROM prefix_table_name'; + $result = $this->db->sql_query($sql); + $this->assertTrue(! $this->db->sql_fetchrow($result)); + $this->db->sql_freeresult($result); + + $this->table_exists = false; + $this->tools->sql_table_drop('prefix_table_name'); + } + + static protected function get_default_values() + { + return array( + 'c_int_size' => 0, + 'c_bint' => 0, + 'c_uint' => 0, + 'c_uint_size' => 0, + 'c_tint_size' => 0, + 'c_usint' => 0, + 'c_bool' => 0, + 'c_vchar' => '', + 'c_vchar_size' => '', + 'c_char_size' => '', + 'c_xstext' => '', + 'c_stext' => '', + 'c_text' => '', + 'c_mtext' => '', + 'c_xstext_uni' => '', + 'c_stext_uni' => '', + 'c_text_uni' => '', + 'c_mtext_uni' => '', + 'c_timestamp' => 0, + 'c_decimal' => 0, + 'c_decimal_size' => 0, + 'c_pdecimal' => 0, + 'c_pdecimal_size' => 0, + 'c_vchar_uni' => '', + 'c_vchar_uni_size' => '', + 'c_vchar_ci' => '', + 'c_varbinary' => '', + ); + } + + static public function column_values() + { + return array( + array('c_int_size', -9999), + array('c_bint', '99999999999999999'), + array('c_uint', 16777215), + array('c_uint_size', 9999), + array('c_tint_size', -99), + array('c_usint', 99), + array('c_bool', 0), + array('c_vchar', str_repeat('a', 255)), + array('c_vchar_size', str_repeat('a', 4)), + array('c_char_size', str_repeat('a', 4)), + array('c_xstext', str_repeat('a', 1000)), + array('c_stext', str_repeat('a', 3000)), + array('c_text', str_repeat('a', 8000)), + array('c_mtext', str_repeat('a', 10000)), + array('c_xstext_uni', str_repeat("\xC3\x84", 100)), + array('c_stext_uni', str_repeat("\xC3\x84", 255)), + array('c_text_uni', str_repeat("\xC3\x84", 4000)), + array('c_mtext_uni', str_repeat("\xC3\x84", 10000)), + array('c_timestamp', 2147483647), + array('c_decimal', 999.99), + array('c_decimal_size', 9999.99), + array('c_pdecimal', 999.999), + array('c_pdecimal_size', 9999.999), + array('c_vchar_uni', str_repeat("\xC3\x84", 255)), + array('c_vchar_uni_size', str_repeat("\xC3\x84", 4)), + array('c_vchar_ci', str_repeat("\xC3\x84", 255)), + array('c_varbinary', str_repeat("\x00\xFF", 127)), + ); + } + + /** + * @dataProvider column_values + */ + public function test_created_column($column_name, $column_value) + { + $row_insert = self::get_default_values(); + $row_insert[$column_name] = $column_value; + + // empty table + $sql = 'DELETE FROM prefix_table_name'; + $result = $this->db->sql_query($sql); + + $sql = 'INSERT INTO prefix_table_name ' . $this->db->sql_build_array('INSERT', $row_insert); + $result = $this->db->sql_query($sql); + + $sql = "SELECT * + FROM prefix_table_name"; + $result = $this->db->sql_query($sql); + $row_actual = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + $row_expect = $row_insert; + + unset($row_actual['id']); // auto increment id changes, so ignore + + $type = $this->table_data['COLUMNS'][$column_name][0]; + $this->assertEquals($row_expect[$column_name], $row_actual[$column_name], "Column $column_name of type $type should have equal return and input value."); + } + + public function test_auto_increment() + { + $sql = 'DELETE FROM prefix_table_name'; + $result = $this->db->sql_query($sql); + + $row1 = array_merge(self::get_default_values(), array( + 'c_uint' => 1, + 'c_vchar' => '1', // these values are necessary to avoid unique index issues + 'c_vchar_size' => '1', + )); + $row2 = array_merge(self::get_default_values(), array( + 'c_uint' => 2, + 'c_vchar' => '2', + 'c_vchar_size' => '2', + )); + + $sql = 'INSERT INTO prefix_table_name ' . $this->db->sql_build_array('INSERT', $row1); + $result = $this->db->sql_query($sql); + $id1 = $this->db->sql_nextid(); + + $sql = 'INSERT INTO prefix_table_name ' . $this->db->sql_build_array('INSERT', $row2); + $result = $this->db->sql_query($sql); + $id2 = $this->db->sql_nextid(); + + $this->assertGreaterThan($id1, $id2, 'Auto increment should increase the id value'); + + $sql = "SELECT * + FROM prefix_table_name WHERE c_id = $id1"; + $result = $this->db->sql_query($sql); + $row_actual = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + $row1['c_id'] = $id1; + $this->assertEquals($row1, $row_actual); + + $sql = "SELECT * + FROM prefix_table_name WHERE c_id = $id2"; + $result = $this->db->sql_query($sql); + $row_actual = $this->db->sql_fetchrow($result); + $this->db->sql_freeresult($result); + + $row2['c_id'] = $id2; + $this->assertEquals($row2, $row_actual); + } + + public function test_column_exists() + { + $this->assertTrue($this->tools->sql_column_exists('prefix_table_name', 'c_id')); + $this->assertFalse($this->tools->sql_column_exists('prefix_table_name', 'column_does_not_exist')); + } + + public function test_column_remove() + { + $this->assertTrue($this->tools->sql_column_exists('prefix_table_name', 'c_int_size')); + + $this->assertTrue($this->tools->sql_column_remove('prefix_table_name', 'c_int_size')); + + $this->assertFalse($this->tools->sql_column_exists('prefix_table_name', 'c_int_size')); + } + + public function test_column_remove_primary() + { + $this->assertTrue($this->tools->sql_column_exists('prefix_table_name', 'c_id')); + + $this->assertTrue($this->tools->sql_column_remove('prefix_table_name', 'c_id')); + + $this->assertFalse($this->tools->sql_column_exists('prefix_table_name', 'c_id')); + } + + public function test_table_exists() + { + $this->assertTrue($this->tools->sql_table_exists('prefix_table_name')); + $this->assertFalse($this->tools->sql_table_exists('prefix_does_not_exist')); + } + + public function test_table_drop() + { + $this->tools->sql_create_table('prefix_test_table', + array('COLUMNS' => array( + 'foo' => array('UINT', 42))) + ); + + $this->tools->sql_table_drop('prefix_test_table'); + } +} diff --git a/tests/dbal/select.php b/tests/dbal/select_test.php index 70f27549d2..e0d08d9306 100644 --- a/tests/dbal/select.php +++ b/tests/dbal/select_test.php @@ -7,8 +7,8 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/utf/utf_tools.php'; class phpbb_dbal_select_test extends phpbb_database_test_case { @@ -318,4 +318,27 @@ class phpbb_dbal_select_test extends phpbb_database_test_case $db->sql_freeresult($result); } + + function test_nested_transactions() + { + $db = $this->new_dbal(); + + // nested transactions should work on systems that do not require + // buffering of nested transactions, so ignore the ones that need + // buffering + if ($db->sql_buffer_nested_transactions()) + { + return; + } + + $sql = 'SELECT user_id FROM phpbb_users ORDER BY user_id ASC'; + $result1 = $db->sql_query($sql); + + $db->sql_transaction('begin'); + $result2 = $db->sql_query($sql); + $row = $db->sql_fetchrow($result2); + $db->sql_transaction('commit'); + + $this->assertEquals('1', $row['user_id']); + } } diff --git a/tests/dbal/write.php b/tests/dbal/write_test.php index 01deacda69..4709d45fa5 100644 --- a/tests/dbal/write.php +++ b/tests/dbal/write_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; class phpbb_dbal_write_test extends phpbb_database_test_case { diff --git a/tests/mock/cache.php b/tests/mock/cache.php new file mode 100644 index 0000000000..11e525ff79 --- /dev/null +++ b/tests/mock/cache.php @@ -0,0 +1,73 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2008 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +class phpbb_mock_cache +{ + public function __construct($data = array()) + { + $this->data = $data; + + if (!isset($this->data['_bots'])) + { + $this->data['_bots'] = array(); + } + } + + public function get($var_name) + { + if (isset($this->data[$var_name])) + { + return $this->data[$var_name]; + } + + return false; + } + + public function put($var_name, $var, $ttl = 0) + { + $this->data[$var_name] = $var; + } + + /** + * Obtain active bots + */ + public function obtain_bots() + { + return $this->data['_bots']; + } + + public function set_bots($bots) + { + $this->data['_bots'] = $bots; + } + + public function checkVar(PHPUnit_Framework_Assert $test, $var_name, $data) + { + $test->assertTrue(isset($this->data[$var_name])); + $test->assertEquals($data, $this->data[$var_name]); + } + + public function check(PHPUnit_Framework_Assert $test, $data, $ignore_db_info = true) + { + $cache_data = $this->data; + + if ($ignore_db_info) + { + unset($cache_data['mssqlodbc_version']); + unset($cache_data['mssql_version']); + unset($cache_data['mysql_version']); + unset($cache_data['mysqli_version']); + unset($cache_data['pgsql_version']); + unset($cache_data['sqlite_version']); + } + + $test->assertEquals($data, $cache_data); + } +} + diff --git a/tests/mock/session_testable.php b/tests/mock/session_testable.php new file mode 100644 index 0000000000..47089cb94b --- /dev/null +++ b/tests/mock/session_testable.php @@ -0,0 +1,63 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2008 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/session.php'; + +/** +* Extends the session class to overwrite the setting of cookies. +* +* The session class directly writes cookie headers making it impossible to +* test it without warnings about sent headers. This class only stores cookie +* data for later verification. +*/ +class phpbb_mock_session_testable extends session +{ + private $_cookies = array(); + + public function set_cookie($name, $data, $time) + { + $this->_cookies[$name] = array($data, $time); + } + + /** + * Checks if the cookies were set correctly. + * + * @param PHPUnit_Framework_Assert test The test from which this is called + * @param array(string => mixed) cookies The cookie data to check against. + * The keys are cookie names, the values can either be null to + * check only the existance of the cookie, or an array(d, t), + * where d is the cookie data to check, or null to skip the + * check and t is the cookie time to check, or null to skip. + */ + public function check_cookies(PHPUnit_Framework_Assert $test, $cookies) + { + $test->assertEquals(array_keys($cookies), array_keys($this->_cookies), 'Incorrect cookies were set'); + + foreach ($cookies as $name => $cookie) + { + if (!is_null($cookie)) + { + $data = $cookie[0]; + $time = $cookie[1]; + + if (!is_null($data)) + { + $test->assertEquals($data, $this->_cookies[$name][0], "Cookie $name contains incorrect data"); + } + + if (!is_null($time)) + { + $test->assertEquals($time, $this->_cookies[$name][1], "Cookie $name expires at the wrong time"); + } + } + } + } +} + diff --git a/tests/mock_user.php b/tests/mock_user.php new file mode 100644 index 0000000000..74d31c4c4a --- /dev/null +++ b/tests/mock_user.php @@ -0,0 +1,20 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +/** +* Mock user class. +* This class is used when tests invoke phpBB code expecting to have a global +* user object, to avoid instantiating the actual user object. +* It has a minimum amount of functionality, just to make tests work. +*/ +class phpbb_mock_user +{ + public $host = "testhost"; + public $page = array('root_script_path' => '/'); +} diff --git a/tests/network/all_tests.php b/tests/network/all_tests.php deleted file mode 100644 index b500647f81..0000000000 --- a/tests/network/all_tests.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2010 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_network_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'network/checkdnsrr.php'; - -class phpbb_network_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Network Functions'); - - $suite->addTestSuite('phpbb_network_checkdnsrr_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_network_all_tests::main') -{ - phpbb_network_all_tests::main(); -} diff --git a/tests/network/checkdnsrr.php b/tests/network/checkdnsrr_test.php index 57fe2761cc..5a756dcef8 100644 --- a/tests/network/checkdnsrr.php +++ b/tests/network/checkdnsrr_test.php @@ -7,9 +7,11 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +/** +* @group slow +*/ class phpbb_network_checkdnsrr_test extends phpbb_test_case { public function data_provider() diff --git a/tests/profile/custom_test.php b/tests/profile/custom_test.php new file mode 100644 index 0000000000..0e0a851243 --- /dev/null +++ b/tests/profile/custom_test.php @@ -0,0 +1,55 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions_profile_fields.php'; + +class phpbb_profile_custom_test extends phpbb_database_test_case +{ + public function getDataSet() + { + return $this->createXMLDataSet(dirname(__FILE__).'/fixtures/profile_fields.xml'); + } + + static public function dropdownFields() + { + return array( + // note, there is an offset of 1 between option_id (0-indexed) + // in the database and values (1-indexed) to avoid problems with + // transmitting 0 in an HTML form + // required, value, expected + array(1, '0', 'FIELD_INVALID_VALUE', 'Required field should throw error for out-of-range value'), + array(1, '1', 'FIELD_REQUIRED', 'Required field should throw error for default value'), + array(1, '2', false, 'Required field should accept non-default value'), + array(0, '0', 'FIELD_INVALID_VALUE', 'Optional field should throw error for out-of-range value'), + array(0, '1', false, 'Optional field should accept default value'), + array(0, '2', false, 'Optional field should accept non-default value'), + ); + } + + /** + * @dataProvider dropdownFields + */ + public function test_dropdown_validate($field_required, $field_value, $expected, $description) + { + global $db; + $db = $this->new_dbal(); + + $field_data = array( + 'field_id' => 1, + 'lang_id' => 1, + 'field_novalue' => 1, + 'field_required' => $field_required, + ); + + $cp = new custom_profile; + $result = $cp->validate_profile_field(FIELD_DROPDOWN, &$field_value, $field_data); + + $this->assertEquals($expected, $result, $description); + } +} diff --git a/tests/profile/fixtures/profile_fields.xml b/tests/profile/fixtures/profile_fields.xml new file mode 100644 index 0000000000..0b2929f625 --- /dev/null +++ b/tests/profile/fixtures/profile_fields.xml @@ -0,0 +1,31 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<dataset> + <table name="phpbb_profile_fields_lang"> + <column>field_id</column> + <column>lang_id</column> + <column>option_id</column> + <column>field_type</column> + <column>lang_value</column> + <row> + <value>1</value> + <value>1</value> + <value>0</value> + <value>5</value> + <value>Default Option</value> + </row> + <row> + <value>1</value> + <value>1</value> + <value>1</value> + <value>5</value> + <value>First Alternative</value> + </row> + <row> + <value>1</value> + <value>1</value> + <value>2</value> + <value>5</value> + <value>Third Alternative</value> + </row> + </table> +</dataset> diff --git a/tests/random/all_tests.php b/tests/random/all_tests.php deleted file mode 100644 index c6ffe78024..0000000000 --- a/tests/random/all_tests.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2010 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_random_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'random/gen_rand_string.php'; - -class phpbb_random_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Random Functions'); - - $suite->addTestSuite('phpbb_random_gen_rand_string_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_random_all_tests::main') -{ - phpbb_random_all_tests::main(); -} diff --git a/tests/random/gen_rand_string.php b/tests/random/gen_rand_string_test.php index cd58d14ed3..115c55e4e2 100644 --- a/tests/random/gen_rand_string.php +++ b/tests/random/gen_rand_string_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; class phpbb_random_gen_rand_string_test extends phpbb_test_case { diff --git a/tests/random/mt_rand.php b/tests/random/mt_rand.php new file mode 100644 index 0000000000..d6502c4e80 --- /dev/null +++ b/tests/random/mt_rand.php @@ -0,0 +1,46 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; + +class phpbb_random_mt_rand_test extends phpbb_test_case +{ + public function test_max_equals_min() + { + $result = phpbb_mt_rand(42, 42); + $this->assertEquals(42, $result); + } + + public function test_max_equals_min_negative() + { + $result = phpbb_mt_rand(-42, -42); + $this->assertEquals(-42, $result); + } + + public function test_max_greater_min() + { + $result = phpbb_mt_rand(3, 4); + $this->assertGreaterThanOrEqual(3, $result); + $this->assertLessThanOrEqual(4, $result); + } + + public function test_min_greater_max() + { + $result = phpbb_mt_rand(4, 3); + $this->assertGreaterThanOrEqual(3, $result); + $this->assertLessThanOrEqual(4, $result); + } + + public function test_min_greater_max_negative() + { + $result = phpbb_mt_rand(-3, -4); + $this->assertGreaterThanOrEqual(-4, $result); + $this->assertLessThanOrEqual(-3, $result); + } +} diff --git a/tests/regex/all_tests.php b/tests/regex/all_tests.php deleted file mode 100644 index 316a9d4a58..0000000000 --- a/tests/regex/all_tests.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2010 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_regex_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'regex/email.php'; -require_once 'regex/ipv4.php'; -require_once 'regex/ipv6.php'; -require_once 'regex/url.php'; - -class phpbb_regex_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Regular Expressions'); - - $suite->addTestSuite('phpbb_regex_email_test'); - $suite->addTestSuite('phpbb_regex_ipv4_test'); - $suite->addTestSuite('phpbb_regex_ipv6_test'); - $suite->addTestSuite('phpbb_regex_url_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_regex_all_tests::main') -{ - phpbb_regex_all_tests::main(); -} diff --git a/tests/regex/censor_test.php b/tests/regex/censor_test.php new file mode 100644 index 0000000000..fa9104e71d --- /dev/null +++ b/tests/regex/censor_test.php @@ -0,0 +1,50 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2010 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; + +class phpbb_regex_censor_test extends phpbb_test_case +{ + public function censor_test_data() + { + return array( + array('bad*word', 'bad word'), + array('bad***word', 'bad word'), + array('bad**word', 'bad word'), + array('*bad*word*', 'bad word'), + array('b*d', 'bad'), + array('*bad*', 'bad'), + array('*b*d*', 'bad'), + array('*b*d*', 'b d'), + array('b*d*word', 'bad word'), + array('**b**d**word**', 'bad word'), + array('**b**d**word**', 'the bad word catched'), + ); + } + + /** + * @dataProvider censor_test_data + */ + public function test_censor_unicode($pattern, $subject) + { + $regex = get_censor_preg_expression($pattern, true); + + $this->assertRegExp($regex, $subject); + } + + /** + * @dataProvider censor_test_data + */ + public function test_censor_no_unicode($pattern, $subject) + { + $regex = get_censor_preg_expression($pattern, false); + + $this->assertRegExp($regex, $subject); + } +}
\ No newline at end of file diff --git a/tests/regex/email.php b/tests/regex/email_test.php index 8658b8af36..0695b801d5 100644 --- a/tests/regex/email.php +++ b/tests/regex/email_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; class phpbb_regex_email_test extends phpbb_test_case { diff --git a/tests/regex/ipv4.php b/tests/regex/ipv4_test.php index 9d131ad0ca..9829547508 100644 --- a/tests/regex/ipv4.php +++ b/tests/regex/ipv4_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; class phpbb_regex_ipv4_test extends phpbb_test_case { diff --git a/tests/regex/ipv6.php b/tests/regex/ipv6_test.php index 3d7a72e492..1b2018403c 100644 --- a/tests/regex/ipv6.php +++ b/tests/regex/ipv6_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; class phpbb_regex_ipv6_test extends phpbb_test_case { diff --git a/tests/regex/password_complexity_test.php b/tests/regex/password_complexity_test.php new file mode 100644 index 0000000000..21e8d12a0a --- /dev/null +++ b/tests/regex/password_complexity_test.php @@ -0,0 +1,81 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2010 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions_user.php'; + +class phpbb_password_complexity_test extends phpbb_test_case +{ + public function password_complexity_test_data_positive() + { + return array( + array('12345', 'PASS_TYPE_ANY'), + array('qwerty', 'PASS_TYPE_ANY'), + array('QWERTY', 'PASS_TYPE_ANY'), + array('QwerTY', 'PASS_TYPE_ANY'), + array('q$erty', 'PASS_TYPE_ANY'), + array('qW$rty', 'PASS_TYPE_ANY'), + + array('QwerTY', 'PASS_TYPE_CASE'), + array('QwerTY123', 'PASS_TYPE_ALPHA'), + array('QwerTY123$&', 'PASS_TYPE_SYMBOL'), + + array('', 'PASS_TYPE_ANY'), + ); + } + + public function password_complexity_test_data_negative() + { + return array( + array('qwerty', 'PASS_TYPE_CASE'), + array('QWERTY', 'PASS_TYPE_CASE'), + array('123456', 'PASS_TYPE_CASE'), + array('#$&', 'PASS_TYPE_CASE'), + array('QTY123$', 'PASS_TYPE_CASE'), + + array('qwerty', 'PASS_TYPE_ALPHA'), + array('QWERTY', 'PASS_TYPE_ALPHA'), + array('123456', 'PASS_TYPE_ALPHA'), + array('QwertY', 'PASS_TYPE_ALPHA'), + array('qwerty123', 'PASS_TYPE_ALPHA'), + array('QWERTY123', 'PASS_TYPE_ALPHA'), + array('#$&', 'PASS_TYPE_ALPHA'), + array('QTY123$', 'PASS_TYPE_ALPHA'), + + array('qwerty', 'PASS_TYPE_SYMBOL'), + array('QWERTY', 'PASS_TYPE_SYMBOL'), + array('123456', 'PASS_TYPE_SYMBOL'), + array('QwertY', 'PASS_TYPE_SYMBOL'), + array('qwerty123', 'PASS_TYPE_SYMBOL'), + array('QWERTY123', 'PASS_TYPE_SYMBOL'), + array('#$&', 'PASS_TYPE_SYMBOL'), + array('qwerty123$', 'PASS_TYPE_SYMBOL'), + array('QWERTY123$', 'PASS_TYPE_SYMBOL'), + ); + } + + /** + * @dataProvider password_complexity_test_data_positive + */ + public function test_password_complexity_positive($password, $mode) + { + global $config; + $config['pass_complex'] = $mode; + $this->assertFalse(validate_password($password)); + } + + /** + * @dataProvider password_complexity_test_data_negative + */ + public function test_password_complexity_negative($password, $mode) + { + global $config; + $config['pass_complex'] = $mode; + $this->assertEquals('INVALID_CHARS', validate_password($password)); + } +} diff --git a/tests/regex/url.php b/tests/regex/url_test.php index 678b7d108f..c3a336063a 100644 --- a/tests/regex/url.php +++ b/tests/regex/url_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; class phpbb_regex_url_test extends phpbb_test_case { diff --git a/tests/request/all_tests.php b/tests/request/all_tests.php deleted file mode 100644 index 1ee3029b36..0000000000 --- a/tests/request/all_tests.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2008 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_request_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'request/request_var.php'; - -class phpbb_request_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Request Parameter Handling'); - - $suite->addTestSuite('phpbb_request_request_var_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_request_all_tests::main') -{ - phpbb_request_all_tests::main(); -} - diff --git a/tests/request/request_var.php b/tests/request/request_var_test.php index b1dacef3fd..fa17b1909f 100644 --- a/tests/request/request_var.php +++ b/tests/request/request_var_test.php @@ -7,8 +7,8 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/utf/utf_tools.php'; class phpbb_request_request_var_test extends phpbb_test_case { diff --git a/tests/security/all_tests.php b/tests/security/base.php index 8e3916733f..db9c884cf4 100644 --- a/tests/security/all_tests.php +++ b/tests/security/base.php @@ -7,18 +7,7 @@ * */ -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_security_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'security/extract_current_page.php'; -require_once 'security/redirect.php'; - -class phpbb_security_all_tests extends PHPUnit_Framework_TestSuite +abstract class phpbb_security_test_base extends phpbb_test_case { /** * Set up the required user object and server variables for the suites @@ -62,25 +51,4 @@ class phpbb_security_all_tests extends PHPUnit_Framework_TestSuite global $user; $user = NULL; } - - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - // I bet there is a better method calling this... :) - $suite = new phpbb_security_all_tests('phpBB Security Fixes'); - - $suite->addTestSuite('phpbb_security_extract_current_page_test'); - $suite->addTestSuite('phpbb_security_redirect_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_security_all_tests::main') -{ - phpbb_security_all_tests::main(); } diff --git a/tests/security/extract_current_page.php b/tests/security/extract_current_page_test.php index 8c72fe1440..71c7a3a397 100644 --- a/tests/security/extract_current_page.php +++ b/tests/security/extract_current_page_test.php @@ -7,12 +7,12 @@ * */ -require_once 'test_framework/framework.php'; +require_once dirname(__FILE__) . '/base.php'; -require_once '../phpBB/includes/functions.php'; -require_once '../phpBB/includes/session.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/session.php'; -class phpbb_security_extract_current_page_test extends phpbb_test_case +class phpbb_security_extract_current_page_test extends phpbb_security_test_base { public static function security_variables() { diff --git a/tests/security/hash_test.php b/tests/security/hash_test.php new file mode 100644 index 0000000000..19a3822145 --- /dev/null +++ b/tests/security/hash_test.php @@ -0,0 +1,21 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; + +class phpbb_security_hash_test extends phpbb_test_case +{ + public function test_check_hash_with_phpass() + { + $this->assertTrue(phpbb_check_hash('test', '$H$9isfrtKXWqrz8PvztXlL3.daw4U0zI1')); + $this->assertTrue(phpbb_check_hash('test', '$P$9isfrtKXWqrz8PvztXlL3.daw4U0zI1')); + $this->assertFalse(phpbb_check_hash('foo', '$H$9isfrtKXWqrz8PvztXlL3.daw4U0zI1')); + } +} + diff --git a/tests/security/redirect.php b/tests/security/redirect_test.php index 37b0a5bb41..70ba8527b1 100644 --- a/tests/security/redirect.php +++ b/tests/security/redirect_test.php @@ -7,12 +7,12 @@ * */ -require_once 'test_framework/framework.php'; +require_once dirname(__FILE__) . '/base.php'; -require_once '../phpBB/includes/functions.php'; -require_once '../phpBB/includes/session.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/session.php'; -class phpbb_security_redirect_test extends phpbb_test_case +class phpbb_security_redirect_test extends phpbb_security_test_base { public static function provider() { @@ -22,13 +22,15 @@ class phpbb_security_redirect_test extends phpbb_test_case array('bad://localhost/phpBB/index.php', 'Tried to redirect to potentially insecure url.', false), array('http://www.otherdomain.com/somescript.php', false, 'http://localhost/phpBB'), array("http://localhost/phpBB/memberlist.php\n\rConnection: close", 'Tried to redirect to potentially insecure url.', false), - array('javascript:test', false, 'http://localhost/phpBB/../tests/javascript:test'), + array('javascript:test', false, 'http://localhost/phpBB/../javascript:test'), array('http://localhost/phpBB/index.php;url=', 'Tried to redirect to potentially insecure url.', false), ); } protected function setUp() { + parent::setUp(); + $GLOBALS['config'] = array( 'force_server_vars' => '0', ); diff --git a/tests/session/continue_test.php b/tests/session/continue_test.php new file mode 100644 index 0000000000..6737562a0a --- /dev/null +++ b/tests/session/continue_test.php @@ -0,0 +1,121 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../mock/cache.php'; +require_once dirname(__FILE__) . '/testable_factory.php'; + +class phpbb_session_continue_test extends phpbb_database_test_case +{ + public function getDataSet() + { + return $this->createXMLDataSet(dirname(__FILE__).'/fixtures/sessions_full.xml'); + } + + static public function session_begin_attempts() + { + // The session_id field is defined as CHAR(32) in the database schema. + // Thus the data we put in session_id fields has to have a length of 32 characters on stricter DBMSes. + // Thus we fill those strings up with zeroes until they have a string length of 32. + + return array( + array( + 'bar_session000000000000000000000', '4', 'user agent', '127.0.0.1', + array( + array('session_id' => 'anon_session00000000000000000000', 'session_user_id' => 1), + array('session_id' => 'bar_session000000000000000000000', 'session_user_id' => 4), + ), + array(), + 'If a request comes with a valid session id with matching user agent and IP, no new session should be created.', + ), + array( + 'anon_session00000000000000000000', '4', 'user agent', '127.0.0.1', + array( + array('session_id' => '__new_session_id__', 'session_user_id' => 1), // use generated SID + array('session_id' => 'bar_session000000000000000000000', 'session_user_id' => 4), + ), + array( + 'u' => array('1', null), + 'k' => array(null, null), + 'sid' => array('__new_session_id__', null), + ), + 'If a request comes with a valid session id and IP but different user id and user agent, a new anonymous session is created and the session matching the supplied session id is deleted.', + ), + ); + } + + /** + * @dataProvider session_begin_attempts + */ + public function test_session_begin_valid_session($session_id, $user_id, $user_agent, $ip, $expected_sessions, $expected_cookies, $message) + { + $db = $this->new_dbal(); + $session_factory = new phpbb_session_testable_factory; + $session_factory->set_cookies(array( + '_sid' => $session_id, + '_u' => $user_id, + )); + $session_factory->merge_config_data(array( + 'session_length' => time(), // need to do this to allow sessions started at time 0 + )); + $session_factory->merge_server_data(array( + 'HTTP_USER_AGENT' => $user_agent, + 'REMOTE_ADDR' => $ip, + )); + + $session = $session_factory->get_session($db); + $session->page = array('page' => 'page', 'forum' => 0); + + $session->session_begin(); + + $sql = 'SELECT session_id, session_user_id + FROM phpbb_sessions + ORDER BY session_user_id'; + + $expected_sessions = $this->replace_session($expected_sessions, $session->session_id); + $expected_cookies = $this->replace_session($expected_cookies, $session->session_id); + + $this->assertSqlResultEquals( + $expected_sessions, + $sql, + $message + ); + + $session->check_cookies($this, $expected_cookies); + + $session_factory->check($this); + } + + /** + * Replaces recursively the value __new_session_id__ with the given session + * id. + * + * @param array $array An array of data + * @param string $session_id The new session id to use instead of the + * placeholder. + * @return array The input array with all occurances of __new_session_id__ + * replaced. + */ + public function replace_session($array, $session_id) + { + foreach ($array as $key => &$value) + { + if ($value === '__new_session_id__') + { + $value = $session_id; + } + + if (is_array($value)) + { + $value = $this->replace_session($value, $session_id); + } + } + + return $array; + } +} diff --git a/tests/session/fixtures/sessions_empty.xml b/tests/session/fixtures/sessions_empty.xml new file mode 100644 index 0000000000..f94337314e --- /dev/null +++ b/tests/session/fixtures/sessions_empty.xml @@ -0,0 +1,25 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<dataset> + <table name="phpbb_users"> + <column>user_id</column> + <column>username_clean</column> + <row> + <value>1</value> + <value>anonymous</value> + </row> + <row> + <value>3</value> + <value>foo</value> + </row> + <row> + <value>4</value> + <value>bar</value> + </row> + </table> + <table name="phpbb_sessions"> + <column>session_id</column> + <column>session_user_id</column> + <column>session_ip</column> + <column>session_browser</column> + </table> +</dataset> diff --git a/tests/session/fixtures/sessions_full.xml b/tests/session/fixtures/sessions_full.xml new file mode 100644 index 0000000000..bf6fc65997 --- /dev/null +++ b/tests/session/fixtures/sessions_full.xml @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<dataset> + <table name="phpbb_users"> + <column>user_id</column> + <column>username_clean</column> + <row> + <value>1</value> + <value>anonymous</value> + </row> + <row> + <value>3</value> + <value>foo</value> + </row> + <row> + <value>4</value> + <value>bar</value> + </row> + </table> + <table name="phpbb_sessions"> + <column>session_id</column> + <column>session_user_id</column> + <column>session_ip</column> + <column>session_browser</column> + <row> + <value>anon_session00000000000000000000</value> + <value>1</value> + <value>127.0.0.1</value> + <value>anonymous user agent</value> + </row> + <row> + <value>bar_session000000000000000000000</value> + <value>4</value> + <value>127.0.0.1</value> + <value>user agent</value> + </row> + </table> +</dataset> diff --git a/tests/session/init_test.php b/tests/session/init_test.php new file mode 100644 index 0000000000..1181fab636 --- /dev/null +++ b/tests/session/init_test.php @@ -0,0 +1,56 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../mock/cache.php'; +require_once dirname(__FILE__) . '/testable_factory.php'; + +class phpbb_session_init_test extends phpbb_database_test_case +{ + public function getDataSet() + { + return $this->createXMLDataSet(dirname(__FILE__).'/fixtures/sessions_empty.xml'); + } + + // also see security/extract_current_page.php + + public function test_login_session_create() + { + $db = $this->new_dbal(); + $session_factory = new phpbb_session_testable_factory; + + $session = $session_factory->get_session($db); + $session->page = array('page' => 'page', 'forum' => 0); + + $session->session_create(3); + + $sql = 'SELECT session_user_id + FROM phpbb_sessions'; + + $this->assertSqlResultEquals( + array(array('session_user_id' => 3)), + $sql, + 'Check if exacly one session for user id 3 was created' + ); + + $cookie_expire = $session->time_now + 31536000; // default is one year + + $session->check_cookies($this, array( + 'u' => array(null, $cookie_expire), + 'k' => array(null, $cookie_expire), + 'sid' => array($session->session_id, $cookie_expire), + )); + + global $SID, $_SID; + $this->assertEquals($session->session_id, $_SID); + $this->assertEquals('?sid=' . $session->session_id, $SID); + + $session_factory->check($this); + } +} + diff --git a/tests/session/testable_factory.php b/tests/session/testable_factory.php new file mode 100644 index 0000000000..f3ef19a257 --- /dev/null +++ b/tests/session/testable_factory.php @@ -0,0 +1,171 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../mock/session_testable.php'; + +/** +* This class exists to setup an instance of phpbb's session class for testing. +* +* The session class has rather complex dependencies, so in order to make its +* tests more * understandable and to make its dependencies more visible this +* factory class sets up all the necessary global state & variable contents. +*/ +class phpbb_session_testable_factory +{ + protected $config_data; + protected $cache_data; + protected $cookies; + + protected $config; + protected $cache; + + /** + * Initialises the factory with a set of default config and cache values. + */ + public function __construct() + { + // default configuration values + $this->config_data = array( + 'allow_autologin' => false, + 'auth_method' => 'db', + 'forwarded_for_check' => true, + 'active_sessions' => 0, // disable + 'rand_seed' => 'foo', + 'rand_seed_last_update' => 0, + 'max_autologin_time' => 0, + 'session_length' => 100, + 'form_token_lifetime' => 100, + 'cookie_name' => '', + 'limit_load' => 0, + 'limit_search_load' => 0, + 'ip_check' => 3, + 'browser_check' => 1, + ); + + $this->cache_data = array( + '_bots' => array(), + ); + + $this->cookies = array(); + + $this->server_data = $_SERVER; + } + + /** + * Retrieve the configured session class instance + * + * @param dbal $dbal The database connection to use for session data + * @return phpbb_mock_session_testable A session instance + */ + public function get_session(dbal $dbal) + { + // set up all the global variables used by session + global $SID, $_SID, $db, $config, $cache; + + $config = $this->config = $this->get_config_data(); + $db = $dbal; + + $cache = $this->cache = new phpbb_mock_cache($this->get_cache_data()); + $SID = $_SID = null; + + $_COOKIE = $this->cookies; + $_SERVER = $this->server_data; + + $session = new phpbb_mock_session_testable; + return $session; + } + + /** + * Set the cookies which should be present in the request data. + * + * @param array $cookies The cookie data, structured like $_COOKIE contents. + */ + public function set_cookies(array $cookies) + { + $this->cookies = $cookies; + } + + /** + * Check if the cache used for the generated session contains correct data. + * + * @param PHPUnit_Framework_Assert $test The test case to call assert methods + * on + */ + public function check(PHPUnit_Framework_Assert $test) + { + $this->cache->check($test, $this->get_cache_data()); + } + + /** + * Merge config data with the current config data to be supplied to session. + * + * New values overwrite new ones. + * + * @param array $config_data The config data to merge with previous data + */ + public function merge_config_data(array $config_data) + { + $this->config_data = array_merge($this->config_data, $config_data); + } + + /** + * Retrieve the entire config data to be passed to the session. + * + * @return array Configuration + */ + public function get_config_data() + { + return $this->config_data; + } + + /** + * Merge the cache contents with more data. + * + * New values overwrite old ones. + * + * @param array $cache_data The additional cache data + */ + public function merge_cache_data(array $cache_data) + { + $this->cache_data = array_merge($this->cache_data, $cache_data); + } + + /** + * Retrieve the entire cache data to be passed to the session. + * + * @return array Cache contents + */ + public function get_cache_data() + { + return $this->cache_data; + } + + /** + * Merge the current server info ($_SERVER) with more data. + * + * New values overwrite old ones. + * + * @param array $server_data The additional server variables + */ + public function merge_server_data($server_data) + { + return $this->server_data = array_merge($this->server_data, $server_data); + } + + /** + * Retrieve all server variables to be passed to the session. + * + * @return array Server variables + */ + public function get_server_data() + { + return $this->server_data; + } +} + diff --git a/tests/template/all_tests.php b/tests/template/all_tests.php deleted file mode 100644 index ea258c1680..0000000000 --- a/tests/template/all_tests.php +++ /dev/null @@ -1,40 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2008 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_template_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'template/template.php'; - -class phpbb_template_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Template Engine'); - - $suite->addTestSuite('phpbb_template_template_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_template_all_tests::main') -{ - phpbb_template_all_tests::main(); -} diff --git a/tests/template/template.php b/tests/template/template_test.php index 0c2ca8a032..33c82d53ad 100644 --- a/tests/template/template.php +++ b/tests/template/template_test.php @@ -7,9 +7,8 @@ * */ -require_once 'test_framework/framework.php'; - -require_once '../phpBB/includes/template.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/template.php'; class phpbb_template_template_test extends phpbb_test_case { @@ -344,8 +343,7 @@ class phpbb_template_template_test extends phpbb_test_case */ public function test_template($file, array $vars, array $block_vars, array $destroy, $expected) { - global $phpEx; - $cache_file = $this->template->cachepath . str_replace('/', '.', $file) . '.' . $phpEx; + $cache_file = $this->template->cachepath . str_replace('/', '.', $file) . '.php'; $this->assertFileNotExists($cache_file); @@ -395,11 +393,9 @@ class phpbb_template_template_test extends phpbb_test_case public function test_php() { - global $phpEx; - $GLOBALS['config']['tpl_allow_php'] = true; - $cache_file = $this->template->cachepath . 'php.html.' . $phpEx; + $cache_file = $this->template->cachepath . 'php.html.php'; $this->assertFileNotExists($cache_file); @@ -410,21 +406,14 @@ class phpbb_template_template_test extends phpbb_test_case public function test_includephp() { - $this->markTestIncomplete('Include PHP test file paths are broken'); - $GLOBALS['config']['tpl_allow_php'] = true; - $cache_file = $this->template->cachepath . 'includephp.html.' . PHP_EXT; - - $cwd = getcwd(); - chdir(dirname(__FILE__) . '/templates'); + $cache_file = $this->template->cachepath . 'includephp.html.php'; $this->run_template('includephp.html', array(), array(), array(), 'testing included php', $cache_file); $this->template->set_filenames(array('test' => 'includephp.html')); - $this->assertEquals('testing included php', $this->display('test'), "Testing $file"); - - chdir($cwd); + $this->assertEquals('testing included php', $this->display('test'), "Testing INCLUDEPHP"); $GLOBALS['config']['tpl_allow_php'] = false; } @@ -438,17 +427,16 @@ class phpbb_template_template_test extends phpbb_test_case false, 'insert', <<<EOT -outer - 0/4 - before -outer - 1/4 -middle - 0/2 -middle - 1/2 -outer - 2/4 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 3/4 -middle - 0/2 -middle - 1/2 +outer - 0 - before +outer - 1 +middle - 0 +middle - 1 +outer - 2 +middle - 0 +middle - 1 +outer - 3 +middle - 0 +middle - 1 EOT , 'Test inserting before on top level block', @@ -459,17 +447,16 @@ EOT true, 'insert', <<<EOT -outer - 0/4 -middle - 0/2 -middle - 1/2 -outer - 1/4 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/4 -middle - 0/2 -middle - 1/2 -outer - 3/4 - after +outer - 0 +middle - 0 +middle - 1 +outer - 1 +middle - 0 +middle - 1 +outer - 2 +middle - 0 +middle - 1 +outer - 3 - after EOT , 'Test inserting after on top level block', @@ -480,17 +467,16 @@ EOT 1, 'insert', <<<EOT -outer - 0/4 -middle - 0/2 -middle - 1/2 -outer - 1/4 - pos #1 -outer - 2/4 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 3/4 -middle - 0/2 -middle - 1/2 +outer - 0 +middle - 0 +middle - 1 +outer - 1 - pos #1 +outer - 2 +middle - 0 +middle - 1 +outer - 3 +middle - 0 +middle - 1 EOT , 'Test inserting at 1 on top level block', @@ -501,172 +487,27 @@ EOT 0, 'change', <<<EOT -outer - 0/3 - pos #1 -middle - 0/2 -middle - 1/2 -outer - 1/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/3 -middle - 0/2 -middle - 1/2 +outer - 0 - pos #1 +middle - 0 +middle - 1 +outer - 1 +middle - 0 +middle - 1 +outer - 2 +middle - 0 +middle - 1 EOT , 'Test inserting at 1 on top level block', ), - array( - 'outer[0].middle', - array('VARIABLE' => 'before'), - false, - 'insert', - <<<EOT -outer - 0/3 -middle - 0/3 - before -middle - 1/3 -middle - 2/3 -outer - 1/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/3 -middle - 0/2 -middle - 1/2 -EOT -, - 'Test inserting before on nested block', - ), - array( - 'outer[0].middle', - array('VARIABLE' => 'after'), - true, - 'insert', - <<<EOT -outer - 0/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 - after -outer - 1/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/3 -middle - 0/2 -middle - 1/2 -EOT -, - 'Test inserting after on nested block', - ), - array( - 'outer[0].middle', - array('VARIABLE' => 'pos #1'), - 1, - 'insert', - <<<EOT -outer - 0/3 -middle - 0/3 -middle - 1/3 - pos #1 -middle - 2/3 -outer - 1/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/3 -middle - 0/2 -middle - 1/2 -EOT -, - 'Test inserting at pos 1 on nested block', - ), - array( - 'outer[1].middle', - array('VARIABLE' => 'before'), - false, - 'insert', - <<<EOT -outer - 0/3 -middle - 0/2 -middle - 1/2 -outer - 1/3 -middle - 0/4 - before -middle - 1/4 -middle - 2/4 -middle - 3/4 -outer - 2/3 -middle - 0/2 -middle - 1/2 -EOT -, - 'Test inserting before on nested block (pos 1)', - ), - array( - 'outer[].middle', - array('VARIABLE' => 'before'), - false, - 'insert', - <<<EOT -outer - 0/3 -middle - 0/2 -middle - 1/2 -outer - 1/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/3 -middle - 0/3 - before -middle - 1/3 -middle - 2/3 -EOT -, - 'Test inserting before on nested block (end)', - ), - array( - 'outer.middle', - array('VARIABLE' => 'before'), - false, - 'insert', - <<<EOT -outer - 0/3 -middle - 0/2 -middle - 1/2 -outer - 1/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/3 -middle - 0/3 - before -middle - 1/3 -middle - 2/3 -EOT -, - 'Test inserting before on nested block (end)', - ), ); } -/* - <<<EOT -outer - 0/3 -middle - 0/2 -middle - 1/2 -outer - 1/3 -middle - 0/3 -middle - 1/3 -middle - 2/3 -outer - 2/3 -middle - 0/2 -middle - 1/2 -EOT -, -*/ - /** * @dataProvider alter_block_array_data */ public function test_alter_block_array($alter_block, array $vararray, $key, $mode, $expect, $description) { - $this->markTestIncomplete('Alter Block Test is broken'); - $this->template->set_filenames(array('test' => 'loop_nested.html')); // @todo Change this @@ -676,12 +517,11 @@ EOT $this->template->assign_block_vars('outer', array()); $this->template->assign_block_vars('outer.middle', array()); $this->template->assign_block_vars('outer.middle', array()); - $this->template->assign_block_vars('outer.middle', array()); $this->template->assign_block_vars('outer', array()); $this->template->assign_block_vars('outer.middle', array()); $this->template->assign_block_vars('outer.middle', array()); - $this->assertEquals("outer - 0/3\nmiddle - 0/2\nmiddle - 1/2\nouter - 1/3\nmiddle - 0/3\nmiddle - 1/3\nmiddle - 2/3\nouter - 2/3\nmiddle - 0/2\nmiddle - 1/2", $this->display('test'), 'Ensuring template is built correctly before modification'); + $this->assertEquals("outer - 0\nmiddle - 0\nmiddle - 1\nouter - 1\nmiddle - 0\nmiddle - 1\nouter - 2\nmiddle - 0\nmiddle - 1", $this->display('test'), 'Ensuring template is built correctly before modification'); $this->template->alter_block_array($alter_block, $vararray, $key, $mode); $this->assertEquals($expect, $this->display('test'), $description); diff --git a/tests/template/templates/_dummy_include.php b/tests/template/templates/_dummy_include.php deleted file mode 100644 index 1de5dddf59..0000000000 --- a/tests/template/templates/_dummy_include.php +++ /dev/null @@ -1,3 +0,0 @@ -<?php - -echo "testing included php"; diff --git a/tests/template/templates/_dummy_include.php.inc b/tests/template/templates/_dummy_include.php.inc new file mode 100644 index 0000000000..aacb6b2045 --- /dev/null +++ b/tests/template/templates/_dummy_include.php.inc @@ -0,0 +1,3 @@ +<?php +// extension is .php.inc so PHPUnit ignores it +echo "testing included php"; diff --git a/tests/template/templates/includephp.html b/tests/template/templates/includephp.html index 3e13fa33fa..70ebdac0d0 100644 --- a/tests/template/templates/includephp.html +++ b/tests/template/templates/includephp.html @@ -1 +1 @@ -<!-- INCLUDEPHP ../templates/_dummy_include.php --> +<!-- INCLUDEPHP ../tests/template/templates/_dummy_include.php.inc --> diff --git a/tests/template/templates/loop_nested.html b/tests/template/templates/loop_nested.html index 571df97b4c..9b251cd453 100644 --- a/tests/template/templates/loop_nested.html +++ b/tests/template/templates/loop_nested.html @@ -1,8 +1,8 @@ <!-- BEGIN outer --> - {outer.S_BLOCK_NAME} - {outer.S_ROW_NUM}/{outer.S_NUM_ROWS}<!-- IF outer.VARIABLE --> - {outer.VARIABLE}<!-- ENDIF --> + outer - {outer.S_ROW_COUNT}<!-- IF outer.VARIABLE --> - {outer.VARIABLE}<!-- ENDIF --> <!-- BEGIN middle --> - {middle.S_BLOCK_NAME} - {middle.S_ROW_NUM}/{middle.S_NUM_ROWS}<!-- IF middle.VARIABLE --> - {middle.VARIABLE}<!-- ENDIF --> + middle - {middle.S_ROW_COUNT}<!-- IF middle.VARIABLE --> - {middle.VARIABLE}<!-- ENDIF --> <!-- END middle --> <!-- END outer --> diff --git a/tests/test_framework/phpbb_database_test_case.php b/tests/test_framework/phpbb_database_test_case.php index a64bae8c57..e1b368dcea 100644 --- a/tests/test_framework/phpbb_database_test_case.php +++ b/tests/test_framework/phpbb_database_test_case.php @@ -9,10 +9,25 @@ abstract class phpbb_database_test_case extends PHPUnit_Extensions_Database_TestCase { - private static $already_connected; + static private $already_connected; protected $test_case_helpers; + public function __construct($name = NULL, array $data = array(), $dataName = '') + { + parent::__construct($name, $data, $dataName); + $this->backupStaticAttributesBlacklist += array( + 'PHP_CodeCoverage' => array('instance'), + 'PHP_CodeCoverage_Filter' => array('instance'), + 'PHP_CodeCoverage_Util' => array('ignoredLines', 'templateMethods'), + 'PHP_Timer' => array('startTimes',), + 'PHP_Token_Stream' => array('customTokens'), + 'PHP_Token_Stream_CachingFactory' => array('cache'), + + 'phpbb_database_test_case' => array('already_connected'), + ); + } + public function get_test_case_helpers() { if (!$this->test_case_helpers) @@ -23,66 +38,6 @@ abstract class phpbb_database_test_case extends PHPUnit_Extensions_Database_Test return $this->test_case_helpers; } - public function get_dbms_data($dbms) - { - $available_dbms = array( - 'firebird' => array( - 'SCHEMA' => 'firebird', - 'DELIM' => ';;', - 'PDO' => 'firebird', - ), - 'mysqli' => array( - 'SCHEMA' => 'mysql_41', - 'DELIM' => ';', - 'PDO' => 'mysql', - ), - 'mysql' => array( - 'SCHEMA' => 'mysql', - 'DELIM' => ';', - 'PDO' => 'mysql', - ), - 'mssql' => array( - 'SCHEMA' => 'mssql', - 'DELIM' => 'GO', - 'PDO' => 'odbc', - ), - 'mssql_odbc'=> array( - 'SCHEMA' => 'mssql', - 'DELIM' => 'GO', - 'PDO' => 'odbc', - ), - 'mssqlnative' => array( - 'SCHEMA' => 'mssql', - 'DELIM' => 'GO', - 'PDO' => 'sqlsrv', - ), - 'oracle' => array( - 'SCHEMA' => 'oracle', - 'DELIM' => '/', - 'PDO' => 'oci', - ), - 'postgres' => array( - 'SCHEMA' => 'postgres', - 'DELIM' => ';', - 'PDO' => 'pgsql', - ), - 'sqlite' => array( - 'SCHEMA' => 'sqlite', - 'DELIM' => ';', - 'PDO' => 'sqlite2', - ), - ); - - if (isset($available_dbms[$dbms])) - { - return $available_dbms[$dbms]; - } - else - { - trigger_error('Database unsupported', E_USER_ERROR); - } - } - public function get_database_config() { if (isset($_SERVER['PHPBB_TEST_DBMS'])) @@ -96,9 +51,9 @@ abstract class phpbb_database_test_case extends PHPUnit_Extensions_Database_Test 'dbpasswd' => isset($_SERVER['PHPBB_TEST_DBPASSWD']) ? $_SERVER['PHPBB_TEST_DBPASSWD'] : '', ); } - else if (file_exists('test_config.php')) + else if (file_exists(dirname(__FILE__) . '/../test_config.php')) { - include('test_config.php'); + include(dirname(__FILE__) . '/../test_config.php'); return array( 'dbms' => $dbms, @@ -114,7 +69,7 @@ abstract class phpbb_database_test_case extends PHPUnit_Extensions_Database_Test // Silently use sqlite return array( 'dbms' => 'sqlite', - 'dbhost' => 'phpbb_unit_tests.sqlite2', // filename + 'dbhost' => dirname(__FILE__) . '/../phpbb_unit_tests.sqlite2', // filename 'dbport' => '', 'dbname' => '', 'dbuser' => '', @@ -127,232 +82,26 @@ abstract class phpbb_database_test_case extends PHPUnit_Extensions_Database_Test } } - // NOTE: This function is not the same as split_sql_file from functions_install - public function split_sql_file($sql, $dbms) - { - $dbms_data = $this->get_dbms_data($dbms); - - $sql = str_replace("\r" , '', $sql); - $data = preg_split('/' . preg_quote($dbms_data['DELIM'], '/') . '$/m', $sql); - - $data = array_map('trim', $data); - - // The empty case - $end_data = end($data); - - if (empty($end_data)) - { - unset($data[key($data)]); - } - - if ($dbms == 'sqlite') - { - // remove comment lines starting with # - they are not proper sqlite - // syntax and break sqlite2 - foreach ($data as $i => $query) - { - $data[$i] = preg_replace('/^#.*$/m', "\n", $query); - } - } - - return $data; - } - - /** - * Retrieves a list of all tables from the database. - * - * @param PDO $pdo - * @param string $dbms - * @return array(string) - */ - function get_tables($pdo, $dbms) - { - switch ($pdo) - { - case 'mysql': - case 'mysql4': - case 'mysqli': - $sql = 'SHOW TABLES'; - break; - - case 'sqlite': - $sql = 'SELECT name - FROM sqlite_master - WHERE type = "table"'; - break; - - case 'mssql': - case 'mssql_odbc': - case 'mssqlnative': - $sql = "SELECT name - FROM sysobjects - WHERE type='U'"; - break; - - case 'postgres': - $sql = 'SELECT relname - FROM pg_stat_user_tables'; - break; - - case 'firebird': - $sql = 'SELECT rdb$relation_name - FROM rdb$relations - WHERE rdb$view_source is null - AND rdb$system_flag = 0'; - break; - - case 'oracle': - $sql = 'SELECT table_name - FROM USER_TABLES'; - break; - } - - $result = $pdo->query($sql); - - $tables = array(); - while ($row = $result->fetch(PDO::FETCH_NUM)) - { - $tables[] = current($row); - } - - return $tables; - } - - /** - * Returns a PDO connection for the configured database. - * - * @param array $config The database configuration - * @param array $dbms Information on the used DBMS. - * @param bool $use_db Whether the DSN should be tied to a - * particular database making it impossible - * to delete that database. - * @return PDO The PDO database connection. - */ - public function new_pdo($config, $dbms, $use_db) - { - $dsn = $dbms['PDO'] . ':'; - - switch ($dbms['PDO']) - { - case 'sqlite2': - $dsn .= $config['dbhost']; - break; - - case 'sqlsrv': - // prefix the hostname (or DSN) with Server= so using just (local)\SQLExpress - // works for example, further parameters can still be appended using ;x=y - $dsn .= 'Server='; - // no break -> rest like ODBC - case 'odbc': - // for ODBC assume dbhost is a suitable DSN - // e.g. Driver={SQL Server Native Client 10.0};Server=(local)\SQLExpress; - $dsn .= $config['dbhost']; - - if ($use_db) - { - $dsn .= ';Database=' . $config['dbname']; - } - break; - - default: - $dsn .= 'host=' . $config['dbhost']; - - if ($use_db) - { - $dsn .= ';dbname=' . $config['dbname']; - } - break; - } - - $pdo = new PDO($dsn, $config['dbuser'], $config['dbpasswd']);; - - // good for debug - // $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - - return $pdo; - } - - private function recreate_db($config, $dbms) - { - switch ($config['dbms']) - { - case 'sqlite': - if (file_exists($config['dbhost'])) - { - unlink($config['dbhost']); - } - break; - - default: - $pdo = $this->new_pdo($config, $dbms, false); - - try - { - $pdo->exec('DROP DATABASE ' . $config['dbname']); - } - catch (PDOException $e) - { - // try to delete all tables if dropping the database was not possible. - foreach ($this->get_tables() as $table) - { - try - { - $pdo->exec('DROP TABLE ' . $table); - } - catch (PDOException $e){} // ignore non-existent tables - } - } - - $pdo->exec('CREATE DATABASE ' . $config['dbname']); - break; - } - } - - private function load_schema($pdo, $config, $dbms) - { - if ($config['dbms'] == 'mysql') - { - $sth = $pdo->query('SELECT VERSION() AS version'); - $row = $sth->fetch(PDO::FETCH_ASSOC); - - if (version_compare($row['version'], '4.1.3', '>=')) - { - $dbms['SCHEMA'] .= '_41'; - } - else - { - $dbms['SCHEMA'] .= '_40'; - } - } - - $sql = $this->split_sql_file(file_get_contents("../phpBB/install/schemas/{$dbms['SCHEMA']}_schema.sql"), $config['dbms']); - - foreach ($sql as $query) - { - $pdo->exec($query); - } - } - public function getConnection() { $config = $this->get_database_config(); - $dbms = $this->get_dbms_data($config['dbms']); + + $manager = $this->create_connection_manager($config); if (!self::$already_connected) { - $this->recreate_db($config, $dbms); + $manager->recreate_db(); } - $pdo = $this->new_pdo($config, $dbms, true); + $manager->connect(); if (!self::$already_connected) { - $this->load_schema($pdo, $config, $dbms); - + $manager->load_schema(); self::$already_connected = true; } - return $this->createDefaultDBConnection($pdo, 'testdb'); + return $this->createDefaultDBConnection($manager->get_pdo(), 'testdb'); } public function new_dbal() @@ -361,7 +110,7 @@ abstract class phpbb_database_test_case extends PHPUnit_Extensions_Database_Test $config = $this->get_database_config(); - require_once '../phpBB/includes/db/' . $config['dbms'] . '.php'; + require_once dirname(__FILE__) . '/../../phpBB/includes/db/' . $config['dbms'] . '.php'; $dbal = 'dbal_' . $config['dbms']; $db = new $dbal(); $db->sql_connect($config['dbhost'], $config['dbuser'], $config['dbpasswd'], $config['dbname'], $config['dbport']); @@ -369,8 +118,24 @@ abstract class phpbb_database_test_case extends PHPUnit_Extensions_Database_Test return $db; } + public function assertSqlResultEquals($expected, $sql, $message = '') + { + $db = $this->new_dbal(); + + $result = $db->sql_query($sql); + $rows = $db->sql_fetchrowset($result); + $db->sql_freeresult($result); + + $this->assertEquals($expected, $rows, $message); + } + public function setExpectedTriggerError($errno, $message = '') { $this->get_test_case_helpers()->setExpectedTriggerError($errno, $message); } + + protected function create_connection_manager($config) + { + return new phpbb_database_test_connection_manager($config); + } } diff --git a/tests/test_framework/phpbb_database_test_connection_manager.php b/tests/test_framework/phpbb_database_test_connection_manager.php new file mode 100644 index 0000000000..a7559e2183 --- /dev/null +++ b/tests/test_framework/phpbb_database_test_connection_manager.php @@ -0,0 +1,346 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +class phpbb_database_test_connection_manager +{ + private $config; + private $dbms; + private $pdo; + + /** + * Constructor + * + * @param array $config Tests database configuration as returned by + * phpbb_database_test_case::get_database_config() + */ + public function __construct($config) + { + $this->config = $config; + $this->dbms = $this->get_dbms_data($this->config['dbms']); + } + + /** + * Return the current PDO instance + */ + public function get_pdo() + { + return $this->pdo; + } + + /** + * Creates a PDO connection for the configured database. + * + * @param bool $use_db Whether the DSN should be tied to a + * particular database making it impossible + * to delete that database. + */ + public function connect($use_db = true) + { + $dsn = $this->dbms['PDO'] . ':'; + + switch ($this->dbms['PDO']) + { + case 'sqlite2': + $dsn .= $this->config['dbhost']; + break; + + case 'sqlsrv': + // prefix the hostname (or DSN) with Server= so using just (local)\SQLExpress + // works for example, further parameters can still be appended using ;x=y + $dsn .= 'Server='; + // no break -> rest like ODBC + case 'odbc': + // for ODBC assume dbhost is a suitable DSN + // e.g. Driver={SQL Server Native Client 10.0};Server=(local)\SQLExpress; + $dsn .= $this->config['dbhost']; + + if ($use_db) + { + $dsn .= ';Database=' . $this->config['dbname']; + } + break; + + default: + $dsn .= 'host=' . $this->config['dbhost']; + + if ($use_db) + { + $dsn .= ';dbname=' . $this->config['dbname']; + } + break; + } + + try + { + $this->pdo = new PDO($dsn, $this->config['dbuser'], $this->config['dbpasswd']); + } + catch (PDOException $e) + { + $cleaned_dsn = str_replace($this->config['dbpasswd'], '*password*', $dsn); + throw new Exception("Unable do connect to $cleaned_dsn using PDO with error: {$e->getMessage()}"); + } + + // good for debug + // $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + } + + /** + * Load the phpBB database schema into the database + */ + public function load_schema() + { + $this->ensure_connected(__METHOD__); + + $directory = dirname(__FILE__) . '/../../phpBB/install/schemas/'; + $this->load_schema_from_file($directory); + } + + /** + * Drop the database if it exists and re-create it + * + * Note: This does not load the schema, and it is suggested + * to re-connect after calling to get use_db isolation. + */ + public function recreate_db() + { + switch ($this->config['dbms']) + { + case 'sqlite': + if (file_exists($this->config['dbhost'])) + { + unlink($this->config['dbhost']); + } + break; + + default: + $this->connect(false); + + try + { + $this->pdo->exec('DROP DATABASE ' . $this->config['dbname']); + } + catch (PDOException $e) + { + // try to delete all tables if dropping the database was not possible. + foreach ($this->get_tables() as $table) + { + $this->pdo->exec('DROP TABLE ' . $table); + } + } + + $this->pdo->exec('CREATE DATABASE ' . $this->config['dbname']); + break; + } + } + + /** + * Retrieves a list of all tables from the database. + * + * @return array(string) + */ + public function get_tables() + { + $this->ensure_connected(__METHOD__); + + switch ($this->config['dbms']) + { + case 'mysql': + case 'mysql4': + case 'mysqli': + $sql = 'SHOW TABLES'; + break; + + case 'sqlite': + $sql = 'SELECT name + FROM sqlite_master + WHERE type = "table"'; + break; + + case 'mssql': + case 'mssql_odbc': + case 'mssqlnative': + $sql = "SELECT name + FROM sysobjects + WHERE type='U'"; + break; + + case 'postgres': + $sql = 'SELECT relname + FROM pg_stat_user_tables'; + break; + + case 'firebird': + $sql = 'SELECT rdb$relation_name + FROM rdb$relations + WHERE rdb$view_source is null + AND rdb$system_flag = 0'; + break; + + case 'oracle': + $sql = 'SELECT table_name + FROM USER_TABLES'; + break; + } + + $result = $this->pdo->query($sql); + + $tables = array(); + while ($row = $result->fetch(PDO::FETCH_NUM)) + { + $tables[] = current($row); + } + + return $tables; + } + + /** + * Throw an exception if not connected + */ + protected function ensure_connected($method_name) + { + if (null === $this->pdo) + { + throw new Exception(sprintf('You must connect before calling %s', $method_name)); + } + } + + /** + * Compile the correct schema filename (as per create_schema_files) and + * load it into the database. + */ + protected function load_schema_from_file($directory) + { + $schema = $this->dbms['SCHEMA']; + + if ($this->config['dbms'] == 'mysql') + { + $sth = $this->pdo->query('SELECT VERSION() AS version'); + $row = $sth->fetch(PDO::FETCH_ASSOC); + + if (version_compare($row['version'], '4.1.3', '>=')) + { + $schema .= '_41'; + } + else + { + $schema .= '_40'; + } + } + + $filename = $directory . $schema . '_schema.sql'; + $sql = $this->split_sql(file_get_contents($filename)); + + foreach ($sql as $query) + { + $this->pdo->exec($query); + } + } + + /** + * Split contents of an SQL file into an array of SQL statements + * + * Note: This method is not the same as split_sql_file from functions_install. + * + * @param string $sql Raw contents of an SQL file + * + * @return Array of runnable SQL statements + */ + protected function split_sql($sql) + { + $sql = str_replace("\r" , '', $sql); + $data = preg_split('/' . preg_quote($this->dbms['DELIM'], '/') . '$/m', $sql); + + $data = array_map('trim', $data); + + // The empty case + $end_data = end($data); + + if (empty($end_data)) + { + unset($data[key($data)]); + } + + if ($this->config['dbms'] == 'sqlite') + { + // remove comment lines starting with # - they are not proper sqlite + // syntax and break sqlite2 + foreach ($data as $i => $query) + { + $data[$i] = preg_replace('/^#.*$/m', "\n", $query); + } + } + + return $data; + } + + /** + * Map a phpBB dbms driver name to dbms data array + */ + protected function get_dbms_data($dbms) + { + $available_dbms = array( + 'firebird' => array( + 'SCHEMA' => 'firebird', + 'DELIM' => ';;', + 'PDO' => 'firebird', + ), + 'mysqli' => array( + 'SCHEMA' => 'mysql_41', + 'DELIM' => ';', + 'PDO' => 'mysql', + ), + 'mysql' => array( + 'SCHEMA' => 'mysql', + 'DELIM' => ';', + 'PDO' => 'mysql', + ), + 'mssql' => array( + 'SCHEMA' => 'mssql', + 'DELIM' => 'GO', + 'PDO' => 'odbc', + ), + 'mssql_odbc'=> array( + 'SCHEMA' => 'mssql', + 'DELIM' => 'GO', + 'PDO' => 'odbc', + ), + 'mssqlnative' => array( + 'SCHEMA' => 'mssql', + 'DELIM' => 'GO', + 'PDO' => 'sqlsrv', + ), + 'oracle' => array( + 'SCHEMA' => 'oracle', + 'DELIM' => '/', + 'PDO' => 'oci', + ), + 'postgres' => array( + 'SCHEMA' => 'postgres', + 'DELIM' => ';', + 'PDO' => 'pgsql', + ), + 'sqlite' => array( + 'SCHEMA' => 'sqlite', + 'DELIM' => ';', + 'PDO' => 'sqlite2', + ), + ); + + if (isset($available_dbms[$dbms])) + { + return $available_dbms[$dbms]; + } + else + { + $message = "Supplied dbms \"$dbms\" is not a valid phpBB dbms, must be one of: "; + $message .= implode(', ', array_keys($available_dbms)); + throw new Exception($message); + } + } +} diff --git a/tests/test_framework/phpbb_test_case.php b/tests/test_framework/phpbb_test_case.php index fe90d321dc..f189da3671 100644 --- a/tests/test_framework/phpbb_test_case.php +++ b/tests/test_framework/phpbb_test_case.php @@ -11,6 +11,21 @@ class phpbb_test_case extends PHPUnit_Framework_TestCase { protected $test_case_helpers; + public function __construct($name = NULL, array $data = array(), $dataName = '') + { + parent::__construct($name, $data, $dataName); + $this->backupStaticAttributesBlacklist += array( + 'PHP_CodeCoverage' => array('instance'), + 'PHP_CodeCoverage_Filter' => array('instance'), + 'PHP_CodeCoverage_Util' => array('ignoredLines', 'templateMethods'), + 'PHP_Timer' => array('startTimes',), + 'PHP_Token_Stream' => array('customTokens'), + 'PHP_Token_Stream_CachingFactory' => array('cache'), + + 'phpbb_database_test_case' => array('already_connected'), + ); + } + public function get_test_case_helpers() { if (!$this->test_case_helpers) diff --git a/tests/text_processing/all_tests.php b/tests/text_processing/all_tests.php deleted file mode 100644 index 5e759c72ee..0000000000 --- a/tests/text_processing/all_tests.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2008 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_text_processing_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'text_processing/make_clickable.php'; - -class phpbb_text_processing_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Text Processing Tools'); - - $suite->addTestSuite('phpbb_text_processing_make_clickable_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_text_processing_all_tests::main') -{ - phpbb_text_processing_all_tests::main(); -} - diff --git a/tests/text_processing/make_clickable.php b/tests/text_processing/make_clickable_test.php index a667dd705e..29b982d709 100644 --- a/tests/text_processing/make_clickable.php +++ b/tests/text_processing/make_clickable_test.php @@ -7,10 +7,8 @@ * */ -require_once 'test_framework/framework.php'; - -require_once '../phpBB/includes/functions.php'; -require_once '../phpBB/includes/functions_content.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/functions_content.php'; class phpbb_text_processing_make_clickable_test extends phpbb_test_case { diff --git a/tests/user/lang_test.php b/tests/user/lang_test.php new file mode 100644 index 0000000000..6c60583a7b --- /dev/null +++ b/tests/user/lang_test.php @@ -0,0 +1,58 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/session.php'; + +class phpbb_user_lang_test extends phpbb_test_case +{ + public function test_user_lang_sprintf() + { + $user = new user; + $user->lang = array( + 'FOO' => 'BAR', + 'BARZ' => 'PENG', + 'EMPTY' => '', + 'ZERO' => '0', + 'STR' => '%d %s, %d topics', + 'STR2' => '%d foos', + 'ARRY' => array( + 0 => 'No posts', // 0 + 1 => '1 post', // 1 + 2 => '%d posts', // 2+ + ), + ); + + // No param + $this->assertEquals($user->lang('FOO'), 'BAR'); + $this->assertEquals($user->lang('EMPTY'), ''); + $this->assertEquals($user->lang('ZERO'), '0'); + + // Invalid index + $this->assertEquals($user->lang('VOID'), 'VOID'); + + // Unnecessary param + $this->assertEquals($user->lang('FOO', 2), 'BAR'); + $this->assertEquals($user->lang('FOO', 2, 3), 'BAR'); + $this->assertEquals($user->lang('FOO', 2, 3, 'BARZ'), 'BAR'); + + // String + $this->assertEquals($user->lang('STR', 24, 'x', 42), '24 x, 42 topics'); + $this->assertEquals($user->lang('STR2', 64), '64 foos'); + + // Array + $this->assertEquals($user->lang('ARRY', 0), 'No posts'); + $this->assertEquals($user->lang('ARRY', 1), '1 post'); + $this->assertEquals($user->lang('ARRY', 2), '2 posts'); + $this->assertEquals($user->lang('ARRY', 123), '123 posts'); + + // Bug PHPBB3-9949 + $this->assertEquals($user->lang('ARRY', 1, 2), '1 post'); + $this->assertEquals($user->lang('ARRY', 1, 's', 2), '1 post'); + } +} diff --git a/tests/utf/all_tests.php b/tests/utf/all_tests.php deleted file mode 100644 index 0d5d44d695..0000000000 --- a/tests/utf/all_tests.php +++ /dev/null @@ -1,43 +0,0 @@ -<?php -/** -* -* @package testing -* @copyright (c) 2008 phpBB Group -* @license http://opensource.org/licenses/gpl-license.php GNU Public License -* -*/ - -if (!defined('PHPUnit_MAIN_METHOD')) -{ - define('PHPUnit_MAIN_METHOD', 'phpbb_utf_all_tests::main'); -} - -require_once 'test_framework/framework.php'; -require_once 'PHPUnit/TextUI/TestRunner.php'; - -require_once 'utf/utf8_wordwrap_test.php'; -require_once 'utf/utf8_clean_string_test.php'; - -class phpbb_utf_all_tests -{ - public static function main() - { - PHPUnit_TextUI_TestRunner::run(self::suite()); - } - - public static function suite() - { - $suite = new PHPUnit_Framework_TestSuite('phpBB Unicode Transformation Format'); - - $suite->addTestSuite('phpbb_utf_utf8_wordwrap_test'); - $suite->addTestSuite('phpbb_utf_utf8_clean_string_test'); - - return $suite; - } -} - -if (PHPUnit_MAIN_METHOD == 'phpbb_utf_all_tests::main') -{ - phpbb_utf_all_tests::main(); -} - diff --git a/tests/utf/data/.gitkeep b/tests/utf/data/.gitkeep new file mode 100644 index 0000000000..e69de29bb2 --- /dev/null +++ b/tests/utf/data/.gitkeep diff --git a/tests/utf/normalizer_test.php b/tests/utf/normalizer_test.php new file mode 100644 index 0000000000..f78dba8004 --- /dev/null +++ b/tests/utf/normalizer_test.php @@ -0,0 +1,320 @@ +<?php +/** +* +* @package testing +* @copyright (c) 2011 phpBB Group +* @license http://opensource.org/licenses/gpl-license.php GNU Public License +* +*/ + +require_once dirname(__FILE__) . '/../../phpBB/includes/utf/utf_normalizer.php'; + +/** +* @group slow +*/ +class phpbb_utf_normalizer_test extends phpbb_test_case +{ + static public function setUpBeforeClass() + { + self::download('http://www.unicode.org/Public/UNIDATA/NormalizationTest.txt', dirname(__FILE__).'/data'); + self::download('http://www.unicode.org/Public/UNIDATA/UnicodeData.txt', dirname(__FILE__).'/data'); + } + + public function test_normalizer() + { + $test_suite = array( + /** + * NFC + * c2 == NFC(c1) == NFC(c2) == NFC(c3) + * c4 == NFC(c4) == NFC(c5) + */ + 'NFC' => array( + 'c2' => array('c1', 'c2', 'c3'), + 'c4' => array('c4', 'c5') + ), + + /** + * NFD + * c3 == NFD(c1) == NFD(c2) == NFD(c3) + * c5 == NFD(c4) == NFD(c5) + */ + 'NFD' => array( + 'c3' => array('c1', 'c2', 'c3'), + 'c5' => array('c4', 'c5') + ), + + /** + * NFKC + * c4 == NFKC(c1) == NFKC(c2) == NFKC(c3) == NFKC(c4) == NFKC(c5) + */ + 'NFKC' => array( + 'c4' => array('c1', 'c2', 'c3', 'c4', 'c5') + ), + + /** + * NFKD + * c5 == NFKD(c1) == NFKD(c2) == NFKD(c3) == NFKD(c4) == NFKD(c5) + */ + 'NFKD' => array( + 'c5' => array('c1', 'c2', 'c3', 'c4', 'c5') + ) + ); + + $tested_chars = array(); + + $fp = fopen(dirname(__FILE__).'/data/NormalizationTest.txt', 'rb'); + while (!feof($fp)) + { + $line = fgets($fp); + + if ($line[0] == '@') + { + continue; + } + + if (!strpos(' 0123456789ABCDEF', $line[0])) + { + continue; + } + + list($c1, $c2, $c3, $c4, $c5) = explode(';', $line); + + if (!strpos($c1, ' ')) + { + /** + * We are currently testing a single character, we add it to the list of + * characters we have processed so that we can exclude it when testing + * for invariants + */ + $tested_chars[$c1] = 1; + } + + foreach ($test_suite as $form => $serie) + { + foreach ($serie as $expected => $tests) + { + $hex_expected = ${$expected}; + $utf_expected = $this->hexseq_to_utf($hex_expected); + + foreach ($tests as $test) + { + $utf_result = $utf_expected; + call_user_func(array('utf_normalizer', $form), &$utf_result); + + $hex_result = $this->utf_to_hexseq($utf_result); + $this->assertEquals($utf_expected, $utf_result, "$expected == $form($test) ($hex_expected != $hex_result)"); + } + } + } + } + fclose($fp); + + return $tested_chars; + } + + /** + * @depends test_normalizer + */ + public function test_invariants(array $tested_chars) + { + $fp = fopen(dirname(__FILE__).'/data/UnicodeData.txt', 'rb'); + + while (!feof($fp)) + { + $line = fgets($fp, 1024); + + if (!$pos = strpos($line, ';')) + { + continue; + } + + $hex_tested = $hex_expected = substr($line, 0, $pos); + + if (isset($tested_chars[$hex_tested])) + { + continue; + } + + $utf_expected = $this->hex_to_utf($hex_expected); + + if ($utf_expected >= UTF8_SURROGATE_FIRST + && $utf_expected <= UTF8_SURROGATE_LAST) + { + /** + * Surrogates are illegal on their own, we expect the normalizer + * to return a replacement char + */ + $utf_expected = UTF8_REPLACEMENT; + $hex_expected = $this->utf_to_hexseq($utf_expected); + } + + foreach (array('nfc', 'nfkc', 'nfd', 'nfkd') as $form) + { + $utf_result = $utf_expected; + call_user_func(array('utf_normalizer', $form), &$utf_result); + $hex_result = $this->utf_to_hexseq($utf_result); + + $this->assertEquals($utf_expected, $utf_result, "$hex_expected == $form($hex_tested) ($hex_expected != $hex_result)"); + } + } + fclose($fp); + } + + /** + * Convert a UTF string to a sequence of codepoints in hexadecimal + * + * @param string $utf UTF string + * @return integer Unicode codepoints in hex + */ + protected function utf_to_hexseq($str) + { + $pos = 0; + $len = strlen($str); + $ret = array(); + + while ($pos < $len) + { + $c = $str[$pos]; + switch ($c & "\xF0") + { + case "\xC0": + case "\xD0": + $utf_char = substr($str, $pos, 2); + $pos += 2; + break; + + case "\xE0": + $utf_char = substr($str, $pos, 3); + $pos += 3; + break; + + case "\xF0": + $utf_char = substr($str, $pos, 4); + $pos += 4; + break; + + default: + $utf_char = $c; + ++$pos; + } + + $hex = dechex($this->utf_to_cp($utf_char)); + + if (!isset($hex[3])) + { + $hex = substr('000' . $hex, -4); + } + + $ret[] = $hex; + } + + return strtr(implode(' ', $ret), 'abcdef', 'ABCDEF'); + } + + /** + * Convert a UTF-8 char to its codepoint + * + * @param string $utf_char UTF-8 char + * @return integer Unicode codepoint + */ + protected function utf_to_cp($utf_char) + { + switch (strlen($utf_char)) + { + case 1: + return ord($utf_char); + + case 2: + return ((ord($utf_char[0]) & 0x1F) << 6) | (ord($utf_char[1]) & 0x3F); + + case 3: + return ((ord($utf_char[0]) & 0x0F) << 12) | ((ord($utf_char[1]) & 0x3F) << 6) | (ord($utf_char[2]) & 0x3F); + + case 4: + return ((ord($utf_char[0]) & 0x07) << 18) | ((ord($utf_char[1]) & 0x3F) << 12) | ((ord($utf_char[2]) & 0x3F) << 6) | (ord($utf_char[3]) & 0x3F); + + default: + throw new RuntimeException('UTF-8 chars can only be 1-4 bytes long'); + } + } + + /** + * Return a UTF string formed from a sequence of codepoints in hexadecimal + * + * @param string $seq Sequence of codepoints, separated with a space + * @return string UTF-8 string + */ + protected function hexseq_to_utf($seq) + { + return implode('', array_map(array($this, 'hex_to_utf'), explode(' ', $seq))); + } + + /** + * Convert a codepoint in hexadecimal to a UTF-8 char + * + * @param string $hex Codepoint, in hexadecimal + * @return string UTF-8 char + */ + protected function hex_to_utf($hex) + { + return $this->cp_to_utf(hexdec($hex)); + } + + /** + * Convert a codepoint to a UTF-8 char + * + * @param integer $cp Unicode codepoint + * @return string UTF-8 string + */ + protected function cp_to_utf($cp) + { + if ($cp > 0xFFFF) + { + return chr(0xF0 | ($cp >> 18)) . chr(0x80 | (($cp >> 12) & 0x3F)) . chr(0x80 | (($cp >> 6) & 0x3F)) . chr(0x80 | ($cp & 0x3F)); + } + else if ($cp > 0x7FF) + { + return chr(0xE0 | ($cp >> 12)) . chr(0x80 | (($cp >> 6) & 0x3F)) . chr(0x80 | ($cp & 0x3F)); + } + else if ($cp > 0x7F) + { + return chr(0xC0 | ($cp >> 6)) . chr(0x80 | ($cp & 0x3F)); + } + else + { + return chr($cp); + } + } + + // chunked download helper + static protected function download($url, $to) + { + $target = $to . '/' . basename($url); + + if (file_exists($target)) + { + return; + } + + if (!$fpr = fopen($url, 'rb')) + { + echo "Failed to download $url\n"; + return; + } + + if (!$fpw = fopen($target, 'wb')) + { + echo "Failed to open $target for writing\n"; + return; + } + + $chunk = 32768; + + while (!feof($fpr)) + { + fwrite($fpw, fread($fpr, $chunk)); + } + fclose($fpr); + fclose($fpw); + } +} diff --git a/tests/utf/utf8_clean_string_test.php b/tests/utf/utf8_clean_string_test.php index 870ad76fc4..e5a771eafa 100644 --- a/tests/utf/utf8_clean_string_test.php +++ b/tests/utf/utf8_clean_string_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/utf/utf_tools.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/utf/utf_tools.php'; class phpbb_utf_utf8_clean_string_test extends phpbb_test_case { diff --git a/tests/utf/utf8_wordwrap_test.php b/tests/utf/utf8_wordwrap_test.php index ef1165a897..03fa9dc38c 100644 --- a/tests/utf/utf8_wordwrap_test.php +++ b/tests/utf/utf8_wordwrap_test.php @@ -7,8 +7,7 @@ * */ -require_once 'test_framework/framework.php'; -require_once '../phpBB/includes/utf/utf_tools.php'; +require_once dirname(__FILE__) . '/../../phpBB/includes/utf/utf_tools.php'; class phpbb_utf_utf8_wordwrap_test extends phpbb_test_case { |