Add namespace.

This commit is contained in:
2014-06-02 18:58:49 +04:00
parent aec1a60985
commit 1ba341b064
159 changed files with 265 additions and 264 deletions

56
Tests/ConfigTest.php Normal file
View File

@ -0,0 +1,56 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-06
*
* Unit tests for Config class
*/
require_once dirname(__FILE__) . '/../Registry.php';
require_once dirname(__FILE__) . '/../Config.php';
require_once dirname(__FILE__) . '/../exception/GeneralException.php';
class ConfigTest extends PHPUnit_Framework_TestCase
{
private $_instance = null;
public function setUp()
{
$this->_instance = Config::getInstance();
}
public function testGetInstance()
{
$this->assertSame($this->_instance, Config::getInstance());
/**
* @TODO: Config - class does not instanciate, Registry instead!!! Use late static binding
*/
$this->assertNotEquals('Config', get_class(Config::getInstance()));
}
public function testArrayAsParam()
{
$arr = array(
'one' => 1,
'two' => 2,
'three' => 3,
4 => 'four'
);
Config::set(0, $arr);
$new_arr = Config::get(0);
$this->assertSame('ConfigArray', get_class($new_arr));
$this->assertSame('four', $new_arr->offsetGet(4));
$this->assertSame(1, $new_arr->one);
$this->assertNotEquals(1, $new_arr->offsetGet('two'));
$this->setExpectedException('GeneralException', 'Configuration variable');
$new_arr->some;
}
}

228
Tests/LoadTest.php Normal file
View File

@ -0,0 +1,228 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-..
*
* Unit tests for Load class
*/
require_once dirname(__FILE__) . '/../Registry.php';
require_once dirname(__FILE__) . '/../Config.php';
require_once dirname(__FILE__) . '/../Load.php';
require_once 'vfsStream/vfsStream.php';
class LoadTest extends PHPUnit_Framework_TestCase
{
private static $inc_dirs = array();
private static $file;
private $root;
public static $file_contents;
public static $autoload_array;
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
/**
* @TODO: Load->buildAutoload() should recieve AutoloadBuilder as a parameter
*/
public function setUp()
{
self::$file_contents = '<?php return array("Db" => "/lib/core/model/Db.php", "DbDriver" => "/lib/core/model/DbDriver.php"); ?>';
self::$autoload_array = array('Db' => '/lib/core/model/Db.php', 'DbDriver' => '/lib/core/model/DbDriver.php');
vfsStreamWrapper::register();
vfsStream::setup();
$this->root = vfsStream::create(
array(
'lib' => array(
'core' =>
array(
'util' => array(
'AutoloadBuilder.php' => ''
),
'model' => array(
'Db.php' => '',
'DbDriver.php' => ''
),
'Registry.php' => '',
'Load.php' => '',
'devel.config' => ' development config file'
)
),
'autoload.php' => self::$file_contents
)
);
if (!class_exists('AutoloadBuilder')) {
$this->getMock('AutoloadBuilder');
}
vfsStreamWrapper::setRoot($this->root);
self::$file = vfsStream::url('root/autoload.php');
set_new_overload(array($this, 'newCallback'));
}
/**
* @runInSeparateProcess
*/
public function testSetAutoLoadFromExistingFile()
{
$this->setConstants();
$this->assertFileExists(self::$file);
Load::setAutoloadFrom(self::$file);
$autoload = require(self::$file);
$this->assertSame(self::$autoload_array, $autoload);
Load::autoload('Db');
}
/**
* @runInSeparateProcess
*/
public function testAutoloadFromNonExistingFile()
{
$this->setConstants();
$this->assertTrue($this->root->removeChild('autoload.php'));
$this->assertFileNotExists(self::$file);
Load::setAutoloadFrom(self::$file);
$autoload = require(self::$file);
$this->assertSame(self::$autoload_array, $autoload);
}
public function testAutoloadArrayExists()
{
$this->assertFileExists(self::$file);
}
/**
* @runInSeparateProcess
*/
public function testFileForArray()
{
$autoload = require(self::$file);
$this->assertInternalType('array', $autoload);
}
/**
* @runInSeparateProcess
*/
public function testAutoloadArrayNotEmpty()
{
$autoload = require(self::$file);
$this->assertNotEmpty($autoload);
$this->assertArrayHasKey('Db', $autoload);
}
/**
* @runInSeparateProcess
*/
public function testAutoloadGetFilePath()
{
$this->setConstants();
Load::setAutoloadFrom(self::$file);
$this->assertNotEmpty(Load::getFilePath('DbDriver'));
}
/**
* @runInSeparateProcess
*/
public function testAutoloadGetFilePathNullIndex()
{
$this->setConstants();
Load::setAutoloadFrom(self::$file);
$autoload = require(self::$file);
$this->setExpectedException('PHPUnit_Framework_Error', 'Undefined index');
$this->assertNotEmpty(Load::getFilePath('ClassDontExist'));
}
/**
* @runInSeparateProcess
*/
public function testDebugAutoload()
{
$this->setConstants();
unlink(self::$file);
Load::setAutoloadFrom(self::$file);
$autoload = require(self::$file);
$this->assertNotEmpty($autoload);
Config::set('DEBUG', true);
Load::autoload('Some');
Load::autoload('DbDriver');
}
/**
* @runInSeparateProcess
*/
public function testSetExclude()
{
$reflection_prop = new ReflectionProperty('Load', 'exclude');
$reflection_prop->setAccessible(true);
$this->assertCount(0, $reflection_prop->getValue('Load'));
Load::setExclude('dir1');
$this->assertCount(1, $reflection_prop->getValue('Load'));
Load::setExclude(array('dir2'));
$this->assertCount(2, $reflection_prop->getValue('Load'));
$this->assertSame(array('dir1', 'dir2'), $reflection_prop->getValue('Load'));
}
protected function newCallback($className)
{
switch ($className) {
case 'AutoloadBuilder':
return 'AutoloadBuilderMock';
default:
return $className;
}
}
private function setConstants()
{
if (!defined('PATH')) {
define('PATH', vfsStream::url('root'));
}
if (!defined('APP')) {
define('APP', 'lib/core/tests/face');
}
}
public function tearDown()
{
// if (defined('PATH')) {
// echo PHP_EOL . __CLASS__ . ' ' . PATH . PHP_EOL;
// } else {
// echo PHP_EOL . __CLASS__ . ' ' . 'PATH NOT DEFINED' . PHP_EOL;
// }
unset_new_overload();
}
}
class AutoloadBuilderMock
{
public function build()
{
$file = new vfsStreamFile('autoload.php');
$file->setContent(LoadTest::$file_contents);
vfsStreamWrapper::getRoot()->addChild($file);
}
}

28
Tests/MySQLTestsSuite.php Normal file
View File

@ -0,0 +1,28 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-12-02
*
* Test set for MySQL
*/
require_once 'model/MySQLiDriverTest.php';
require_once 'model/MySQLiStatementTest.php';
class PackageMySQLTests
{
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('MySQL');
$suite->addTestSuite('MySQLiDriverTest');
$suite->addTestSuite('MySQLiStatementTest');
return $suite;
}
}

27
Tests/RedisTestsSuite.php Normal file
View File

@ -0,0 +1,27 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-12-02
*
* Test set for Redis
*/
require_once 'redis/RedisDebugTest.php';
require_once 'redis/RedisManagerTest.php';
class PackageRedisTests
{
public static function suite()
{
$suite = new PHPUnit_Framework_TestSuite('Redis');
$suite->addTestSuite('RedisDebugTest');
$suite->addTestSuite('RedisManagerTest');
return $suite;
}
}

72
Tests/RegistryTest.php Normal file
View File

@ -0,0 +1,72 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-06
*
* Unit tests for Registry
*/
require_once dirname(__FILE__) . '/../Registry.php';
class RegistryTest extends PHPUnit_Framework_TestCase
{
private $_registry = null;
public function setUp()
{
$this->assertFalse(Registry::isRegistered(10));
$this->_registry = Registry::getInstance();
}
public function testGetInstance()
{
$this->assertNotNull(Registry::getInstance());
$this->assertNotNull($this->_registry);
$this->assertSame(Registry::getInstance(), $this->_registry);
}
/**
* @TODO: Registry - make __construct private
*/
// public function testRegistryConstructor()
// {
// $this->setExpectedException('PHPUnit_Framework_Error');
// $reg = new Registry();
// }
public function testSet()
{
Registry::set(1, 1);
Registry::set('two', 2);
$this->assertSame(Registry::get(1), $this->_registry->get(1));
$this->assertSame(2, Registry::get('two'));
}
public function testGet()
{
$this->assertSame(Registry::get(1), $this->_registry->get(1));
$this->assertSame(Registry::get('two'), 2);
$this->assertNull(Registry::get(4));
}
/**
* @TODO: Registry::isRegistered - check input for null
*/
public function testIsRegistered()
{
$this->assertFalse(Registry::isRegistered(43));
$this->_registry->set(3, 'three');
$this->assertTrue(Registry::isRegistered(3));
$this->setExpectedException('PHPUnit_Framework_Error');
$this->assertFalse(Registry::isRegistered(null));
}
}

76
Tests/app/ActionTest.php Normal file
View File

@ -0,0 +1,76 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-1
*
* Unit tests for Action class
*/
require_once dirname(__FILE__) . '/Action_TestCase.php';
class ActionTest extends Action_TestCase
{
/**
* @runInSeparateProcess
*/
public function testActionConstructWithParams()
{
Config::set('DEBUG', false);
Env::setParams(array('param1' => 'value1', 'param2' => 'value2'));
$action = $this->getMockForAbstractClass('Action' );
$this->assertSame('value1', $action->param1);
}
/**
* @runInSeparateProcess
*/
public function testFetch()
{
Config::set('DEBUG', false);
$load = new ReflectionClass('Load');
$classes = $load->getProperty('autoload');
$classes->setAccessible(true);
$classes->setValue('autoload', array('ActionMock' =>'some/path/to/action.php'));
Env::setParams(array('template' => 'SomeTemplate', 'param2' => 'value2'));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('Action', array(), 'ActionMock');
$result = $action->fetch();
$this->assertSame('/actions/to/SomeTemplate', $result['template']);
}
/**
* @runInSeparateProcess
*/
public function testFetchNoTemplate()
{
Config::set('DEBUG', false);
Env::setParams(array('template' => ''));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('Action', array(), 'ActionMock');
$result = $action->fetch();
$this->assertSame('/actions//Acti', $result['template']);
}
/**
* @runInSeparateProcess
*/
public function testRedirect()
{
set_exit_overload(function() { return false; });
Config::set('DEBUG', false);
$load = new ReflectionClass('Action');
$redirect = $load->getMethod('redirect');
$redirect->setAccessible(true);
$action = $this->getMockForAbstractClass('Action', array(), 'ActionMock');
$this->assertNull($redirect->invoke($action, '/some/url'));
unset_exit_overload();
}
}

View File

@ -0,0 +1,70 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-1
*
* Action_TestCase class for testing Actions
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../Load.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../app/Action.php';
require_once dirname(__FILE__) . '/../../view/iView.php';
class Action_TestCase extends PHPUnit_Framework_TestCase
{
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
$this->getMock('Router');
$this->getMock('PHPView', array('fetch', 'assignObject'));
}
public function tearDown()
{
$env = new ReflectionClass('Env');
$params = $env->getProperty('params');
$params->setAccessible(true);
$params->setValue('Env', array());
}
}
class SomeView implements iView
{
private $result = array();
public function fetch($template)
{
$this->result['template'] = $template;
return $this->result;
}
public function assignObject() {}
public function assign($name, $value = null) {
$this->result[$name] = $value;
}
public function prepend($name, $value)
{
}
public function append($name, $value)
{
}
}

View File

@ -0,0 +1,93 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-01
*
* Unit tests for AjaxAction class
*/
require_once dirname(__FILE__) . '/Action_TestCase.php';
require_once dirname(__FILE__) . '/../../app/AjaxAction.php';
class AjaxActionTest extends Action_TestCase
{
/**
* @runInSeparateProcess
*/
public function testConstruct()
{
Config::set('DEBUG', false);
Env::setParams(array('ajax' => 'AjaxTemplate', 'param2' => 'value2'));
$action = $this->getMockForAbstractClass('AjaxAction');
$this->assertAttributeEquals('ajax', 'template', $action);
}
/**
* @runInSeparateProcess
*/
public function testFetchWithEncode()
{
Config::set('DEBUG', false);
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('AjaxAction');
$action->data = array('var' => 'val');
$result = $action->fetch();
$this->assertSame('/actions//ajax', $result['template']);
$this->assertSame('{"var":"val"}', $result['data']);
}
/**
* @runInSeparateProcess
*/
public function testFetchNoEncode()
{
Config::set('DEBUG', false);
Env::setParams(array('json_encode' => false));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('AjaxAction');
$action->data = array('var' => 'val');
$result = $action->fetch();
$this->assertSame('/actions//ajax', $result['template']);
$this->assertSame('Array', (string) $result['data']);
$action->data = 'stringvalue';
$result = $action->fetch();
$this->assertSame('/actions//ajax', $result['template']);
$this->assertSame('stringvalue', (string) $result['data']);
}
/**
* @runInSeparateProcess
*/
public function testFetchWithEncodeDefault()
{
Config::set('DEBUG', false);
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('AjaxAction');
$result = $action->fetch();
$this->assertSame('/actions//ajax', $result['template']);
$this->assertSame('false', (string) $result['data']);
}
/**
* @runInSeparateProcess
*/
public function testFetchNoEncodeDefault()
{
Config::set('DEBUG', false);
Env::setParams(array('json_encode' => false));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('AjaxAction');
$result = $action->fetch();
$this->assertSame('/actions//ajax', $result['template']);
$this->assertSame('', (string) $result['data']);
}
}

View File

@ -0,0 +1,120 @@
<?php
/**
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage Tests app
* @since 10.07.12
*
*/
require_once __DIR__ . '/../../util/profiler/Profiler.php';
require_once __DIR__ . '/../../exception/GeneralException.php';
require_once __DIR__ . '/../../exception/ErrorHTTPException.php';
require_once __DIR__ . '/../../exception/Error404Exception.php';
require_once __DIR__ . '/../../exception/ErrorHandler.php';
require_once __DIR__ . '/../../app/CliController.php';
require_once __DIR__ . '/../../Registry.php';
require_once __DIR__ . '/../../Config.php';
require_once __DIR__ . '/../../app/iCli.php';
require_once __DIR__ . '/../../logger/Logger.php';
require_once __DIR__ . '/../../logger/CliLogger.php';
/**
* @desc CliController tests
* @author Aleksandr Demidov
*/
class CliControllerTest extends PHPUnit_Framework_TestCase
{
protected $stream;
public function testGetInstance()
{
$instance = CliController::getInstance();
$this->assertInstanceOf('CliController', $instance);
}
public function testExecute()
{
Config::set('PROFILER', false);
$cli_class = $this->getMockForAbstractClass('iCli', array(), '', '', '', '', array('run'));
$cli_class->expects($this->once())
->method('run')
->with();
CliController::getInstance()->execute($cli_class);
}
public function testExecuteWithProfiler()
{
ob_start();
Config::set('PROFILER', true);
$cli_class = $this->getMockForAbstractClass('iCli', array(), '', '', '', '', array('run'));
$cli_class->expects($this->once())
->method('run')
->with();
CliController::getInstance()->execute($cli_class);
$output = ob_get_clean();
$this->assertContains('Elapsed time:', $output);
}
public function testExecuteWithLogger()
{
ob_start();
Config::set('PROFILER', true);
Config::set('LOGGING', true);
Config::set('Logger', array('logger' => 'CliLogger'));
$cli_class = $this->getMockForAbstractClass('iCli', array(), '', '', '', '', array('run'));
$cli_class->expects($this->once())
->method('run')
->with();
CliController::getInstance()->execute($cli_class);
$output = ob_get_clean();
$this->assertContains('Elapsed time:', $output);
}
/**
* @runInSeparateProcess
*/
public function testExecuteImplementErrorToFile()
{
Config::set('ErrorStream', __DIR__ . '/temp.txt');
touch(Config::get('ErrorStream'));
$cli_class = new StdClass();
CliController::getInstance()->execute($cli_class);
$this->assertContains('Runner "' . get_class($cli_class) . '" need implement of "iCli" interface.', file_get_contents(Config::get('ErrorStream')));
unlink(Config::get('ErrorStream'));
}
/**
* @runInSeparateProcess
*/
public function testExecuteImplementErrorToConsole()
{
Config::set('ErrorStream', 'php://output');
$cli_class = new StdClass();
$this->expectOutputRegex('/.*Runner "' . get_class($cli_class) . '" need implement of "iCli" interface\..*/');
CliController::getInstance()->execute($cli_class);
}
/**
* @runInSeparateProcess
*/
public function testExecuteWithRunThrowError()
{
Config::set('ErrorStream', 'php://output');
Config::set('PROFILER', false);
$cli_class = $this->getMockForAbstractClass('iCli', array(), '', '', '', '', array('run'));
$cli_class->expects($this->once())
->method('run')
->with()
->will($this->returnCallback(array($this, 'callbackWithThrow')));
$this->expectOutputRegex('/.*Error from callback\..*/');
CliController::getInstance()->execute($cli_class);
}
public function callbackWithThrow()
{
throw new ErrorException('Error from callback.');
}
}

View File

@ -0,0 +1,162 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-1
*
* Unit tests for ErrorAction class
*/
require_once dirname(__FILE__) . '/Action_TestCase.php';
require_once dirname(__FILE__) . '/../../app/ErrorAction.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHTTPException.php';
require_once dirname(__FILE__) . '/../../exception/Error404Exception.php';
class ErrorActionTest extends Action_TestCase
{
private $log;
public function setUp()
{
parent::setUp();
$this->log = ini_get('error_log');
ini_set('error_log', '/dev/null');
set_exit_overload(function () {
return false;
});
}
/**
* @runInSeparateProcess
*/
public function testErrorExceptionNotice()
{
$this->setConstants(false);
$exception = $this->getMock('ErrorException', array(), array('', 0, E_NOTICE));
$action = new ErrorAction($exception);
$this->assertSame($exception, $action->exception);
}
/**
* @runInSeparateProcess
*/
public function testErrorExceptionWarning()
{
$this->setConstants(false);
$exception = $this->getMock('ErrorException', array(), array('', 0, E_WARNING));
$action = new ErrorAction($exception);
$this->assertSame($exception, $action->exception);
}
/**
* @runInSeparateProcess
*/
public function testErrorExceptionError()
{
$this->setConstants(false);
$exception = $this->getMock('ErrorException', array(), array('', 0, E_ERROR));
$action = new ErrorAction($exception);
$this->assertSame($exception, $action->exception);
}
/**
* @runInSeparateProcess
*/
public function testErrorExceptionCustom()
{
$this->setConstants(false);
$exception = $this->getMock('ErrorException', array(), array('', 0, 211));
$action = new ErrorAction($exception);
$this->assertSame($exception, $action->exception);
}
/**
* @runInSeparateProcess
*/
public function testFetchNoTemplate()
{
Config::set('DEBUG', false);
$exception = $this->getMock('ErrorException');
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = new ErrorAction($exception);
$result = $action->fetch();
$this->assertSame('/actions/500', $result['template']);
}
/**
* @runInSeparateProcess
*/
public function testError404WithAjax()
{
$this->setConstants(false);
$exception = new Error404Exception('Some message');
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = new ErrorAction($exception);
$action->setAjaxError();
$this->assertSame($exception, $action->exception);
$result = $action->fetch();
$this->assertSame('Some message', $result);
}
/**
* @runInSeparateProcess
*/
public function testError404NoAjax()
{
$this->setConstants(false);
$exception = new Error404Exception('Some message');
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = new ErrorAction($exception);
$this->assertSame($exception, $action->exception);
$result = $action->fetch();
$this->assertSame('/actions/404', $result['template']);
}
/**
* @runInSeparateProcess
*/
public function testErrorHTTP()
{
$this->setConstants(false);
$exception = new ErrorHTTPException('Some message', 410);
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = new ErrorAction($exception);
$this->assertSame($exception, $action->exception);
$result = $action->fetch();
$this->assertSame('/actions/HTTP', $result['template']);
}
private function setConstants($val = false)
{
Config::set('DEBUG', $val);
}
private function header()
{
ob_end_clean();
flush();
}
public function tearDown()
{
parent::tearDown();
ini_set('error_log', $this->log);
unset_exit_overload();
}
}

View File

@ -0,0 +1,311 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-1
*
* Unit tests for FrontController class
*/
require_once dirname(__FILE__) . '/../../session/Session.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../util/FirePHPCore-0.3.2/lib/FirePHPCore/fb.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHTTPException.php';
require_once dirname(__FILE__) . '/../../exception/Error404Exception.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../app/router/Route.php';
require_once dirname(__FILE__) . '/../../app/router/Router.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../app/Action.php';
require_once dirname(__FILE__) . '/../../app/AjaxAction.php';
class FrontControllerTest extends PHPUnit_Framework_TestCase
{
protected $log_file_name = 'error_log_file';
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
if (!class_exists('PHPViewMock')) {
$this->getMock('PHPView', array('fetch', 'append', 'prepend', 'assign', 'getTemplate'), array(), 'PHPViewMock', false);
}
if (!class_exists('View')) {
$this->getMock('View');
}
if (!class_exists('ErrorLayout')) {
$this->getMock('ErrorLayout', array('fetch', 'setException'), array(), 'ErrorLayoutMock');
}
if (!class_exists('ErrorActionMock')) {
$this->getMock('ErrorAction', array('setAjaxError'), array(), 'ErrorActionMock', false);
}
set_new_overload(array($this, 'newCallback'));
}
/**
* @runInSeparateProcess
*/
public function testGetInstanceNoProfiler()
{
$this->setConstants(false);
$controller = FrontController::getInstance();
$this->assertAttributeEquals($controller, 'instance', 'FrontController');
}
/**
* @runInSeparateProcess
*/
public function testGetInstanceWithProfiler()
{
$this->setConstants(true);
$controller = FrontController::getInstance();
$this->assertAttributeEquals($controller, 'instance', 'FrontController');
}
/**
* @runInSeparateProcess
*/
public function testSetView()
{
$this->setConstants(false);
$controller = FrontController::getInstance();
$this->assertSame($controller, $controller->setView('View'));
}
/**
* @runInSeparateProcess
*/
public function testGetDefaultView()
{
$this->setConstants(false);
$controller = FrontController::getInstance();
$this->assertNotInstanceOf('View', $controller->getView());
$this->assertInstanceOf('PHPView', $controller->getView());
}
/**
* @runInSeparateProcess
*/
public function testGetCustomView()
{
$this->setConstants(false);
$controller = FrontController::getInstance();
$this->assertInstanceOf('View', $controller->getView('View'));
}
/**
* @runInSeparateProcess
*/
public function testSetGetBaseUrl()
{
$this->setConstants(false);
$controller = FrontController::getInstance();
$this->assertSame('', $controller->getBaseUrl());
$controller->setBaseUrl('/index/');
$this->assertSame('/index', $controller->getBaseUrl());
}
/**
* @runInSeparateProcess
*/
public function testGetRouter()
{
$this->setConstants(false);
$controller = FrontController::getInstance();
$this->assertInstanceOf('Router', $controller->getRouter());
}
/**
* @runInSeparateProcess
*/
public function testExecuteNoRoute()
{
$this->setConstants(false);
$controller = FrontController::getInstance();
$this->assertNull($controller->execute());
}
/**
* @runInSeparateProcess
*/
public function testExecuteNoRouteDebug()
{
$this->setConstants(true);
ini_set('error_log', $this->log_file_name);
$controller = FrontController::getInstance();
$result = $controller->execute();
$this->assertNotEmpty($result);
$this->assertContains('Route for "" not found', $result);
$this->assertContains('Error404Exception', $result);
$error = file_get_contents($this->log_file_name);
$this->assertContains('PHP Unknown Error: Error404Exception: Route for "" not found in ', $error);
}
/**
* @runInSeparateProcess
*/
public function testExecuteNoAction()
{
$_SERVER['REQUEST_URI'] = '/user/account/213';
$this->setConstants(true);
ini_set('error_log', $this->log_file_name);
$controller = FrontController::getInstance();
$router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'user');
$result = $controller->execute();
$this->assertContains('Action class "userAction" not found.', $result);
$error = file_get_contents($this->log_file_name);
$this->assertContains('PHP Unknown Error: GeneralException: Action class "userAction" not found. in ', $error);
}
/**
* @runInSeparateProcess
*/
public function testExecuteNoLayout()
{
$this->getMock('userAction');
$_SERVER['REQUEST_URI'] = '/user/account/213';
$this->setConstants(true);
ini_set('error_log', $this->log_file_name);
$controller = FrontController::getInstance();
$router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'user');
$result = $controller->execute();
$this->assertContains('Layout class "DefaultLayout" not found.', $result);
$error = file_get_contents($this->log_file_name);
$this->assertContains('PHP Unknown Error: GeneralException: Layout class "DefaultLayout" not found. in ', $error);
}
/**
* @runInSeparateProcess
*/
public function testExecuteWithLayout()
{
$this->getMock('userAction');
$this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
$_SERVER['REQUEST_URI'] = '/user/account/213';
$this->setConstants(true);
$controller = FrontController::getInstance();
$router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'user');
$result = $controller->execute();
$this->assertNull($result);
}
/**
* @runInSeparateProcess
*/
public function testExecuteWithLayoutProfiler()
{
Config::set('PROFILER', true);
$this->getMock('userAction');
$this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
$_SERVER['REQUEST_URI'] = '/user/account/213';
$this->setConstants(true);
$controller = FrontController::getInstance();
$router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'user');
$result = $controller->execute();
$this->assertNull($result);
}
/**
* @runInSeparateProcess
*/
public function testExecuteWithAjaxAction()
{
$this->getMock('userAction');
$this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
$_SERVER['REQUEST_URI'] = '/user/account/213';
$this->setConstants(true);
$controller = FrontController::getInstance();
$router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'NewAjax');
$result = $controller->execute();
$this->assertNull($result);
}
/**
* @runInSeparateProcess
*/
public function testExecuteWithAjaxActionError()
{
$this->getMock('userAction');
$_SERVER['REQUEST_URI'] = '/user/account/213';
$this->setConstants(false);
$controller = FrontController::getInstance();
$router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'NewAjax');
$result = $controller->execute();
$this->assertNull($result);
}
/**
* @runInSeparateProcess
*/
public function testExecuteWithAjaxActionProfiler()
{
Config::set('PROFILER', true);
$this->getMock('userAction');
$this->getMock('DefaultLayout', array('fetch'), array(), 'DefaultLayoutMock');
$_SERVER['REQUEST_URI'] = '/user/account/213';
$this->setConstants(true);
$controller = FrontController::getInstance();
$router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'NewAjax');
$result = $controller->execute();
$this->assertNull($result);
}
private function setConstants($val = false)
{
Config::set('DEBUG', $val);
}
public function tearDown()
{
unset_new_overload();
if (file_exists($this->log_file_name) && is_writable($this->log_file_name)) {
unlink($this->log_file_name);
}
ini_set('error_log', 'php://stderr');
}
protected function newCallback($className)
{
switch ($className) {
case 'PHPView':
return 'PHPViewMock';
case 'DefaultLayout':
return 'DefaultLayoutMock';
case 'ErrorAction':
return 'ErrorActionMock';
case 'ErrorLayout':
return 'ErrorLayoutMock';
default:
return $className;
}
}
}
/**
* Used in testExecuteWithAjaxAction
*/
class NewAjaxAction extends AjaxAction
{
protected function execute()
{
}
}

View File

@ -0,0 +1,96 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-1
*
* Unit tests for PagerAction class
*/
require_once dirname(__FILE__) . '/Action_TestCase.php';
require_once dirname(__FILE__) . '/../../app/PagerAction.php';
class PagerActionTest extends Action_TestCase
{
/**
* @runInSeparateProcess
*/
public function testConstructWithParams()
{
Config::set('DEBUG', false);
$action = $this->getMockForAbstractClass('PagerAction');
$this->assertSame(20, $action->getLimit());
$action = $this->getMockForAbstractClass('PagerAction', array(50));
$this->assertSame(50, $action->getLimit());
}
/**
* @runInSeparateProcess
*/
public function testSetCount()
{
Config::set('DEBUG', false);
$action = $this->getMockForAbstractClass('PagerAction');
$action->setCount(50);
$this->assertSame(1, $action->page);
$this->assertSame(0, $action->getOffset());
$_GET['p'] = 'last';
$action->setCount(50);
$this->assertSame(3.0, $action->page);
$this->assertSame(40, $action->getOffset());
$_GET['p'] = 2;
$action->setCount(50);
$this->assertSame(2, $action->page);
$this->assertSame(20, $action->getOffset());
$_GET['p'] = -3;
$action->setCount(50);
$this->assertSame(1, $action->page);
}
/**
* @runInSeparateProcess
*/
public function testGetOffset()
{
Config::set('DEBUG', false);
$action = $this->getMockForAbstractClass('PagerAction');
$this->assertSame(0, $action->getOffset());
}
/**
* @runInSeparateProcess
*/
public function testFetchNoTemplate()
{
Config::set('DEBUG', false);
Env::setParams(array('template' => ''));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('PagerAction', array(), 'PagerActionMock');
$result = $action->fetch();
$this->assertSame('/actions/PagerActi', $result['template']);
}
/**
* @runInSeparateProcess
*/
public function testFetchWithTemplate()
{
Config::set('DEBUG', false);
Env::setParams(array('template' => 'SomeTemplate'));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('PagerAction');
$result = $action->fetch();
$this->assertSame('/actions/SomeTemplate', $result['template']);
}
}

View File

@ -0,0 +1,48 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-1
*
* Unit tests for StaticAction class
*/
require_once dirname(__FILE__) . '/Action_TestCase.php';
require_once dirname(__FILE__) . '/../../app/StaticAction.php';
class StaticActionTest extends Action_TestCase
{
/**
* @runInSeparateProcess
*/
public function testFetchNoTemplate()
{
Config::set('DEBUG', false);
Env::setParams(array('template' => ''));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('StaticAction', array(), 'StaticActionMock');
$result = $action->fetch();
$this->assertSame('/static/StaticActi', $result['template']);
}
/**
* @runInSeparateProcess
*/
public function testFetchWithTemplate()
{
Config::set('DEBUG', false);
Env::setParams(array('template' => 'SomeTemplate'));
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('StaticAction', array(), 'StaticActionMock');
$result = $action->fetch();
$this->assertSame('/static/SomeTemplate', $result['template']);
}
}

View File

@ -0,0 +1,93 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-31
*
* Unit tests for Router class
*/
require_once dirname(__FILE__) . '/../../../app/router/Route.php';
class RouteTest extends PHPUnit_Framework_TestCase
{
public function testConstructNoParams()
{
$route = new Route('index', 'user');
$this->assertSame('userAction', $route->getAction());
$this->assertSame('Layout', $route->getLayout());
$this->assertEmpty($route->getParams());
$this->assertAttributeEquals('index', 'route', $route);
}
public function testConstructWithParams()
{
$route = new Route('index', 'user', array('name' => 'tony', 'role' => 'user'));
$this->assertArrayHasKey('role', $route->getParams());
$this->assertSame(array('name' => 'tony', 'role' => 'user'), $route->getParams());
}
public function testMatchDiffCount()
{
$route = new Route('user/account/id/142', 'user', array('name' => 'tony', 'role' => 'user'));
$this->assertFalse($route->match(array('user', 'account')));
}
/**
* @TODO: Route::match() - need to trim left-right slashes
*/
public function testMatchDiffParts()
{
$route = new Route('user/account', 'user');
$this->assertFalse($route->match(array('user', 'login')));
}
public function testMatchVariable()
{
$route = new Route('user/account/:id', 'user');
$this->assertTrue($route->match(array('user', 'account', '142')));
$this->assertSame(array('id' => '142'), $route->getParams());
}
public function testMatchDiffPregParts()
{
$route = new Route('user/account/(?<key>value)', 'user');
$this->assertFalse($route->match(array('user', 'account', 'wrong')));
$this->assertSame(0, count($route->getParams()));
}
public function testMatchPregPasses()
{
$route = new Route('user/account/(?<key>[a-z]+)', 'user');
$this->assertTrue($route->match(array('user', 'account', 'value')));
$this->assertSame(array('key' => 'value'), $route->getParams());
$this->assertSame(1, count($route->getParams()));
}
/**
* @TODO Need check empty parameters from constructor Route
*/
public function testMatchEmptyRequest()
{
$route = new Route('', 'user', array('name' => 'tony', 'role' => 'user'));
$this->setExpectedException('PHPUnit_Framework_Error');
$route->match('');
}
public function testGetUri()
{
$route = 'myroute';
$route_mock = $this->getMockBuilder('Route')
->disableOriginalConstructor()
->setMethods(array('__construct'))
->getMock();
$reflection = new ReflectionProperty('Route', 'route');
$reflection->setAccessible(true);
$reflection->setValue($route_mock, $route);
$this->assertEquals('/' . $route, $route_mock->getUri());
}
}

View File

@ -0,0 +1,122 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-31
*
* Unit tests for Router class
*/
require_once dirname(__FILE__) . '/../../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../../app/router/Route.php';
require_once dirname(__FILE__) . '/../../../app/router/Router.php';
class RouterTest extends PHPUnit_Framework_TestCase
{
public function testGetRouteFirst()
{
$router = new Router();
$this->assertNull($router->getRoute());
$this->assertNull($router->getRouteName());
}
public function testRouterCycle()
{
$router = new Router();
$router->add('user', 'user/account/:id', 'user');
$route = $router->route('user/account/213');
$this->assertSame(1, count($route->getParams()));
$this->assertSame(array('id' => '213'), $route->getParams());
$this->assertSame('user', $router->getRouteName());
}
public function testRouterMultipleRoutes()
{
$router = new Router();
$router->add('user', 'user/account/:id', 'user');
$router->add('sale', 'sale/order/:id', 'user');
$route = $router->route('user/account/213');
$this->assertSame('user', $router->getRouteName());
$this->assertSame(1, count($route->getParams()));
$this->assertSame(array('id' => '213'), $route->getParams());
$route = $router->route('sale/order/22');
$this->assertSame('sale', $router->getRouteName());
$this->assertSame(array('id' => '22'), $route->getParams());
}
public function testRouteNotmatch()
{
$router = new Router();
$router->add('user', 'user/account/:id', 'user');
$this->assertFalse($router->route('user/info/213'));
}
public function testSetDefaultLayout()
{
$router = new Router();
$router->setDefaultLayout('userLayout');
$this->assertAttributeEquals('userLayout', 'default_layout', $router);
}
public function testGetRouteWithNameIsNull()
{
$name = null;
$route = 'route object.';
$router = new Router();
$reflection = new ReflectionProperty('Router', 'route');
$reflection->setAccessible(true);
$reflection->setValue($router, $route);
$this->assertEquals($route, $router->getRoute($name));
}
public function testGetRouteWithNamed()
{
$name = 'nameofroute';
$uri = 'uri from route.';
$route = 'route object.';
$router = new Router();
$reflection = new ReflectionProperty('Router', 'routes');
$reflection->setAccessible(true);
$reflection->setValue($router, array($name => $route));
$this->assertEquals($route, $router->getRoute($name));
}
public function testGetRouteWithNamedWithError()
{
$name = 'name of route';
$router = new Router();
$this->setExpectedException('ErrorException');
$router->getRoute($name);
}
public function testRouteIsExists()
{
$route = 'route object.';
$name = 'nameofroute';
$name_is_not_exists = 'nameofroutenotexists';
$routes = array($name => $route);
$router = new Router();
$reflection = new ReflectionProperty('Router', 'routes');
$reflection->setAccessible(true);
$reflection->setValue($router, $routes);
$this->assertTrue($router->routeIsExists($name));
$this->assertFalse($router->routeIsExists($name_is_not_exists));
}
public function testGetDefaultErrorLayout()
{
$router = new Router();
$this->assertSame('ErrorLayout', $router->getErrorLayout());
}
public function testSetErrorLayout()
{
$router = new Router();
$router->setErrorLayout('CustomError');
$this->assertSame('CustomErrorLayout', $router->getErrorLayout());
}
}

7
Tests/bootstrap.php Normal file
View File

@ -0,0 +1,7 @@
<?php
require_once dirname(__FILE__) . '/../session/Session.php';
ob_start();
Session::start();
?>

85
Tests/cache/CacheKeyTest.php vendored Normal file
View File

@ -0,0 +1,85 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-14
*
* Unit tests for CacheKey class
*/
/**
* @TODO: CacheKey->getExpire() method never used
*/
require_once dirname(__FILE__) . '/../../cache/Cache.php';
require_once dirname(__FILE__) . '/../../cache/CacheKey.php';
class CacheKeyTest extends PHPUnit_Framework_TestCase
{
private $cache;
public function testConstructor()
{
$mock = $this->getMock('Cache');
$cache = new CacheKey($mock, 'anything', array('one', 'two', 'three'),200);
$this->assertAttributeEquals('anything_one|two|three', 'key', $cache);
}
public function testExpire()
{
$this->cache = new CacheKey($this->getMock('Cache'), 'key');
$this->assertAttributeEquals(0, 'expire', $this->cache);
$this->cache->setExpire(20);
$this->assertAttributeEquals(20, 'expire', $this->cache);
}
public function testGetExpire()
{
$this->cache = new CacheKey(null, 'key');
$this->cache->setExpire(100);
$getExpireMethod = new ReflectionMethod('CacheKey', 'getExpire');
$getExpireMethod->setAccessible(TRUE);
$this->assertSame(100, $getExpireMethod->invoke($this->cache));
}
public function testGetSet()
{
$mockCacher = $this->getMock('Cache');
$mockCacher->expects($this->any())
->method('set')
->with('any', 'some', 0);
$mockCacher->expects($this->any())
->method('get')
->with('any')
->will($this->returnValue('some'));
$this->cache = new CacheKey($mockCacher, 'any');
$this->cache->set('some');
$this->assertSame('some', $this->cache->get());
}
public function testDel()
{
$mockCacher = $this->getMock('Cacher', array('del'));
$mockCacher->expects($this->any())
->method('del')
->with('some')
->will($this->returnValue(true));
$cache = new CacheKey($mockCacher, 'some');
$this->assertTrue($cache->del());
}
}

68
Tests/cache/CacherTest.php vendored Normal file
View File

@ -0,0 +1,68 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-25
*
* Unit tests for Cacher class
*/
require_once dirname(__FILE__) . '/../../cache/Cache.php';
require_once dirname(__FILE__) . '/../../cache/Cacher.php';
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class CacherTest extends PHPUnit_Framework_TestCase
{
private $mock;
protected function setUp()
{
set_new_overload(array($this, 'newCallback'));
}
public function testNotExtendsCache()
{
$this->setExpectedException('InitializationException', 'Cache driver');
Cacher::get('Cacher');
}
public function testGet()
{
$this->mock = $this->getMockForAbstractClass(
'Cache', /* name of class to mock */
array(), /* list of methods to mock */
'CacheMock' /* name for mocked class */
);
$this->assertTrue(Cacher::get('Cache') instanceof Cache);
}
public function testCacheAlreadySet()
{
$this->assertTrue(Cacher::get('Cache') instanceof Cache);
}
protected function newCallback($className)
{
switch ($className) {
case 'Cache':
return 'CacheMock';
default:
return $className;
}
}
public function tearDown()
{
unset_new_overload();
}
}

202
Tests/cache/MemcacheCacheTest.php vendored Normal file
View File

@ -0,0 +1,202 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-25
*
* Unit tests for MemcacheCache class
*
* Tests need test_helpers extension by Sebastian Bergmann
*/
require_once dirname(__FILE__) . '/../../cache/Cache.php';
require_once dirname(__FILE__) . '/../../cache/MemcacheCache.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class MemcacheCacheTest extends PHPUnit_Framework_TestCase
{
protected function setUp()
{
$this->getMock('Memcache');
set_new_overload(array($this, 'newCallback'));
}
public function testConstruct()
{
$config = array('key_salt' => 'some', 'host' => array('hostname' => 'localhost', 'port' => 8080));
$memcache = new MemcacheCache($config);
$this->assertAttributeInstanceOf('TestCache', 'connection', $memcache);
}
public function testWrongConfig()
{
$config = array('some' => array());
$this->setExpectedException('InitializationException', 'Configuration must have a');
$memcache = new MemcacheCache($config);
}
public function testAddGet()
{
$memcache = new MemcacheCache(array());
$this->assertTrue($memcache->add('key', 'value'));
$this->assertSame('value', $memcache->get('key'));
$this->assertFalse($memcache->add('key', 'newvalue'));
}
public function testIncrementDecrement()
{
$memcache = new MemcacheCache(array());
$memcache->add('one', 1);
$memcache->add('two', 2);
$memcache->add('three', 'three');
$this->assertTrue($memcache->increment('one'));
$this->assertSame(2, $memcache->get('one'));
$this->assertTrue($memcache->decrement('two'));
$this->assertSame(1, $memcache->get('two'));
$this->assertFalse($memcache->decrement('three'));
}
public function testDelete()
{
$memcache = new MemcacheCache(array());
$memcache->add('one', 1);
$memcache->add('two', 2);
$memcache->del('one');
$this->assertSame(2, $memcache->get('two'));
$this->assertFalse($memcache->get('one'));
}
public function testFlush()
{
$memcache = new MemcacheCache(array());
$memcache->add('one', 1);
$memcache->add('two', 2);
$memcache->add('three', 'three');
$this->assertSame('three', 'three');
$memcache->flush();
$this->assertFalse($memcache->get('three'));
$this->assertFalse($memcache->get('one'));
}
public function testSetReplace()
{
$memcache = new MemcacheCache(array());
$memcache->add('one', 1);
$memcache->add('two', 2);
$memcache->add('three', 'three');
$memcache->set('one', 30);
$memcache->replace('three', 3);
$this->assertSame(30, $memcache->get('one'));
$this->assertSame(3, $memcache->get('three'));
}
protected function newCallback($className)
{
switch ($className) {
case 'Memcache':
return 'TestCache';
default:
return $className;
}
}
public function tearDown()
{
unset_new_overload();
}
}
class TestCache
{
private $vals = array();
public function addServer($host, $port)
{
return true;
}
public function add($key, $value, $some, $expire = 0)
{
if(!isset($this->vals[$key])) {
$this->vals[$key] = $value;
return true;
}
return false;
}
public function decrement($key, $decrement = 1)
{
if (isset($this->vals[$key]) && is_int($this->vals[$key])) {
$this->vals[$key]--;
return true;
}
return false;
}
public function delete($key)
{
if (isset($this->vals[$key])) {
unset($this->vals[$key]);
}
return true;
}
public function flush()
{
$this->vals = array();
}
public function get($key)
{
if (isset($this->vals[$key])) {
return $this->vals[$key];
}
return false;
}
public function increment($key, $increment = 1)
{
if (isset($this->vals[$key]) && is_int($this->vals[$key])) {
$this->vals[$key]++;
return true;
}
return false;
}
public function replace($key, $value, $any = null, $expire = 0)
{
if (isset($this->vals[$key])) {
$this->vals[$key] = $value;
return true;
}
return false;
}
public function set($key, $value, $any = null, $expire = 0)
{
$this->vals[$key] = $value;
return true;
}
}

View File

@ -0,0 +1,104 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-27
*
* Unit tests for Captcha class
*/
require_once dirname(__FILE__) . '/../../session/Session.php';
require_once dirname(__FILE__) . '/../../captcha/Captcha.php';
class CaptchaTest extends PHPUnit_Framework_TestCase
{
private $captcha;
protected $width = 200;
protected $height = 70;
public function setUp()
{
$this->captcha = new Captcha();
}
/**
* @TODO: give a path to custom font as a param
*/
public function testGetImage()
{
$token = $this->captcha->getToken();
$image = $this->captcha->getImage($token);
$this->assertNotNull($image);
$my_image = $this->createBlankImage();
$this->assertNotSame($image, $my_image);
}
public function testGetImageWrongToken()
{
$token = $this->captcha->getToken();
$image = $this->captcha->getImage('tony');
$this->assertNotNull($image);
$my_image = $this->createBlankImage();
$this->assertSame($image, $my_image);
}
public function testGetImageEmptyCode()
{
$token = $this->captcha->getToken();
Session::set('_ccode', '');
$image = $this->captcha->getImage($token);
$this->assertNotNull($image);
$my_image = $this->createBlankImage();
$this->assertSame($image, $my_image);
}
public function testGetToken()
{
$token = $this->captcha->getToken();
$code = Session::get('_ccode');
$this->assertNotEmpty($token);
$this->assertNotEmpty($code);
$this->assertSame(5, strlen($code));
$this->assertSame(Session::get('_ctoken'), $token);
$this->assertSame(32, strlen($token));
}
public function testCheckCode()
{
$token = Session::get('_ctoken');
$code = Session::get('_ccode');
$this->assertFalse($this->captcha->checkCode($token . 'asd', $code));
$this->assertSame(Session::get('_ctoken'), $token);
$this->assertTrue($this->captcha->checkCode($token, $code));
$this->assertNull(Session::get('_ctoken'));
}
public function tearDown()
{
$sid = session_id();
if (!empty($sid)) {
Session::destroy();
}
}
private function createBlankImage()
{
$image = imagecreatetruecolor($this->width, $this->height);
$background = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $this->width, $this->height, $background);
ob_start();
imagejpeg($image, '', 100);
return ob_get_clean();
}
}

View File

@ -0,0 +1,43 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-27
*
* Unit tests for CaptchaValidator class
*/
require_once dirname(__FILE__) . '/../../session/Session.php';
require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../captcha/CaptchaValidator.php';
require_once dirname(__FILE__) . '/../../captcha/Captcha.php';
class CaptchaValidatorTest extends PHPUnit_Framework_TestCase
{
/**
* @TODO: CaptchaValidator->isValid() - $value param not used
*/
public function testIsValid()
{
$captcha = new Captcha();
$token = $captcha->getToken();
$code = Session::get('_ccode');
$validator = new CaptchaValidator();
$this->assertTrue($validator->isValid(null, array('ctoken' => $token, 'ccode' => $code)));
$this->assertFalse($validator->isValid(null, array('ctoken' => $token . 'asd', 'ccode' => $code)));
$this->assertSame('Entered code wrong', $validator->getMessage());
}
public function testIsValidInvalid()
{
$validator = new CaptchaValidator();
$this->assertFalse($validator->isValid(null, array()));
$this->assertSame('Entered code wrong', $validator->getMessage());
}
}

120
Tests/classes/EnvTest.php Normal file
View File

@ -0,0 +1,120 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-26
*
* Unit tests for Env class
*/
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../app/router/Router.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
class EnvTest extends PHPUnit_Framework_TestCase
{
/**
* @runInSeparateProcess
*/
public function testGetRequestUri()
{
Config::set('DEBUG', false);
$_SERVER['REQUEST_URI'] = '/test/index.php?id=1&test=wet&id_theme=512';
$this->assertSame('/test/index.php', Env::getRequestUri());
$_SERVER['REQUEST_URI'] = '/tes?t/index.php?id=1&test=wet&id_theme=512';
$this->assertSame('/test/index.php', Env::getRequestUri());
}
/**
* @runInSeparateProcess
*/
public function testTrimBaseRequestUri()
{
Config::set('DEBUG', false);
$class = new ReflectionClass('Env');
$this->started = $class->getProperty('request');
$this->started->setAccessible(true);
$this->started->setValue(null, array());
FrontController::getInstance()->setBaseUrl('/test');
$_SERVER['REQUEST_URI'] = '/test/index.php?id=1&test=wet&id_theme=512';
$this->assertSame('/index.php', Env::getRequestUri(true));
}
public function testServer()
{
$this->assertSame($_SERVER, Env::Server());
$this->assertSame($_SERVER['DOCUMENT_ROOT'], Env::Server('DOCUMENT_ROOT'));
$this->assertNotEmpty(Env::Server());
$this->assertArrayHasKey('DOCUMENT_ROOT', Env::Server());
}
public function testCookie()
{
$this->assertTrue(Env::setCookie('var', 'value', 20));
$_COOKIE['var'] = 'value';
$this->assertSame(array('var' => 'value'), Env::Cookie());
$this->assertSame('value', Env::Cookie('var'));
$this->assertSame('default', Env::Cookie('new', 'default'));
}
public function testPost()
{
$_POST['var'] = 'value';
$this->assertSame(array('var' => 'value'), Env::Post());
$this->assertSame('value', Env::Post('var'));
$this->assertSame('default', Env::Post('new', 'default'));
}
public function testGet()
{
$_GET['var'] = 'value';
$this->assertSame(array('var' => 'value'), Env::Get());
$this->assertSame('value', Env::Get('var'));
$this->assertSame('default', Env::Get('new', 'default'));
}
public function testFiles()
{
$this->assertSame('default', Env::Files('file.txt', 'default'));
$this->assertSame(array(), Env::Files());
}
public function testUnsetFiles()
{
unset($_FILES);
$this->assertSame('default', Env::Files('file.txt', 'default'));
$_FILES['file'] = array('name' => 'files', 'path' => '/');
$this->assertSame(array('name' => 'files', 'path' => '/'), Env::Files('file', 'default'));
$this->assertSame('files', Env::Files('file', 'empty', 'name'));
}
public function testParams()
{
Env::setParams(array('name' => 'tony', 'age' => 21));
$this->assertSame(array('name' => 'tony', 'age' => 21), Env::getParam());
Env::setParams(array('sex' => 'male'));
$this->assertSame(array('name' => 'tony', 'age' => 21, 'sex' => 'male'), Env::getParam());
$this->assertSame('tony', Env::getParam('name'));
$this->assertSame('default', Env::getParam('height', 'default'));
Env::setParam('surname', 'grebnev');
$this->assertSame('grebnev', Env::getParam('surname'));
}
public function tearDown()
{
$env = new ReflectionClass('Env');
$params = $env->getProperty('params');
$params->setAccessible(true);
$params->setValue('Env', array());
}
}

View File

@ -0,0 +1,163 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-26
*
* Unit tests for Format class
*/
require_once dirname(__FILE__) . '/../../classes/Format.class.php';
class FormatTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
}
public function testCurrency()
{
$this->assertSame('руб.', Format::getCurrency());
Format::setCurrencySymbol('usd');
$this->assertSame('usd', Format::getCurrency());
}
/**
* @TODO: ???WHY??? itn2Money - utf non-breaking space + &nbsp;
*/
public function testInt2Money()
{
$a = '2 000&nbsp;руб.';
$b = Format::int2money(200000, true, false);
//$this->printStr($a);
//$this->printStr($b);
$this->assertSame('2' . chr(0xC2) . chr(0xA0) . '000&nbsp;руб.', Format::int2money(200000, true, false));
$this->assertSame('20 000,00', Format::int2money(2000000, false));
Format::setCurrencySymbol('usd');
$this->assertSame('200,00&nbsp;usd', Format::int2money(20000, true));
}
public function testMoney2Int()
{
$this->assertSame(20000, Format::money2int('200,00', false));
$this->assertSame(20000, Format::money2int('200', false));
$this->assertSame(2000, Format::money2int('2 000руб.'));
}
public function testInt2Time()
{
$time = 14 * 60 * 60 + 44 * 60 + 24;
$this->assertSame('14:44:24', Format::int2time($time));
$this->assertSame('00:00:00', Format::int2time());
}
public function testInt2Date()
{
$this->assertSame(date('H:i d.m.Y', 0), Format::int2date());
$this->assertSame(date('H:i d.m.Y'), Format::int2date(time()));
$this->assertSame(date('d.m.Y'), Format::int2date(time(), false));
$this->assertSame('20.04.2011', Format::int2date(strtotime('20 April 2011'), false));
$this->assertSame('21:10 20.04.2011', Format::int2date(strtotime('21:10:30 20 April 2011')));
}
public function testInt2rusDate()
{
$this->assertSame('10 января 1990', Format::int2rusDate(strtotime('10 January 1990')));
$this->assertSame('19:10 10 января 1990', Format::int2rusDate(strtotime('19:10:59 10 January 1990'), true));
}
public function testSetTimezoneOffset()
{
Format::setTimezoneOffset(3);
$class = new ReflectionClass('Format');
$offset = $class->getProperty('timezone_offset');
$offset->setAccessible(true);
$this->assertSame(3, $offset->getValue());
}
public function testSetDateTimeFormat()
{
Format::setDateFormat('H_i d::m::Y', 'd--m--Y');
$this->assertSame('14_22 20::04::2011', Format::int2date(strtotime('14:22:00 20 April 2011')));
$this->assertSame('20--04--2011', Format::int2date(strtotime('14:22:00 20 April 2011'), false));
}
public function testSetTodayFormat()
{
Format::setTodayFormat('H_i d::m::Y', 'd--m--Y');
$this->assertSame(date('H_i d::m::Y', strtotime('+2hours' )), Format::int2date(strtotime('+2 hours')));
$this->assertSame(date('d--m--Y', strtotime('+2hours' )), Format::int2date(strtotime('+2 hours'), false));
}
public function testTime2Int()
{
$time = 14 * 60 * 60 + 44 * 60 + 24;
$this->assertSame($time, Format::time2int('14:44:24'));
$this->assertSame(14, Format::time2int('14:44'));
$this->assertSame(14, Format::time2int('14:44:32:53:12'));
}
public function testDate2Int()
{
$this->assertSame(strtotime('2 Jan 2010'), Format::date2int('2 Jan 2010'));
}
public function testInt2Phone()
{
$this->assertSame('777-77-77', Format::int2phone(7777777));
$this->assertSame('(123) 456-78-90', Format::int2phone(1234567890));
$this->assertSame('', Format::int2phone(12890));
$this->assertSame('', Format::int2phone('asdas'));
}
/**
* @TODO: change name, check values(only Moscow???)
*/
public function testPhone2Int()
{
$this->assertSame('4951234567', Format::phone2int('123-45-67'));
$this->assertSame('9261234567', Format::phone2int('926-123-45-67'));
$this->assertSame('', Format::phone2int('8-926-123-45-67'));
$this->assertSame('', Format::phone2int('12-45-67'));
$this->assertSame('', Format::phone2int('not a phone'));
}
public function testBytes2MB()
{
$this->assertSame('1МБ', Format::bytes2MB(1048576));
}
public function testBytes2KB()
{
$this->assertSame('2КБ', Format::bytes2KB(2048));
}
public function tearDown()
{
Format::setCurrencySymbol('руб.');
Format::setTimezoneOffset(0);
Format::setDateFormat('H:i d.m.Y', 'd.m.Y');
Format::setTodayFormat('H:i d.m.Y', 'd.m.Y');
}
private function printStr($a)
{
echo PHP_EOL;
for($i = 0; $i < strlen($a); $i++) {
echo sprintf(' 0x%X ', ord($a[$i]));
}
echo PHP_EOL;
}
}

View File

@ -0,0 +1,37 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for Error404Exception class
*/
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHTTPException.php';
require_once dirname(__FILE__) . '/../../exception/Error404Exception.php';
class Error404ExceptionTest extends PHPUnit_Framework_TestCase
{
public function testError404Exception()
{
$this->setExpectedException('Error404Exception', 404);
throw new Error404Exception();
}
public function testError404ExceptionMessage()
{
$this->setExpectedException('Error404Exception', 'Error404Exception message', 404);
throw new Error404Exception('Error404Exception message', 10);
}
public function testError404ExceptionWithPrevious()
{
$this->setExpectedException('Error404Exception', 'Error404Exception message', 404);
throw new Error404Exception('Error404Exception message', 10, new ErrorException('Error message'));
}
}

View File

@ -0,0 +1,106 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for Error404Exception class
*/
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHTTPException.php';
require_once dirname(__FILE__) . '/../../exception/Error404Exception.php';
class ErrorHTTPExceptionTest extends PHPUnit_Framework_TestCase
{
public function testErrorHTTPException()
{
$this->setExpectedException('ErrorHTTPException', 404);
throw new ErrorHTTPException('Some error occurred', 400);
}
public function testErrorHTTPExceptionMessage()
{
$this->setExpectedException('ErrorHTTPException', 'ErrorHTTPException message', 410);
throw new ErrorHTTPException('ErrorHTTPException message', 410);
}
public function testErrorHTTPExceptionWithPrevious()
{
$this->setExpectedException('ErrorHTTPException', 'ErrorHTTPException message', 500);
throw new ErrorHTTPException('ErrorHTTPException message', 500, new ErrorException('Error message'));
}
/**
* @dataProvider providerHTTPCode
*/
public function testGetHTTPHeader($message, $code, $header)
{
try {
throw new ErrorHTTPException($message, $code, new ErrorException('Error message'));
}
catch (ErrorHTTPException $e) {
$this->assertSame($header, $e->getHTTPHeader());
$this->assertSame($message, $e->getMessage());
$this->assertSame($code, $e->getCode());
$this->assertEquals(new ErrorException('Error message'), $e->getPrevious());
}
}
public function providerHTTPCode()
{
return array(
array('ErrorHTTPException message for 400', 400, 'HTTP/1.0 400 Bad Request'),
array('ErrorHTTPException message for 402', 402, 'HTTP/1.0 402 Payment Required'),
array('ErrorHTTPException message for 403', 403, 'HTTP/1.0 403 Forbidden'),
array('ErrorHTTPException message for 404', 404, 'HTTP/1.0 404 Not Found'),
array('ErrorHTTPException message for 410', 410, 'HTTP/1.0 410 Gone'),
array('ErrorHTTPException message for 500', 500, 'HTTP/1.0 500 Internal Server Error'),
array('ErrorHTTPException message for 501', 501, 'HTTP/1.0 501 Not Implemented'),
array('ErrorHTTPException message for 503', 503, 'HTTP/1.0 503 Service Unavailable'),
);
}
public function testErrorHTTPException200()
{
try {
throw new ErrorHTTPException('ErrorHTTPException message', 200, new ErrorException('Error message'));
}
catch (ErrorHTTPException $e) {
$this->fail();
}
catch (GeneralException $e) {
$this->assertSame('Can\'t send 200 via ErrorHTTPException', $e->getMessage());
}
}
public function testErrorHTTPExceptionBadCode()
{
try {
throw new ErrorHTTPException('ErrorHTTPException message', 100, new ErrorException('Error message'));
}
catch (ErrorHTTPException $e) {
$this->fail();
}
catch (GeneralException $e) {
$this->assertSame('Incorrect HTTP code 100.', $e->getMessage());
}
}
public function testErrorHTTPExceptionGoodCode()
{
try {
throw new ErrorHTTPException('ErrorHTTPException message', 400, new ErrorException('Error message'));
}
catch (ErrorHTTPException $e) {
$this->assertSame(400, $e->getCode());
}
catch (GeneralException $e) {
$this->fail();
}
}
}

View File

@ -0,0 +1,179 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for ErrorHandler class
*/
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../session/Session.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
class ErrorHandlerTest extends PHPUnit_Framework_TestCase
{
public $old_eh = array('PHPUnit_Util_ErrorHandler', 'handleError');
protected $log_file_name = 'error_log_file';
public function setUp()
{
set_error_handler(array('ErrorHandler', 'error_handler'));
ob_start();
}
public function testErrorHandlerInit()
{
$my_eh = array('ErrorHandler', 'error_handler');
ErrorHandler::init();
$eh = set_error_handler($my_eh);
$this->assertInternalType('array', $eh);
$this->assertSame($eh, $my_eh);
}
public function testHandleError()
{
$this->setExpectedException('ErrorException', 'test error');
trigger_error("test error", E_USER_ERROR);
}
public function testHandleAt()
{
$my_eh = array('ErrorHandler', 'error_handler');
ErrorHandler::init();
set_error_handler($my_eh);
$var = '';
$ok = @$var['some'];
$this->assertSame('', $var);
ob_start();
$this->setExpectedException('ErrorException');
$ex = $var['some'];
}
/**
* @TODO: ErrorHandler->wrapTrace() not used
*/
public function testShowDebug()
{
try {
throw new ErrorException("test error", E_USER_ERROR);
}
catch (ErrorException $e) {
$_SESSION['some'] = 'value';
$result = ErrorHandler::showDebug($e);
$this->assertNotEmpty($result);
$this->assertStringStartsWith('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', $result);
$this->assertStringEndsWith('</html>', $result);
}
}
/**
* @TODO: ErrorHandler::wrapTrace not used
* @TODO: nl2br() adds html <br /> but leaves original linebreak line \n
*/
public function testWrapTrace()
{
$class = new ReflectionClass('ErrorHandler');
$method = $class->getMethod('WrapTrace');
$method->setAccessible(true);
$result = $method->invoke(null, "first line\nsecond line");
$this->assertSame("<code>first line<br />\nsecond line</code>", $result);
$result = $method->invoke(null, "first line\r\nsecond line");
$this->assertSame("<code>first line<br />\r\nsecond line</code>", $result);
$result = $method->invoke(null, "first line\r\n\r\nsecond line");
$this->assertSame("<code>first line<br />\r\n<br />\r\nsecond line</code>", $result);
}
/**
* @runInSeparateProcess
*/
public function testLogErrorDefaultException()
{
$ex = new Exception('message', 123);
ini_set('error_log', $this->log_file_name);
ErrorHandler::logError($ex);
$log = file_get_contents($this->log_file_name);
$this->assertContains('PHP Unknown Error: Exception: message in ', $log);
}
/**
* @runInSeparateProcess
*/
public function testLogErrorDefaultExceptionWithHTTP()
{
$_SERVER['REQUEST_METHOD'] = 'GET';
$_SERVER['REQUEST_URI'] = '/somelongurl';
$_SERVER['HTTP_REFERER'] = 'http://referrer/url';
$this->assertEquals('GET', ENV::Server('REQUEST_METHOD'));
$this->assertEquals('/somelongurl', ENV::Server('REQUEST_URI'));
$this->assertEquals('http://referrer/url', ENV::Server('HTTP_REFERER'));
$ex = new Exception('message', 123);
ini_set('error_log', $this->log_file_name);
ErrorHandler::logError($ex);
$log = file_get_contents($this->log_file_name);
$this->assertContains('PHP Unknown Error: Exception: message in ', $log);
$this->assertContains('URL: GET /somelongurl, referrer: http://referrer/url', $log);
}
/**
* @runInSeparateProcess
*/
public function testLogErrorCustomException()
{
$ex = new LogicException('Logic', 333);
ini_set('error_log', $this->log_file_name);
ErrorHandler::logError($ex);
$log = file_get_contents($this->log_file_name);
$this->assertContains('PHP Unknown Error: LogicException: Logic in ', $log);
}
/**
* @runInSeparateProcess
*/
public function testLogErrorErrorExceptionNotice()
{
$ex = new ErrorException('message', 321, E_NOTICE);
ini_set('error_log', $this->log_file_name);
ErrorHandler::logError($ex);
$log = file_get_contents($this->log_file_name);
$this->assertContains('PHP Notice: message in ', $log);
}
/**
* @runInSeparateProcess
*/
public function testLogErrorErrorExceptionWarning()
{
$ex = new ErrorException('message', 321, E_WARNING);
ini_set('error_log', $this->log_file_name);
ErrorHandler::logError($ex);
$log = file_get_contents($this->log_file_name);
$this->assertContains('PHP Warning: message in ', $log);
}
/**
* @runInSeparateProcess
*/
public function testLogErrorErrorExceptionFatal()
{
$ex = new ErrorException('message', 321, E_ERROR);
ini_set('error_log', $this->log_file_name);
ErrorHandler::logError($ex);
$log = file_get_contents($this->log_file_name);
$this->assertContains('PHP Fatal Error: message in ', $log);
}
public function tearDown()
{
if (file_exists($this->log_file_name) && is_writable($this->log_file_name)) {
unlink($this->log_file_name);
}
ini_set('error_log', 'php://stderr');
set_error_handler($this->old_eh);
}
}

View File

@ -0,0 +1,29 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for GeneralException class
*/
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class GeneralExceptionTest extends PHPUnit_Framework_TestCase
{
public function testGeneralException()
{
$this->setExpectedException('GeneralException');
throw new GeneralException();
}
public function testGeneralExceptionMessage()
{
$this->setExpectedException('GeneralException', 'GeneralException message', 1);
throw new GeneralException('GeneralException message', 1);
}
}

View File

@ -0,0 +1,28 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-24
*
* Unit tests for InitializationException class
*/
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class InitializationExceptionTest extends PHPUnit_Framework_TestCase
{
public function testInitializationException()
{
$this->setExpectedException('InitializationException');
throw new InitializationException();
}
public function testInitializationExceptionMessage()
{
$this->setExpectedException('InitializationException', 'InitializationException message', 1);
throw new InitializationException('InitializationException message', 1);
}
}

View File

@ -0,0 +1,336 @@
<?php
/**
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage form
* @since 2010-04-25
*/
require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../validator/NotEmptyValidator.php';
require_once dirname(__FILE__) . '/../../validator/RegexValidator.php';
require_once dirname(__FILE__) . '/../../validator/EmailValidator.php';
require_once dirname(__FILE__) . '/../../form/FormField.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class FormFieldTest extends PHPUnit_Framework_TestCase
{
public function testSetRequired()
{
$form_field = new FormField();
$this->assertTrue($form_field->isRequired());
$return_object = $form_field->setRequired(false);
$this->assertInstanceOf('FormField', $return_object);
$this->assertSame($form_field, $return_object);
$this->assertFalse($form_field->isRequired());
}
public function testSetIgnored()
{
$form_field = new FormField();
$this->assertFalse($form_field->isIgnored());
$return_object = $form_field->setIgnored(true);
$this->assertInstanceOf('FormField', $return_object);
$this->assertSame($form_field, $return_object);
$this->assertTrue($form_field->isIgnored());
}
public function testIsIgnored()
{
$class_name = 'FormField';
$form_field = new $class_name();
$this->assertFalse($form_field->isIgnored());
$form_field->setIgnored(true);
$this->assertTrue($form_field->isIgnored());
}
public function testIsRequired()
{
$class_name = 'FormField';
$form_field = new $class_name();
$this->assertTrue($form_field->isRequired());
$form_field->setRequired(false);
$this->assertFalse($form_field->isRequired());
}
public function testAddValidators()
{
$validators = array(
'NotEmpty' => new NotEmptyValidator(),
'Email' => new EmailValidator()
);
$this->assertInstanceOf('iValidator', $validators['NotEmpty']);
$this->assertInstanceOf('iValidator', $validators['Email']);
$form_field = new FormField();
$return_object = $form_field->addValidators($validators);
$array = array('NotEmptyValidator' => new NotEmptyValidator(), 'EmailValidator' => new EmailValidator());
$this->assertAttributeEquals($array, 'validators', $form_field);
$this->assertSame($form_field, $return_object);
}
public function testAddValidatorObject()
{
$validator = new NotEmptyValidator();
$array = array('NotEmptyValidator' => new NotEmptyValidator());
$form_field = new FormField();
$return_object = $form_field->addValidator($validator);
$this->assertAttributeEquals($array, 'validators', $form_field);
$this->assertSame($form_field, $return_object);
}
public function testAddValidatorString()
{
$form_field = new FormField();
$return_object = $form_field->addValidator('NotEmpty');
$array = array('NotEmptyValidator' => new NotEmptyValidator());
$this->assertAttributeEquals($array, 'validators', $form_field);
$this->assertSame($form_field, $return_object);
}
public function testAddValidatorElse()
{
$validator = true;
$tmp_form_field = new FormField();
// @TODO Fix exception type
$this->setExpectedException('InitializationException', 'Invalid validator provided to addValidator; must be string or iValidator'); // Text of Exception
$tmp_form_field->addValidator($validator);
}
public function testAddFilters()
{
$array = array('loginFilter' => new loginFilter(), 'passwordFilter' => new passwordFilter());
$this->assertInstanceOf('iFilter', $array['loginFilter']);
$this->assertInstanceOf('iFilter', $array['passwordFilter']);
$form_field = new FormField();
$return_object = $form_field->addFilters($array);
$this->assertAttributeEquals($array, 'filters', $form_field);
$this->assertSame($form_field, $return_object);
}
public function testAddFilterObject()
{
$filter = new loginFilter();
$array = array('loginFilter' => new loginFilter());
$this->assertInstanceOf('iFilter', new loginFilter());
$form_field = new FormField();
$return_object = $form_field->addFilter($filter);
$this->assertAttributeEquals($array, 'filters', $form_field);
$this->assertSame($form_field, $return_object);
}
public function testAddFilterString()
{
$form_field = new FormField();
$array = array('loginFilter' => new loginFilter());
$this->assertInstanceOf('iFilter', new loginFilter());
$return_object = $form_field->addFilter('login');
$this->assertAttributeEquals($array, 'filters', $form_field);
$this->assertSame($form_field, $return_object);
}
public function testAddFilterElse()
{
$filter = new NotEmptyValidator();
$form_field = new FormField();
// @TODO Fix exception type
$this->setExpectedException('InitializationException', 'Invalid filter provided to addFilter; must be string or iFilter'); // Text of exception
$form_field->addFilter($filter);
}
public function testGetValueArray()
{
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$form_field = new FormField();
$form_field->addFilter('Login');
$this->assertTrue($form_field->isValid($test_array));
$this->assertAttributeInternalType('array', 'value', $form_field);
$value = $form_field->getValue();
$this->assertArrayHasKey('login', $value);
$this->assertArrayHasKey('password', $value);
$this->assertSame(array('login' => 'login',
'password' => ''), $value);
}
public function testGetValueStringCorrect()
{
$test_string = 'login';
$form_field = new FormField();
$form_field->addFilter('Login');
$this->assertTrue($form_field->isValid($test_string));
$this->assertAttributeNotInternalType('array', 'value', $form_field);
$this->assertSame('login', $form_field->getValue());
}
public function testGetValueStringIncorrect()
{
$test_string = 'password';
$form_field = new FormField();
$form_field->addFilter('Login');
$this->assertTrue($form_field->isValid($test_string));
$this->assertAttributeNotInternalType('array', 'value', $form_field);
$this->assertSame('', $form_field->getValue());
}
public function testGetMessageDefault()
{
$form_field = new FormField();
$this->assertFalse($form_field->getMessage());
$form_field->addValidator('NotEmpty');
$this->assertFalse($form_field->isValid(''));
$this->assertSame('Value is required and can\'t be empty', $form_field->getMessage());
}
public function testGetMessageCustom()
{
$message = 'Test message';
$form_field = new FormField($message);
$this->assertFalse($form_field->getMessage());
$form_field->addValidator('NotEmpty');
$this->assertFalse($form_field->isValid(''));
$this->assertSame($message, $form_field->getMessage());
}
public function testIsValidArrayMissingDefaultMessage()
{
$test_array = array(
'login' => '',
'password' => ''
);
$form_field = new FormField();
$form_field->addValidator('NotEmpty');
$this->setExpectedException('InitializationException', 'Define default message for array fields');
$form_field->isValid($test_array);
}
public function testIsValidArrayMissingCustomMessage()
{
$message = 'Test message';
$test_array = array(
'login' => '',
'password' => ''
);
$form_field = new FormField($message);
$return_object = $form_field->addValidator('NotEmpty');
$array = array('NotEmptyValidator' => new NotEmptyValidator());
$this->assertAttributeEquals($array, 'validators', $form_field);
$this->assertSame($form_field, $return_object);
$this->assertFalse($form_field->isValid($test_array));
$this->assertSame($message, $form_field->getMessage());
}
public function testIsValidMissingNotRequired()
{
$form_field = new FormField();
$form_field->setRequired(false);
$this->assertTrue($form_field->isValid(''));
}
public function testIsValidArray()
{
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$validator = new NotEmptyValidator();
$form_field = new FormField();
$return_object = $form_field->addValidator($validator);
$this->assertTrue($form_field->isValid($test_array));
}
public function testIsValidScalar()
{
$test = 'password';
$validator = new NotEmptyValidator();
$form_field = new FormField();
$return_object = $form_field->addValidator($validator);
$this->assertTrue($form_field->isValid($test));
}
public function testGetSourceValue()
{
$test_array = array(
'login' => ' login ',
'password' => ''
);
$form_field = new FormField('Custom message');
$form_field->addFilter('login');
$form_field->addValidator('NotEmpty');
$this->assertFalse($form_field->isValid($test_array));
$this->assertSame(array('login' => 'login', 'password' => ''), $form_field->getValue());
$this->assertNotSame($test_array, $form_field->getValue());
$this->assertSame($test_array, $form_field->getSourceValue());
}
public function testFilterValue()
{
$input = ' login ';
$form_field = new FormField();
$form_field->isValid($input);
$form_field->addFilter('login');
$lf = new loginFilter();
$this->assertSame($form_field->getValue(), $lf->filter($input));
}
}
interface iFilter
{
public function isValid($value, $context = null);
public function filter($value);
public function getMessage();
}
class loginFilter implements iFilter
{
public function filter($value)
{
$value = trim($value);
if ($value === 'login') {
return $value;
}
return '';
}
public function isValid($value, $context = null)
{
}
public function getMessage()
{
}
}
class passwordFilter implements iFilter
{
public function filter($value)
{
return $value;
}
public function isValid($value, $context = null)
{
}
public function getMessage()
{
}
}

266
Tests/form/FormTest.php Normal file
View File

@ -0,0 +1,266 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-07
*
* Unit tests for Form class
*/
require_once dirname(__FILE__) . '/../../form/Form.php';
require_once dirname(__FILE__) . '/../../form/FormField.php';
require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../validator/RegexValidator.php';
require_once dirname(__FILE__) . '/../../validator/NotEmptyValidator.php';
require_once dirname(__FILE__) . '/../../validator/EmailValidator.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class FormTest extends PHPUnit_Framework_TestCase
{
public function testAddFieldEmptyMessage()
{
$form_field = new FormField();
$stub = $this->getMockForAbstractClass('Form');
$method = new ReflectionMethod('Form', 'addField');
$method->setAccessible(true);
$return_object = $method->invokeArgs($stub, array('login'));
$this->assertInstanceOf('FormField', $return_object);
$this->assertEquals($form_field, $return_object);
}
public function testAddFieldWithMessage()
{
$message = 'Test message';
$form_field = new FormField($message);
$stub = $this->getMockForAbstractClass('Form');
$method = new ReflectionMethod('Form', 'addField');
$method->setAccessible(true);
$return_object = $method->invokeArgs($stub, array('login', $message));
$this->assertInstanceOf('FormField', $return_object);
$this->assertEquals($form_field, $return_object);
$this->assertAttributeEquals($message, 'default_message', $return_object);
}
public function testIsValidWithNotArray()
{
$form = new NotEmptyForm();
// @TODO Fix exception type
$this->setExpectedException('InitializationException', 'Form::Form::isValid expects an array');
$form->isValid('');
}
public function testIsValidCorrectFields()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$this->assertSame(1, $form->isValid($test_array));
}
public function testIsValidMissingField()
{
$form = new NotEmptyForm();
$test_array = array(
'password' => 'password'
);
$this->assertSame(0, $form->isValid($test_array));
$data['messages'] = $form->getMessages();
$data['values'] = $form->getSourceValues();
$this->assertSame($_SESSION['NotEmptyForm'], $data);
}
public function testGetValues()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$this->assertSame(1, $form->isValid($test_array));
$this->assertSame($test_array, $form->getValues());
}
public function testGetValuesWithFieldIsIgnored()
{
$form = new WithIgnoredFieldForm();
$test_array = array(
'login' => 'login',
'password' => 'password',
'remember' => true
);
$this->assertSame(1, $form->isValid($test_array));
$this->assertSame(array(
'login' => 'login',
'password' => 'password'), $form->getValues());
$this->assertSame($test_array, $form->getSourceValues());
}
public function testGetValueCorrect()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$this->assertSame(1, $form->isValid($test_array));
$this->assertSame($test_array['login'], $form->getValue('login'));
$this->assertSame($test_array['password'], $form->getValue('password'));
}
public function testGetValueEmpty()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => 'login'
);
$this->assertSame(0, $form->isValid($test_array));
$this->assertSame('login', $form->getValue('login'));
$this->assertNull($form->getValue('password'));
}
public function testGetValueMissing()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$this->assertSame(1, $form->isValid($test_array));
$this->assertSame('login', $form->getValue('login'));
$this->assertSame('password', $form->getValue('password'));
$this->assertFalse($form->getValue('missing'));
}
public function testGetMessageTypeCorrect()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$this->assertSame(1, $form->isValid($test_array));
$this->assertSame('success', Form::SUCCESS);
$this->assertSame($form->getMessageType(), Form::SUCCESS);
}
public function testGetMessageTypeMissing()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => '',
'password' => ''
);
$this->assertSame(0, $form->isValid($test_array));
$this->assertSame('error', Form::ERROR);
$this->assertSame($form->getMessageType(), Form::ERROR);
}
public function testGetMessageCorrect()
{
$form = new NotEmptyForm();
$message = 'Test message';
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$this->assertSame(1, $form->isValid($test_array));
$form->setSuccessMessage($message);
$this->assertSame($message, $form->getMessage());
}
public function testGetMessageMissing()
{
$form = new NotEmptyForm();
$message = 'Test message';
$test_array = array(
'login' => ''
);
$this->assertSame(0, $form->isValid($test_array));
$form->setErrorMessage($message);
$this->assertSame($message, $form->getMessage());
}
public function testSetSuccessMessage()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => 'login',
'password' => 'password'
);
$this->assertSame(1, $form->isValid($test_array));
$message = 'Form data valid';
$form->setSuccessMessage($message);
$this->assertSame($message, $form->getMessage());
}
public function testSetErrorMessage()
{
$form = new NotEmptyForm();
$test_array = array(
'login' => ''
);
$this->assertSame(0, $form->isValid($test_array));
$message = 'Form data invalid';
$form->setErrorMessage($message);
$this->assertSame($message, $form->getMessage());
}
}
class NotEmptyForm extends Form
{
public function init()
{
$validator = new NotEmptyValidator();
$validator->setMessage('Enter login name.');
$this->addField('login')->addValidator($validator);
$validator = new NotEmptyValidator();
$validator->setMessage('Enter your password.');
$this->addField('password')->addValidator($validator);
}
}
class WithIgnoredFieldForm extends Form
{
public function init()
{
$validator = new NotEmptyValidator();
$validator->setMessage('Enter login name.');
$this->addField('login')->addValidator($validator);
$validator = new NotEmptyValidator();
$validator->setMessage('Enter your password.');
$this->addField('password')->addValidator($validator);
$validator = new NotEmptyValidator();
$validator->setMessage('Remember');
$this->addField('remember')->addValidator($validator)->setIgnored(true);
}
}

View File

@ -0,0 +1,95 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-07
*
* Unit tests for Form class
*/
require_once dirname(__FILE__) . '/../../view/iView.php';
require_once dirname(__FILE__) . '/../../view/PHPView.php';
require_once dirname(__FILE__) . '/../../view/helpers/ViewHelper.php';
require_once dirname(__FILE__) . '/../../form/FormViewHelper.php';
require_once dirname(__FILE__) . '/../../session/Session.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class FormViewHelperTest extends PHPUnit_Framework_TestCase
{
public function setUp()
{
$this->view = new PHPView(array('path' => '/path/to/templates'));
$this->formname = 'formname';
$this->test_array = array('values' => array('key1' => 'val"ue1'), 'messages' => array('field1' => 'Can\'t serialize "value"'));
Session::set($this->formname, $this->test_array);
}
public function testFormWithNotViewInstance()
{
// @TODO check, that iView used in construct
$form = new FormViewHelper('something');
$this->assertInstanceOf('FormViewHelper', $form);
}
public function testFormUnsetFormName()
{
$helper = new FormViewHelper($this->view);
$this->setExpectedException('InitializationException', 'Form name required for helper init');
// @TODO Refactor for form name is required param?
$helper->form();
}
public function testFormEmptyFormName()
{
$helper = new FormViewHelper($this->view);
$this->setExpectedException('InitializationException', 'Form name required for helper init');
$helper->form('');
}
public function testFillData()
{
$helper = new FormViewHelper($this->view);
$this->assertAttributeSame(null, 'data', $helper);
$return_obj = $helper->form($this->formname);
$this->assertAttributeSame($this->test_array, 'data', $helper);
$this->assertNull(Session::get($this->formname));
$this->assertSame($helper, $return_obj);
}
public function testValueSet()
{
$helper = new FormViewHelper($this->view);
$helper->form($this->formname);
$value = $helper->value('key1');
$this->assertSame($this->view->escape('val"ue1'), $value);
}
public function testValueDefault()
{
$helper = new FormViewHelper($this->view);
$helper->form($this->formname);
$value = $helper->value('key_not_exist', 'default"');
$this->assertSame($this->view->escape('default"'), $value);
}
public function testMessageSet()
{
$helper = new FormViewHelper($this->view);
$helper->form($this->formname);
$value = $helper->message('field1');
$this->assertSame('<span class="error">' . $this->view->escape('Can\'t serialize "value"') . '</span>', $value);
}
public function testMessageNotSet()
{
$helper = new FormViewHelper($this->view);
$helper->form($this->formname);
$value = $helper->message('key_not_exist', 'default"');
$this->assertSame('', $value);
}
}

189
Tests/i18n/I18NTest.php Normal file
View File

@ -0,0 +1,189 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-31
*
* Unit tests for I18N class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../i18n/I18N.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
/**
* @runTestsInSeparateProcesses
*/
class I18NTest extends PHPUnit_Framework_TestCase
{
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setConstants();
$this->setPreserveGlobalState(false);
return parent::run($result);
}
/**
* @runInSeparateProcess
*/
public function testInit()
{
$this->setConstants();
Config::set('I18N', array('locales' => array('ru' => 'ru-ru', 'us' => 'en-us')));
I18N::init();
$this->assertAttributeEquals(array('ru' => 'ru-ru', 'us' => 'en-us'), 'locales', 'I18N');
$this->assertAttributeEquals('ru-ru', 'locale', 'I18N');
}
public function testInitNoConfig()
{
Config::set('I18N', array('locales' => null));
$this->setExpectedException('InitializationException');
I18N::init();
}
/**
* @runInSeparateProcess
*/
public function testInitFullConfig()
{
$this->setConstants();
Config::set('I18N', array('locales' => array('ru' => 'ru-ru', 'en' => 'en_US'), 'bidi' => 'bidivalue', 'default' => 'ru'));
I18N::init();
$this->assertAttributeEquals('ru-ru', 'locale', 'I18N');
$this->assertAttributeEquals('bidivalue', 'bidi', 'I18N');
$this->assertAttributeEquals('ru', 'default', 'I18N');
}
/**
* @runInSeparateProcess
*/
public function testInitPostLangSet()
{
$this->setConstants();
$_POST['lang'] = 'en';
$_COOKIE['lang'] = 'en';
Config::set('I18N', array('locales' => array('ru' => 'ru-ru', 'en' => 'en_US'), 'bidi' => 'bidivalue', 'default' => 'ru'));
set_exit_overload(function() { return FALSE; });
I18N::init();
$this->assertAttributeEquals('en_US', 'locale', 'I18N');
unset_exit_overload();
}
/**
* @runInSeparateProcess
*/
public function testInitSetDefaultLangNotInLocales()
{
$this->setExpectedException('PHPUnit_Framework_Error');
$this->setConstants();
Config::set('I18N', array('locales' => array('rus' => 'ru_RU'), 'default' => 'ru'));
I18N::init();
$this->assertAttributeEquals('ru_RU', 'locale', 'I18N');
}
/**
* @runInSeparateProcess
*/
public function testInitServerLangConfigured()
{
$this->setConstants();
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'ru';
Config::set('I18N', array('locales' => array('ru_ru' => 'ru_RU', 'ru' => 'ru-ru', 'us' => 'en-us')));
I18N::init();
$this->assertAttributeEquals('ru-ru', 'locale', 'I18N');
}
/**
* @runInSeparateProcess
*/
public function testInitServerLangConfiguredWithWeights()
{
$this->setConstants();
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3';
Config::set('I18N', array('locales' => array('en_US' => 'en-us')));
I18N::init();
$this->assertAttributeEquals('en-us', 'locale', 'I18N');
}
/**
* @runInSeparateProcess
*/
public function testInitServerLangConfiguredWithWeightsNoLocale()
{
$this->setConstants();
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3';
Config::set('I18N', array('locales' => array('en' => 'en_US')));
I18N::init();
$this->assertAttributeEquals('en_US', 'locale', 'I18N');
}
/**
* @runInSeparateProcess
*/
public function testGetLang()
{
$this->setConstants();
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3';
Config::set('I18N', array('locales' => array('en' => 'en_US'), 'default' => 'ru'));
I18N::init();
$this->assertSame('en', I18N::getLang());
$this->assertSame('ru', I18N::getDefaultLang());
}
/**
* @runInSeparateProcess
*/
public function testLangs()
{
$this->setConstants();
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3';
Config::set('I18N', array('locales' => array('ru' => 'ru-ru'), 'default' => 'ru'));
I18N::init();
I18N::setLangs(array('en' => 'en-us', 'fr' => 'fr-fr'));
$this->assertSame(array('en' => 'en-us', 'fr' => 'fr-fr'), I18N::getLangs());
}
/**
* @runInSeparateProcess
*/
public function testLangName()
{
$this->setConstants();
$_SERVER['HTTP_ACCEPT_LANGUAGE'] = 'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3';
Config::set('I18N', array('locales' => array('ru' => 'ru-ru'), 'default' => 'ru'));
I18N::init();
I18N::setLangs(array('ru' => 'ru_ru', 'en' => 'en-us', 'fr' => 'fr-fr'));
$this->assertSame('ru_ru', I18N::getLangName());
$this->assertFalse(I18N::getLangName('br'));
}
private function setConstants()
{
if (!defined('PATH')) {
define('PATH', '/some/path/');
}
if (!defined('APP')) {
define('APP', '/some/app/');
}
}
}

View File

@ -0,0 +1,82 @@
<?php
/**
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 04-06-2012
* @user: agrebnev
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../layout/Layout.php';
require_once dirname(__FILE__) . '/../../layout/Error.layout.php';
/**
* @runTestsInSeparateProcesses
*/
class ErrorLayoutTest extends PHPUnit_Framework_TestCase
{
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
if (!class_exists('RouterMock')) {
$this->getMock('Router', array(), array(), 'RouterMock', false);
}
if (!class_exists('PHPViewMock')) {
$this->getMock('PHPView', array('fetch', 'append', 'prepend', 'assign', 'getTemplate'), array(), 'PHPViewMock', false);
}
set_new_overload(array($this, 'newCallback'));
}
public function testSetException()
{
Config::set('DEBUG', false);
$layout = new ErrorLayout();
$layout->setException(new GeneralException());
$this->assertAttributeInstanceOf('GeneralException', 'exception', $layout);
}
public function testExecute()
{
Config::set('DEBUG', false);
$action = $this->getMock('Action', array('fetch'));
$action->expects($this->once())
->method('fetch')
->will($this->returnValue('this is the result of Action::fetch()'));
$layout = new ErrorLayout();
$layout->fetch($action);
}
protected function newCallback($className)
{
switch ($className) {
case 'Router':
return 'RouterMock';
case 'PHPView':
return 'PHPViewMock';
default:
return $className;
}
}
public function tearDown()
{
unset_new_overload();
}
}

137
Tests/layout/LayoutTest.php Normal file
View File

@ -0,0 +1,137 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-31
*
* Unit tests for Layout class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../layout/Layout.php';
/**
* @runTestsInSeparateProcesses
*/
class LayoutTest extends PHPUnit_Framework_TestCase
{
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
if (!class_exists('RouterMock')) {
$this->getMock('Router', array(), array(), 'RouterMock', false);
}
if (!class_exists('PHPViewMock')) {
$this->getMock('PHPView', array('fetch', 'append', 'prepend', 'assign', 'getTemplate'), array(), 'PHPViewMock', false);
}
set_new_overload(array($this, 'newCallback'));
}
public function testConstruct()
{
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout');
$this->assertAttributeInstanceOf('PHPView', 'view', $layout);
}
public function testFetch()
{
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout');
$action = $this->getMock('Action', array('fetch'));
$action->expects($this->once())
->method('fetch')
->will($this->returnValue('this is the result of Action::fetch()'));
$this->assertNull($layout->fetch($action));
}
public function testFetchWithTemplate()
{
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout');
$class = new ReflectionClass('Layout');
$template = $class->getProperty('template');
$template->setAccessible(TRUE);
$this->assertAttributeEquals(null, 'template', $layout);
$template->setValue($layout, 'template');
$this->assertAttributeEquals('template', 'template', $layout);
$action = $this->getMock('Action', array('fetch'));
$action->expects($this->once())
->method('fetch')
->will($this->returnValue('this is the result of Action::fetch()'));
$this->assertNull($layout->fetch($action));
}
public function testAppend()
{
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout', array('append', 'prepend'), 'LayoutMock');
$action = $this->getMock('Action', array('fetch'));
$action->expects($this->exactly(3))
->method('fetch')
->will($this->returnValue(true));
$class = new ReflectionClass('LayoutMock');
$method = $class->getMethod('append');
$method->setAccessible(true);
$method->invoke($layout, 'var', $action);
$method = $class->getMethod('prepend');
$method->setAccessible(true);
$method->invoke($layout, 'var', $action);
$method = $class->getMethod('assign');
$method->setAccessible(true);
$method->invoke($layout, 'var', $action);
}
protected function newCallback($className)
{
switch ($className) {
case 'Router':
return 'RouterMock';
case 'PHPView':
return 'PHPViewMock';
default:
return $className;
}
}
public function tearDown()
{
// if (!is_null(Config::get('DEBUG'))) {
// $debug = Config::get('DEBUG') ? 'TRUE' : 'FALSE';
// echo PHP_EOL . __CLASS__ . ' DEBUG = ' . $debug . PHP_EOL;
// } else {
// echo PHP_EOL . __CLASS__ . ' ' . 'DEBUG NOT DEFINED' . PHP_EOL;
// }
unset_new_overload();
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-06
*
* Unit tests for CliLogger class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../logger/Logger.php';
require_once dirname(__FILE__) . '/../../logger/CliLogger.php';
class CliLoggerTest extends PHPUnit_Framework_TestCase
{
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
Config::set('Logger', array('logger' => 'CliLogger'));
}
/**
* @runInSeparateProcess
*/
public function testGetInstance()
{
$logger = Logger::getInstance();
$this->assertInstanceOf('CliLogger', $logger);
}
/**
* @runInSeparateProcess
*/
public function testLog()
{
Config::set('LOGGING', true);
Config::set('Logger', array('logger' => 'CliLogger'));
$logger = Logger::getInstance();
ob_start();
$logger->setPid(123);
$logger->log('new msg');
$out = ob_get_clean();
$this->assertContains('<123> new msg', $out);
}
public function tearDown()
{
$conf = Config::getInstance();
$conf->offsetUnset('Logger');
}
}

View File

@ -0,0 +1,113 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-06
*
* Unit tests for CliLogger class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../logger/Logger.php';
require_once dirname(__FILE__) . '/../../logger/FileLogger.php';
require_once 'vfsStream/vfsStream.php';
class FileLoggerTest extends PHPUnit_Framework_TestCase
{
protected $conf;
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
vfsStreamWrapper::register();
vfsStream::setup();
$root = vfsStream::create(array());
vfsStreamWrapper::setRoot($root);
Config::set('LOGGING', true);
$this->conf = array('logger' => 'FileLogger', 'filepath' => vfsStream::url('root/log.txt'));
Config::set('Logger', $this->conf);
if ($root->hasChild('log.txt')) {
$root->removeChild('log.txt');
}
}
/**
* @runInSeparateProcess
*/
public function testGetInstance()
{
$logger = Logger::getInstance();
$this->assertInstanceOf('FileLogger', $logger);
}
/**
* @runInSeparateProcess
*/
public function testCannotWrite()
{
Config::set('DEBUG', true);
$conf = array('logger' => 'FileLogger', 'filepath' => '/log.txt');
Config::set('Logger', $conf);
$this->setExpectedException('GeneralException', 'Could not open file /log.txt');
$logger = Logger::getInstance()->log('new msg');
$this->assertFileNotExists('log.txt');
}
/**
* @runInSeparateProcess
*/
public function testLog()
{
Config::set('DEBUG', true);
$this->assertFileNotExists($this->conf['filepath']);
$logger = Logger::getInstance();
$logger->setPid(123);
$logger->log('new msg');
$this->assertFileExists($this->conf['filepath']);
}
/**
* @runInSeparateProcess
*/
public function testDestruct()
{
Config::set('DEBUG', true);
$my_pid = posix_getpid();
$fd_command = 'lsof -n -p ' . $my_pid . ' | wc -l';
$fd_count_start = (int) `$fd_command`;
$logger = Logger::getInstance();
$logger->log('new msg');
$logger->log('new msg');
$logger->log('new msg');
$logger->log('new msg');
$logger->log('new msg');
$logger->log('new msg');
$logger->log('new msg');
$logger->log('new msg');
$logger->__destruct();
$this->assertAttributeEquals(null, 'handler', $logger);
$fd_count_end = (int) `$fd_command`;
$this->assertSame($fd_count_start, $fd_count_end);
}
public function tearDown()
{
$conf = Config::getInstance();
$conf->offsetUnset('Logger');
if (file_exists($this->conf['filepath'])) {
unlink($this->conf['filepath']);
}
}
}

View File

@ -0,0 +1,23 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-3
*
* Unit tests for DbExpr class
*/
require_once dirname(__FILE__) . '/../../model/DbExpr.php';
class DbExprTest extends PHPUnit_Framework_TestCase
{
public function testExpr()
{
$expr = new DbExpr('THIS IS SQL EXPRESSION');
$str = (string) $expr;
$this->assertSame('THIS IS SQL EXPRESSION', $str);
}
}

View File

@ -0,0 +1,102 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-3
*
* Unit tests for DbStatement class
*/
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/DbStatement.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class DbStatementTest extends PHPUnit_Framework_TestCase
{
private $driver;
private $sql;
private $stmt;
private $testData = array(
array('one' => 11, 'two' => 12),
array('one' => 21, 'two' => 22),
array('one' => 31, 'two' => 32),
);
public function setUp()
{
if (!isset($this->stmt)) {
$this->driver = $this->getMockBuilder('DbDriverMock')
->disableOriginalConstructor()
->setMethods(array('quote'))
->getMock();
$this->sql = 'SELECT * :place FROM :place AND :new';
$this->stmt = $this->getMockForAbstractClass('DbStatement', array($this->driver, $this->sql));
}
}
public function testConstruct()
{
$this->assertAttributeEquals($this->driver, 'driver', $this->stmt);
$this->assertAttributeEquals($this->sql, 'request', $this->stmt);
}
public function testFetch()
{
$this->stmt
->expects($this->any())
->method('fetch')
->with($this->anything())
->will($this->returnCallback(array($this, 'dbStatementFetch')));
$this->assertSame(11, $this->stmt->fetchField('one'));
$this->assertFalse($this->stmt->fetchField('zero'));
reset($this->testData);
$this->assertSame(array(11, 21, 31), $this->stmt->fetchColumn('one'));
reset($this->testData);
$result = $this->stmt->fetchAll();
$this->assertSame(11, $result[0]->one);
$this->assertSame(32, $result[2]->two);
// reset($this->testData);
// $result = $this->stmt->fetchPairs();
// $this->assertEquals(31, $result['one']);
}
public function dbStatementFetch($style)
{
$result = null;
switch ($style) {
case Db::FETCH_OBJ:
$data = each($this->testData);
if ($data !== false) {
$result = new ArrayObject($data['value'], ArrayObject::ARRAY_AS_PROPS);
} else {
$result = false;
}
break;
case Db::FETCH_ASSOC:
$data = each($this->testData);
$result = $data['value'];
break;
case Db::FETCH_NUM:
$data = each($this->testData);
if ($data !== false) {
$data = $data['value'];
$result[0] = key($data);
$result[1] = current($data);
} else {
$result = false;
}
}
return $result;
}
}

62
Tests/model/DbTest.php Normal file
View File

@ -0,0 +1,62 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-1
*
* Unit tests for Db class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class DbTest extends PHPUnit_Framework_TestCase
{
public function testConnectNoParams()
{
$this->setExpectedException('InitializationException', 'Trying to get property of non-object');
Db::connect();
}
public function testConnectConfigNotArray()
{
$this->setExpectedException('InitializationException', 'Connection parameters must be an array');
Db::connect('name', 'config');
}
/**
* @group MySQL
*/
public function testConnectGlobalConfig()
{
$conf = array('hostname' => 'localhost', 'driver' => 'MySQLiDriverGlobalConfMock', 'database' => 'db', 'username' => 'test', 'password' => '1234');
$this->getMockForAbstractClass('DbDriver', array(), 'MySQLiDriverGlobalConfMock', false);
Config::set('Db', array('global' =>$conf));
$driver = Db::connect('global');
$this->assertInstanceOf('DbDriver', $driver);
}
/**
* @group MySQL
*/
public function testConnectWithConfigParam()
{
$conf = array('hostname' => 'localhost', 'driver' => 'MySQLiDriverMock', 'database' => 'db', 'username' => 'test', 'password' => '1234');
$this->getMockForAbstractClass('DbDriver', array(), 'MySQLiDriverMock', false);
$driver = Db::connect('mysql', $conf);
$this->assertInstanceOf('DbDriver', $driver);
}
public function testConnectWithWrongDriver()
{
$this->getMock('NotDbDriver', array(), array(), 'NoDbDriverMock');
$this->setExpectedException('InitializationException', 'Database driver must extends DbDriver');
$driver = Db::connect('nodb', array('hostname' => 'localhost', 'driver' => 'NoDbDriverMock'));
}
}

View File

@ -0,0 +1,389 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-10
*
* Unit tests for MongoDriver class
*/
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/NoSqlDbDriver.php';
require_once dirname(__FILE__) . '/../../model/MongoDriver.php';
require_once dirname(__FILE__) . '/../../model/MongoDbCommand.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class MongoDbCommandTest extends PHPUnit_Framework_TestCase
{
private $conf = array();
private $driver;
private $collection;
public function setUp()
{
$this->conf = array(
'hostname' => 'localhost',
'database' => 'test',
'username' => 'test',
'password' => '1234',
'port' => 27017
);
$this->driver = new MongoDriver($this->conf);
$connection = $this->driver->getConnection();
$db = $connection->selectDB($this->conf['database']);
$db->authenticate($this->conf['username'], $this->conf['password']);
$collection = 'items';
$db->dropCollection($collection);
$this->collection = $db->selectCollection($collection);
}
/**
* @group Mongo
*/
public function testCommandFactory()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND);
$this->assertInstanceOf('MongoDbCommand', $cmd);
$this->assertInstanceOf('FindMongoCommand', $cmd);
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT);
$this->assertInstanceOf('MongoDbCommand', $cmd);
$this->assertInstanceOf('InsertMongoCommand', $cmd);
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::UPDATE);
$this->assertInstanceOf('MongoDbCommand', $cmd);
$this->assertInstanceOf('UpdateMongoCommand', $cmd);
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::REMOVE);
$this->assertInstanceOf('MongoDbCommand', $cmd);
$this->assertInstanceOf('RemoveMongoCommand', $cmd);
}
/**
* @group Mongo
*/
public function testFindCommand()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'bread'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(0, $result->count());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$cmd->execute();
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$cmd->execute();
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'insert'))->bindParam('fields', array());
$this->assertEquals(2, $cmd->execute()->count());
$cmd
->bindParam('condition', array('name' => 'insert'))
->bindParam('fields', array())
->bindParam('multiple', false);
$result = $cmd->execute();
$this->assertEquals('insert', $result['name']);
}
/**
* @group Mongo
*/
public function testCountCommand()
{
$count_cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT, $this->collection);
$count_cmd->bindParam('condition', array('name' => 'bread'));
$count_result = $count_cmd->execute();
$find_cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$find_cmd->bindParam('condition', array('name' => 'bread'))->bindParam('fields', array());
$find_result = $find_cmd->execute();
$this->assertEquals(0, $count_result);
$this->assertEquals($count_result, $find_result->count());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$cmd->execute();
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$cmd->execute();
$count_cmd->bindParam('condition', array('name' => 'insert'));
$this->assertEquals(2, $count_cmd->execute());
$find_cmd->bindParam('condition', array('name' => 'insert'));
$this->assertEquals($find_cmd->execute()->count(), $count_cmd->execute());
}
/**
* @group Mongo
*/
public function testInsertCommand()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$this->assertFalse($cmd->getInsertId());
$this->assertArrayHasKey('n', $cmd->execute());
$this->assertNotEmpty($cmd->getInsertId());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'insert'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(1, $result->count());
}
/**
* @group Mongo
*/
public function testInsertCommandMultipleObjects()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$data = array(
array('name' => 'first object'),
array('name' => 'second object'),
array('name' => 'equal object'),
array('name' => 'equal object')
);
$cmd
->bindParam('data', $data)
->bindParam('multiple', true)
->bindParam('safe', true);
$this->assertFalse($cmd->getInsertId());
$this->assertArrayHasKey('n', $cmd->execute());
$cmd->bindParam('data', array());
$cmd->execute();
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'first object'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(1, $result->count());
$cmd->bindParam('condition', array('name' => 'second object'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(1, $result->count());
$cmd->bindParam('condition', array('name' => 'equal object'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(2, $result->count());
}
/**
* @group Mongo
*/
public function testInsertCommandNotAllParamsBinded()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$this->setExpectedException('GeneralException', 'InsertMongoCommand error. Bind all required params first');
$cmd->execute();
}
/**
* @group Mongo
*/
public function testUpdateCommand()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$this->assertArrayHasKey('n', $cmd->execute());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::UPDATE, $this->collection);
$cmd
->bindParam('condition', array('name' => 'insert'))
->bindParam('data', array('$set' => array('name' => 'update')))
->bindParam('upsert', false)
->bindParam('safe', true);
$this->assertArrayHasKey('n', $cmd->execute());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'insert'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(0, $result->count());
$cmd->bindParam('condition', array('name' => 'update'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(1, $result->count());
}
/**
* @group Mongo
*/
public function testUpdateCommandNotAllParamsBinded()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::UPDATE, $this->collection);
$cmd->bindParam('data', array('name' => 'bread'));
$this->setExpectedException('GeneralException', 'UpdateMongoCommand error. Bind all required params first');
$cmd->execute();
}
/**
* @group Mongo
*/
public function testRemoveCommand()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$this->assertArrayHasKey('n', $cmd->execute());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'insert'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(1, $result->count());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::REMOVE, $this->collection);
$cmd
->bindParam('condition', array('name' => 'insert'))
->bindParam('safe', true);
$this->assertArrayHasKey('n', $cmd->execute());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->collection);
$cmd->bindParam('condition', array('name' => 'insert'))->bindParam('fields', array());
$result = $cmd->execute();
$this->assertEquals(0, $result->count());
}
/**
* @group Mongo
*/
public function testRemoveCommandNotAllParamsBinded()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::REMOVE, $this->collection);
$this->setExpectedException('GeneralException', 'RemoveMongoCommand error. Bind all required params first.');
$cmd->execute();
}
/**
* @group Mongo
*/
public function testCommandCommandNotAllParamsBinded()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, $this->collection);
$this->setExpectedException('GeneralException', 'CommandMongoCommand error. Bind all required params first');
$cmd->execute();
}
/**
* @group Mongo
*/
public function testCommandCommandNotMongoDb()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, new CollectionMock());
$cmd->bindParam('command', array());
$this->assertFalse($cmd->execute());
}
/**
* @group Mongo
*/
public function testCommandCommand()
{
$col = new CollectionMock();
$col->db = $this->getMock('MongoDb', array('command'), array(), 'SomeMongoMock', false);
$col->db
->expects($this->once())
->method('command')
->will($this->returnValue(true));
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, $col);
$cmd->bindParam('command', array());
$this->assertTrue($cmd->execute());
}
/**
* @group Mongo
*/
public function testToStringParamsNotSet()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, new CollectionMock());
$this->assertSame('Command properties not set', $cmd->__toString());
}
/**
* @group Mongo
*/
public function testToString()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd->bindParam('collection', new CollectionMock());
$this->assertStringStartsWith("\n" . 'Collection: CollectionMock', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd->bindParam('collection', new CollectionMock());
$cmd->bindParam('condition', array());
$this->assertStringStartsWith("\n" . 'Collection: CollectionMock', $cmd->__toString());
$this->assertContains('Condition: ' . '[]' . PHP_EOL, $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, new CollectionMock());
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd->bindParam('command', array());
$this->assertStringStartsWith("\n" . 'Collection: CollectionMock', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('safe', true);
$this->assertStringStartsWith("\n" . 'Collection: ', $cmd->__toString());
$this->assertContains('Bulk insert: FALSE', $cmd->__toString());
$this->assertContains('Data: ' . '[' . PHP_EOL . "\tname = insert" . PHP_EOL . ']' . PHP_EOL, $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd
->bindParam('data', array('name' => 'insert'))
->bindParam('multiple', true)
->bindParam('safe', true);
$this->assertContains('Bulk insert: TRUE', $cmd->__toString());
$cmd->bindParam('condition', array('name' => 'insert'))->bindParam('fields', array());
$this->assertStringStartsWith("\n" . 'Collection: ', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::REMOVE, $this->collection);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd
->bindParam('condition', array('name' => 'insert'))
->bindParam('safe', true);
$this->assertStringStartsWith("\n" . 'Collection: ', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::UPDATE, $this->collection);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd
->bindParam('condition', array('name' => 'insert'))
->bindParam('data', array('$set' => array('name' => 'update')))
->bindParam('upsert', false)
->bindParam('safe', true);
$this->assertStringStartsWith("\n" . 'Collection: ', $cmd->__toString());
}
}
class CollectionMock
{
public $db = array();
public function __toString()
{
return PHP_EOL . 'CollectionMock';
}
}

View File

@ -0,0 +1,387 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-10
*
* Unit tests for MongoDriver class
*/
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/NoSqlDbDriver.php';
require_once dirname(__FILE__) . '/../../model/MongoDbCommand.php';
require_once dirname(__FILE__) . '/../../model/DbStatement.php';
require_once dirname(__FILE__) . '/../../model/MongoStatement.php';
require_once dirname(__FILE__) . '/../../model/MongoDriver.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class MongoDriverTest extends PHPUnit_Framework_TestCase
{
private $conf = array();
public function setUp()
{
$this->conf = array(
'hostname' => 'localhost',
'database' => 'test',
'username' => 'test',
'password' => '1234',
'port' => 27017
);
$data = array(
array(
'name' => 'bread',
'price' => 3.2,
'quantity' => 10
),
array(
'name' => 'eggs',
'price' => 2.1,
'quantity' => 20
),
array(
'name' => 'fish',
'price' => 13.2,
'quantity' => 2
),
array(
'name' => 'milk',
'price' => 3.8,
'quantity' => 1
),
array(
'name' => 'eggs',
'price' => 2.3,
'quantity' => 5
)
);
$connection = new Mongo('mongodb://' . $this->conf['hostname'] . ':' . $this->conf['port']);
$db = $connection->selectDB($this->conf['database']);
$db->authenticate($this->conf['username'], $this->conf['password']);
$collection = 'items';
$db->dropCollection($collection);
$collection = $db->selectCollection($collection);
foreach ($data as $document) {
$collection->insert($document);
}
}
/**
* @group Mongo
*/
public function testGetConnectionNoHostname()
{
unset($this->conf['hostname']);
$this->setExpectedException('GeneralException', 'Configuration must have a "hostname"');
$mongo = new MongoDriver($this->conf);
}
/**
* @group Mongo
*/
public function testGetConnectionWrongPassword()
{
$this->conf['password'] = 'nopass';
$mongo = new MongoDriver($this->conf);
$this->setExpectedException('MongoConnectionException', 'Couldn\'t authenticate with database');
$this->assertInstanceOf('MongoDB', $mongo->getConnection());
}
/**
* @group Mongo
*/
public function testGetConnection()
{
$mongo = new MongoDriver($this->conf);
$this->assertFalse($mongo->isConnected());
$this->assertInstanceOf('Mongo', $mongo->getConnection());
$this->assertTrue($mongo->isConnected());
$mongo->getConnection();
$mongo->disconnect();
$this->assertFalse($mongo->isConnected());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFind()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(2, $mongo->find('items', array('name' => 'eggs'))->numRows());
$eggs = $mongo->find('items', array('name' => 'eggs'));
$egg = $eggs->fetch();
$this->assertEquals(20, $egg->quantity);
$egg = $eggs->fetchObject();
$this->assertEquals('eggs', $egg->name);
$this->assertFalse($eggs->fetchObject());
$this->assertEquals(3, $mongo->find('items', array('price' => array('$lt' => 3.5)))->numRows());
$data = $mongo->find('items', array('price' => array('$lt' => 3.5)));
$count = 0;
while ($row = $data->fetch(Db::FETCH_ASSOC)) {
$count++;
$this->assertLessThan(3.5, $row['price']);
}
$this->assertEquals(3, $count);
$this->assertEquals(5, $mongo->find('items', array())->numRows());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testOrderSkipLimit()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$count = $mongo->find('items', array())->numRows();
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(2, $mongo->find('items', array('name' => 'eggs'))->numRows());
$mongo->insert('items', array('name' => 'fdsbssc'));
$mongo->insert('items', array('name' => 'boc'));
$mongo->insert('items', array('name' => 'abc'));
$mongo->insert('items', array('name' => 'vcxxc'));
$mongo->insert('items', array('name' => 'abbc'));
$mongo->insert('items', array('name' => 'dsbssc'));
$mongo->insert('items', array('name' => 'bssc'));
$data = $mongo->find('items', array());
$this->assertEquals($count + 7, $data->numRows());
$data->order(array('name' => 1));
$this->assertEquals('abbc', $data->fetch()->name);
$this->assertEquals('abc', $data->fetch()->name);
$this->assertEquals('boc', $data->fetch()->name);
$data = $mongo->find('items', array());
$data->order(array('name' => -1));
$data->skip(3);
$data->limit(1);
while ($row = $data->fetch()) {
$this->assertEquals('fdsbssc', $row->name);
}
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCount()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(5, $mongo->count('items'));
$this->assertEquals(2, $mongo->count('items', array('name' => 'eggs')));
$this->assertEquals(1, $mongo->count('items', array('name' => 'eggs'), 1));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCursorCount()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(5, $mongo->find('items')->count(5));
$this->assertCount(3, $mongo->find('items')->limit(3)->fetchAll());
$this->assertEquals(5, $mongo->count('items'));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testRemove()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(0, $mongo->delete('items', array('name' => 'esggs')));
$this->assertEquals(2, $mongo->delete('items', array('name' => 'eggs')));
$this->assertEquals(1, $mongo->delete('items', array('name' => 'bread')));
$this->assertEquals(0, $mongo->find('items', array('name' => 'bread'))->numRows());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testInsert()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(0, $mongo->insert('items', array('name' => 'bread')));
$this->assertNotEmpty($mongo->getInsertId());
$this->assertEquals(2, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(0, $mongo->insert('items', array('name' => 'meat', 'weight' => 230)));
$this->assertEquals(230, $mongo->find('items', array('name' => 'meat'))->fetch()->weight);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testBatchInsert()
{
Config::set('DEBUG', false);
$data = array(
array('name' => 'first object'),
array('name' => 'second object'),
array('name' => 'equal object'),
array('name' => 'equal object')
);
$mongo = new MongoDriver($this->conf);
$mongo->insert('items', $data, true);
$this->assertEquals(1, $mongo->find('items', array('name' => 'first object'))->numRows());
$this->assertEquals(1, $mongo->find('items', array('name' => 'second object'))->numRows());
$this->assertEquals(2, $mongo->find('items', array('name' => 'equal object'))->numRows());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testGetInsertId()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(0, $mongo->getInsertId());
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(0, $mongo->insert('items', array('name' => 'bread')));
$this->assertEquals(2, $mongo->find('items', array('name' => 'bread'))->numRows());
$id1 = $mongo->getInsertId();
$this->assertNotEmpty($id1);
$this->assertEquals(0, $mongo->insert('items', array('name' => 'bread')));
$id2 = $mongo->getInsertId();
$this->assertNotEmpty($id2);
$this->assertNotEquals($id1, $id2);
$this->assertEquals(3, $mongo->find('items', array('name' => 'bread'))->numRows());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testUpdate()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(1, $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'fish')));
$this->assertEquals(2, $mongo->update('items', array('$set' => array('price' => 1)), array('name' => 'eggs')));
$fish = $mongo->find('items', array('name' => 'fish'))->fetch();
$this->assertEquals(200, $fish->price);
$this->assertEquals('today', $fish->date);
$this->assertEquals(0, $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'ball')));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testUpsert()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$mongo->insert('items', array('name' => 'bread'));
$this->assertInstanceOf('MongoId', $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'ball'), true, true));
$this->assertEquals('today', $mongo->find('items', array('name' => 'ball'))->fetch()->date);
$this->assertEquals(2, $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'eggs'), true, true));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFindAndModify()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(10, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
$result = $mongo->findAndModify('items', array('name' => 'bread'), array('$set' => array('quantity' => 20)));
$this->assertEquals(10, $result->fetch()->quantity);
$this->assertEquals(20, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFindAndModifyNoItem()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(10, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
$result = $mongo->findAndModify('items', array('name' => 'breading'), array('$set' => array('quantity' => 20)))->fetch();
$this->assertFalse($result);
$this->assertEquals(10, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testEvalCommand()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('$eval' => 'function() { return db.items.count();}'));
$this->assertEquals(5, $result->fetch());
$this->assertEquals(5, $mongo->count('items'));
$result = $mongo->command('items', array('$eval' => 'function() { return "HELLO!";}'));
$this->assertEquals("HELLO!", $result->fetch());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testEval()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('$eval' => 'function() {return true; }'));
$this->assertTrue($result->fetch());
$result = $mongo->command('items', array('$eval' => 'function() {return "Hello"; }'));
$this->assertSame('Hello', $result->fetch());
$result = $mongo->command('items', array('$eval' => 'function() {return db.items.count(); }'));
$this->assertEquals(5, $result->fetch());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCommand()
{
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('distinct' => 'items', 'key' => 'name'));
$this->assertEquals(4, count($result->fetch(DB::FETCH_ASSOC)));
}
}

View File

@ -0,0 +1,432 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-7
*
* Unit tests for MongoModel class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../cache/Cacher.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../model/DbExpr.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/MongoDbCommand.php';
require_once dirname(__FILE__) . '/../../model/DbStatement.php';
require_once dirname(__FILE__) . '/../../model/MongoStatement.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/NoSqlDbDriver.php';
require_once dirname(__FILE__) . '/../../model/MongoDriver.php';
require_once dirname(__FILE__) . '/../../model/Model.php';
require_once dirname(__FILE__) . '/../../model/MongoModel.php';
class MongoModelTest extends PHPUnit_Framework_TestCase
{
/**
* @var MongoModel
*/
private $model;
/**
* @var ReflectionMethod
*/
private $method_count;
/**
* @var ReflectionMethod
*/
private $method_fetch;
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
$conf = array('default' => array('driver' => 'MongoDriver', 'hostname' => 'localhost', 'database' => 'test', 'username' => 'test', 'password' => '1234', 'port' => 27017));
$this->dbSetUp($conf);
Config::set('Db', $conf);
if (!class_exists('MockModel')) {
$this->model = $this->getMockForAbstractClass('MongoModel', array(), 'MongoMockModel');
} else {
$this->model = new MongoMockModel();
}
$model = new ReflectionClass('MongoModel');
$this->method_count = $model->getMethod('count');
$this->method_count->setAccessible(true);
$this->method_fetch = $model->getMethod('fetch');
$this->method_fetch->setAccessible(true);
set_new_overload(array($this, 'newCallback'));
}
/**
* @group Mongo
*/
public function testModel()
{
$this->assertInstanceOf('MongoMockModel', $this->model);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetch()
{
Config::set('DEBUG', false);
$mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->once())
->method('set')
->will($this->returnValue(true));
$mock->expects($this->once())
->method('get')
->will($this->returnValue(false));
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => -1), 'limit' => 2), $mock);
$this->assertInstanceOf('ArrayObject', $result);
$this->assertEquals('milk', $result->name);
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => array('name')));
$this->assertSame('bread', $result->name);
$result = $this->method_fetch->invoke($this->model, array());
$this->setExpectedException('PHPUnit_Framework_Error');
$this->assertNull($result->pounds);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchField()
{
Config::set('DEBUG', false);
$mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->exactly(2))
->method('set')
->will($this->returnValue(true));
$mock->expects($this->exactly(2))
->method('get')
->will($this->returnValue(false));
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchField');
$method->setAccessible(true);
$result = $method->invoke($this->model, array('name' => 'milk'), array(), 'quantity', $mock);
$this->assertEquals(1, $result);
$result = $method->invoke($this->model, array(), array('skip' => 2), 'quantity', $mock);
$this->assertEquals($result, $this->method_fetch->invoke($this->model, array(), array('skip' => 2))->quantity);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchAll()
{
Config::set('DEBUG', false);
$mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->once())
->method('set')
->will($this->returnValue(true));
$mock->expects($this->once())
->method('get')
->will($this->returnValue(false));
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchAll');
$method->setAccessible(true);
$result = $method->invoke($this->model, array('name' => 'eggs'), array(), $mock);
$this->assertEquals(2, count($result));
$result = $method->invoke($this->model, array(), array('skip' => 2));
$this->assertEquals(3, count($result));
$this->assertEquals('fish', $result[0]->name);
$this->assertEquals('milk', $result[1]->name);
$this->assertEquals('eggs', $result[2]->name);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchOrderParam()
{
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => 'name'));
$this->assertSame('bread', $result->name);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1, 'quantity' => -1), 'skip' => 1));
$this->assertSame(2.1, $result->price);
$this->setExpectedException('GeneralException', 'Wrong order parameter given to query.');
$this->method_fetch->invoke($this->model, array(), array('order' => 1));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchSkipLimitParam()
{
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => 'name'));
$this->assertSame('bread', $result->name);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1, 'quantity' => -1), 'skip' => 1, 'limit' => 1));
$this->assertSame(2.1, $result->price);
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchAll');
$method->setAccessible(true);
$this->assertCount(3, $method->invoke($this->model, array(), array('limit' => 3)));
$this->assertCount(2, $method->invoke($this->model, array(), array('skip' => 3)));
$this->assertCount(5, $method->invoke($this->model, array(), array()));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchFieldsParam()
{
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => 'name'));
$this->assertTrue(!isset($result->quantity));
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => array('name', 'price')));
$this->assertTrue(!isset($result->quantity));
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => array('name' => 1, 'price' => 1)));
$this->assertTrue(!isset($result->quantity));
$this->setExpectedException('GeneralException', 'Wrong fields parameter given to query.');
$this->method_fetch->invoke($this->model, array(), array('fields' => 1));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testGet()
{
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1)));
$this->assertEquals('bread', $result->name);
$id = $result->_id;
$this->assertEquals(10, $this->model->get($id)->quantity);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testDelete()
{
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1)));
$id = $result->_id;
$this->assertEquals(1, $this->model->delete($id));
$this->assertFalse($this->method_fetch->invoke($this->model, array('name' => 'bread')));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testUpdate()
{
Config::set('DEBUG', false);
$this->model->insert(array('name' => 'testbread', 'price' => 3.2, 'quantity' => 10));
$result = $this->method_fetch->invoke($this->model, array('name' => 'testbread'));
$this->assertEquals(10, $result->quantity);
$this->model->update(array('$set' => array('quantity' => 3)), $result->_id);
$this->assertEquals(3, $this->model->get($result->_id)->quantity);
$this->model->update(array('$set' => array('quantity' => 13)), (string)$result->_id);
$this->assertEquals(13, $this->model->get($result->_id)->quantity);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testBatchInsert()
{
Config::set('DEBUG', false);
$data = array(
array('name' => 'first object'),
array('name' => 'second object'),
array('name' => 'equal object'),
array('name' => 'equal object')
);
$this->model->batchInsert($data);
$this->assertEquals(1, $this->method_count->invoke($this->model, array('name' => 'first object')));
$this->assertEquals(2, $this->method_count->invoke($this->model, array('name' => 'equal object')));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCount()
{
Config::set('DEBUG', false);
$this->assertEquals(5, $this->method_count->invoke($this->model));
$this->assertEquals(2, $this->method_count->invoke($this->model, array('name' => 'eggs')));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testUseMongoId()
{
Config::set('DEBUG', false);
$this->assertAttributeEquals(true, 'useMongoId', $this->model);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testId()
{
Config::set('DEBUG', false);
$class = new ReflectionClass('MongoModel');
$prop = $class->getProperty('useMongoId');
$prop->setAccessible(true);
$this->model->insert(array('_id' => 1, 'name' => 'testbread', 'price' => 3.2, 'quantity' => 10));
$this->model->insert(array('_id' => 2, 'name' => 'testbread', 'price' => 12, 'quantity' => 2));
$this->assertSame(2, $this->method_count->invoke($this->model, array('name' => 'testbread')));
$prop->setValue($this->model, false);
$this->model->delete(1);
$this->assertSame(1, $this->method_count->invoke($this->model, array('name' => 'testbread')));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testIdToMongoId()
{
Config::set('DEBUG', false);
$this->model->insert(array('name' => 'testbread', 'price' => 3.2, 'quantity' => 10));
$this->model->insert(array('name' => 'testbread', 'price' => 12, 'quantity' => 2));
$this->assertSame(2, $this->method_count->invoke($this->model, array('name' => 'testbread')));
$id = $this->method_fetch->invoke($this->model, array('name' => 'testbread'))->_id->__toString();
$this->assertInternalType('string', $id);
$item = $this->model->get($id);
$this->assertSame('testbread', $item->name);
$this->model->delete($id);
$this->assertSame(1, $this->method_count->invoke($this->model, array('name' => 'testbread')));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testAddCondition()
{
Config::set('DEBUG', false);
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('addCondition');
$method->setAccessible(true);
$query = array();
$result = $method->invokeArgs($this->model, array(&$query, 'name', 'tony'));
$this->assertSame(array('name' => 'tony'), $query);
$this->assertSame($this->model, $result);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testAddConditionEmptyValue()
{
Config::set('DEBUG', false);
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('addCondition');
$method->setAccessible(true);
$query = array();
$method->invokeArgs($this->model, array(&$query, 'name', false));
$this->assertEmpty($query);
$method->invokeArgs($this->model, array(&$query, 'name', null));
$this->assertEmpty($query);
}
public function tearDown()
{
$conf = array('driver' => 'MongoDriver', 'hostname' => 'localhost', 'database' => 'test', 'username' => 'test', 'password' => '1234', 'port' => 27017);
$connection = new Mongo('mongodb://' . $conf['hostname'] . ':' . $conf['port']);
$db = $connection->selectDB($conf['database']);
$db->authenticate($conf['username'], $conf['password']);
$collection = 'mongomock';
$db->selectCollection($collection)->remove(array());
}
protected function newCallback($className)
{
switch ($className) {
case 'CacheKey':
return 'MockCacheKey';
default:
return $className;
}
}
public function dbSetUp($conf)
{
$data = array(
array(
'name' => 'bread',
'price' => 3.2,
'quantity' => 10
),
array(
'name' => 'eggs',
'price' => 2.1,
'quantity' => 20
),
array(
'name' => 'fish',
'price' => 13.2,
'quantity' => 2
),
array(
'name' => 'milk',
'price' => 3.8,
'quantity' => 1
),
array(
'name' => 'eggs',
'price' => 2.3,
'quantity' => 5
)
);
$connection = new Mongo('mongodb://' . $conf['default']['hostname'] . ':' . $conf['default']['port']);
$db = $connection->selectDB($conf['default']['database']);
$db->authenticate($conf['default']['username'], $conf['default']['password']);
$collection = 'mongomock';
$db->dropCollection($collection);
$collection = $db->selectCollection($collection);
foreach ($data as $document) {
$collection->insert($document);
}
}
}

View File

@ -0,0 +1,480 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-15
*
* Unit tests for MySQLiStatement class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../util/profiler/CommandProfiler.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/DbStatement.php';
require_once dirname(__FILE__) . '/../../model/MongoStatement.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class MongoStatementTest extends PHPUnit_Framework_TestCase
{
private $driver;
private $stmt;
private $request;
private $testData = array(
array('one' => 11, 'two' => 12),
array('one' => 21, 'two' => 22),
array('one' => 31, 'two' => 32),
);
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
if (!isset($this->stmt)) {
$this->driver = $this->getMockBuilder('DbDriverMock')
->disableOriginalConstructor()
->setMethods(array('getConnection'))
->getMock();
$this->request = $this->getMockBuilder('MongoDbCommandMock')
->disableOriginalConstructor()
->setMethods(array('execute', 'bindParam', 'getInsertId', '__toString'))
->getMock();
$this->stmt = new MongoStatement($this->driver, $this->request);
}
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testAffectedNumRowsNoResult()
{
Config::set('PROFILER_DETAILS', false);
$this->assertFalse($this->stmt->affectedRows());
$this->assertFalse($this->stmt->numRows());
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->any())
->method('execute')
->will($this->returnValue(array()));
$this->stmt->execute();
$this->assertFalse($this->stmt->affectedRows());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testAffectedNumRows()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('n' => 20, 'ok' => 1)));
$this->stmt->execute();
$this->assertEquals(20, $this->stmt->affectedRows());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testGetInsertId()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->request = $this->getMockBuilder('InsertMongoCommand')
->disableOriginalConstructor()
->setMethods(array('execute', 'bindParam', 'getInsertId'))
->getMock();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('n' => 20, 'ok' => 1)));
$this->request
->expects($this->once())
->method('getInsertId')
->will($this->returnValue('4b0rrs'));
$this->stmt = new MongoStatement($this->driver, $this->request);
$this->stmt->execute();
$this->assertEquals('4b0rrs', $this->stmt->getInsertId());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testExecute()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod()->setRequestExecuteMethod();
$this->assertTrue($this->stmt->execute());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testExecuteNoResult()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->any())
->method('execute')
->will($this->returnValue(false));
$this->setExpectedException('GeneralException', 'MongoDB request error.');
$this->stmt->execute();
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testExecuteNoConnection()
{
Config::set('PROFILER_DETAILS', false);
$this->driver
->expects($this->any())
->method('getConnection')
->will($this->returnValue(false));
$this->setExpectedException('GeneralException', 'No connection to MongoDB server.');
$this->stmt->execute();
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testExecuteWithDebug()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod()->setRequestExecuteMethod();
$this->assertTrue($this->stmt->execute());
$this->assertEquals(10, $this->stmt->numRows());
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testBindParam()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->request
->expects($this->once())
->method('bindParam')
->will($this->returnValue(true));
$this->setDriverGetConnectionMethod()->setRequestExecuteMethod();
$this->assertTrue($this->stmt->execute(array('one' => 'two')));
$this->assertAttributeNotEquals(null, 'result', $this->stmt);
$this->stmt->close();
$this->assertAttributeEquals(null, 'result', $this->stmt);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetch()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod()->setRequestForFetch();
$this->stmt->execute();
$result = $this->stmt->fetch();
$this->assertEquals('prev', $result->next);
$this->assertFalse($this->stmt->fetch());
$this->assertContains('Queries not counted.', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchWithInitialArray()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('retval' => 'val')));
$this->stmt->execute();
$this->assertEquals('val', $this->stmt->fetch());
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchAssocFromCursor()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod()->setRequestForFetch();
$this->stmt->execute();
$result = $this->stmt->fetch(Db::FETCH_ASSOC);
$this->assertEquals('prev', $result['next']);
$this->assertEquals(array(), $this->stmt->fetch(Db::FETCH_ASSOC));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchAssocFromArray()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('some' => 'val')));
$this->stmt->execute();
$result = $this->stmt->fetch(Db::FETCH_ASSOC);
$this->assertEquals('val', $result['some']);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetchWrongMode()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('some' => 'val')));
$this->stmt->execute();
$this->setExpectedException('GeneralException', 'Invalid fetch mode "222" specified');
$this->stmt->fetch(222);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testSkipOrderLimit()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod()->setRequestForFetch();
$this->stmt->execute();
$this->assertInstanceOf('MongoStatement', $this->stmt->order(array('id' => 1)));
$this->assertInstanceOf('MongoStatement', $this->stmt->limit(10));
$this->assertInstanceOf('MongoStatement', $this->stmt->skip(1));
$this->stmt->fetch();
$this->stmt->fetch();
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCount()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod()->setRequestForFetch();
$this->stmt->execute();
$this->assertSame(10, $this->stmt->count());
$this->stmt->fetch();
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCountException()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('some' => 'val')));
$this->stmt->execute();
$this->setExpectedException('GeneralException', 'MongoStatement error. Impossible count result of opened cursor');
$this->stmt->count();
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testOrderException()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('some' => 'val')));
$this->stmt->execute();
$this->setExpectedException('GeneralException', 'MongoStatement error. Impossible order results of opened cursor');
$this->stmt->order(array('id' => 1));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testSkipException()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('some' => 'val')));
$this->stmt->execute();
$this->setExpectedException('GeneralException', 'MongoStatement error. Impossible skip results of opened cursor');
$this->stmt->skip(array('id' => 1));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testLimitException()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod();
$this->request
->expects($this->once())
->method('execute')
->will($this->returnValue(array('some' => 'val')));
$this->stmt->execute();
$this->setExpectedException('GeneralException', 'MongoStatement error. Impossible limit results of opened cursor');
$this->stmt->limit(array('id' => 1));
}
private function setDriverGetConnectionMethod()
{
$mongoMock = $this->getMock('Mongo');
$this->driver
->expects($this->any())
->method('getConnection')
->will($this->returnValue($mongoMock));
return $this;
}
public function setRequestExecuteMethod()
{
$resultMock = $this->getMockBuilder('MongoCursor')
->setMethods(array('count'))
->disableOriginalConstructor()
->getMock();
$resultMock
->expects($this->any())
->method('count')
->will($this->returnValue(10));
$this->request
->expects($this->any())
->method('execute')
->will($this->returnValue($resultMock));
return $this;
}
public function setRequestForFetch()
{
$resultMock = $this->getMockBuilder('MongoCursor')
->setMethods(array('count', 'getNext', 'limit', 'sort', 'skip'))
->disableOriginalConstructor()
->getMock();
$resultMock
->expects($this->any())
->method('limit');
$resultMock
->expects($this->any())
->method('sort');
$resultMock
->expects($this->any())
->method('skip');
$resultMock
->expects($this->any())
->method('count')
->will($this->returnValue(10));
$resultMock
->expects($this->at(0))
->method('getNext')
->will($this->returnValue(array('next' => 'prev', '_id' => 10)));
$resultMock
->expects($this->at(1))
->method('getNext')
->will($this->returnValue(array()));
$this->request
->expects($this->any())
->method('execute')
->will($this->returnValue($resultMock));
return $this;
}
}

View File

@ -0,0 +1,60 @@
<?php
abstract class MyDbDriver extends DbDriver
{
public function getInsertId($table = null, $key = null)
{
return true;
}
public function quoteIdentifier($param)
{
return $param;
}
public function quote($param)
{
return $param;
}
public function insert($table, $bind, $on_duplicate = array())
{
return $table;
}
public function update($table, $bind, $where = '')
{
return $table;
}
public function delete($table, $where = '')
{
return $table;
}
public function query($sql, $params = array())
{
$conf = array('driver' => 'MockDbDriver', 'hostname' => 'somehost', 'database' => 'db', 'username' => 'test', 'password' => '1234');
return new MockDbDriver($conf);
}
public function execute()
{
return true;
}
public function fetch()
{
return true;
}
public function fetchField($field)
{
return $field;
}
public function fetchAll()
{
return true;
}
}

View File

@ -0,0 +1,206 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-7
*
* Unit tests for MySQLiDriver class
*/
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbStatement.php';
require_once dirname(__FILE__) . '/../../model/MySQLiStatement.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/SqlDbDriver.php';
require_once dirname(__FILE__) . '/../../model/MySQLiDriver.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
{
static private $pdo = null;
private $conn = null;
private $conf = array();
protected function getConnection()
{
if ($this->conn === null) {
if (self::$pdo == null) {
self::$pdo = new PDO($GLOBALS['DB_DSN'], $GLOBALS['DB_USER'], $GLOBALS['DB_PASSWD']);
}
$this->conn = $this->createDefaultDBConnection(self::$pdo, $GLOBALS['DB_DBNAME']);
}
$this->conf = array('hostname' => 'localhost', 'database' => $GLOBALS['DB_DBNAME'], 'username' => $GLOBALS['DB_USER'], 'password' => $GLOBALS['DB_PASSWD']);
return $this->conn;
}
protected function getDataSet()
{
return $this->createFlatXMLDataSet(dirname(__FILE__) . '/testData.xml');
}
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
/**
* @group MySQL
*/
public function testDriver()
{
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf);
$queryTable = $this->getConnection()->createQueryTable(
'table', 'SELECT * FROM `table`'
);
$expectedTable = $this->createFlatXmlDataSet(dirname(__FILE__) . '/testData.xml')
->getTable("table");
$this->assertTablesEqual($expectedTable, $queryTable);
$this->assertSame(1, $driver->insert('table', array('id' => 3, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20')));
$this->assertSame(3, $this->getConnection()->getRowCount('table'));
}
/**
* @group MySQL
*/
public function testGetConnection()
{
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf);
$this->assertInstanceOf('mysqli', $driver->getConnection());
$this->assertTrue($driver->isConnected());
}
/**
* @group MySQL
*/
public function testGetConnectionWrongConfig()
{
Config::set('DEBUG', false);
$this->conf['database'] = 'nodb';
$driver = new MySQLiDriver($this->conf);
$this->setExpectedException('GeneralException', 'Unknown database \'nodb\'');
$this->assertNull('mysqli', $driver->getConnection());
}
/**
* @group MySQL
*/
public function testDisconnect()
{
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf);
$driver->disconnect();
$this->assertAttributeEquals(null, 'connection', $driver);
$this->assertInstanceOf('mysqli', $driver->getConnection());
$this->assertAttributeInstanceOf('mysqli', 'connection', $driver);
$driver->disconnect();
$this->assertAttributeEquals(null, 'connection', $driver);
}
/**
* @group MySQL
*/
public function testInsert()
{
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf);
$this->assertSame(1, $driver->insert('table', array('id' => 3, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20')));
$this->assertSame(3, $driver->getInsertId());
$this->assertSame(1, $driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20')));
$this->assertSame(4, $driver->getInsertId());
$this->assertSame(1, $driver->insert('table', array('id' => null, 'user' => true, 'content' => 'some test content', 'created' => '2011-11-07 11:35:20')));
$this->assertSame(5, $driver->getInsertId());
$this->assertSame(2, $driver->insert('table', array('id' => '5', 'user' => true, 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'), array('id' => 8)));
$this->assertSame(8, $driver->getInsertId());
}
/**
* @TODO: DbDriver::getInsertId($table = null, $key = null) - params not used
* @group MySQL
*/
public function testGetInsertId()
{
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf);
$this->assertSame(1, $driver->insert('table', array('id' => 3, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20')));
$this->assertSame(3, $driver->getInsertId());
}
/**
* @group MySQL
*/
public function testTransaction()
{
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf);
$queryTable = $this->getConnection()->createQueryTable(
'table', 'SELECT * FROM `table`'
);
$expectedTable = $this->createFlatXmlDataSet(dirname(__FILE__) . '/testData.xml')
->getTable("table");
$this->assertTablesEqual($expectedTable, $queryTable);
$driver->getConnection();
$driver->beginTransaction();
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$queryTable = $this->getConnection()->createQueryTable(
'table', 'SELECT * FROM `table`'
);
$driver->commit();
$expectedTable = $this->createFlatXmlDataSet(dirname(__FILE__) . '/testDataAfterCommit.xml')
->getTable("table");
$this->assertTablesEqual($expectedTable, $queryTable);
}
/**
* @group MySQL
*/
public function testRollback()
{
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf);
$queryTable = $this->getConnection()->createQueryTable(
'table', 'SELECT * FROM `table`'
);
$expectedTable = $this->createFlatXmlDataSet(dirname(__FILE__) . '/testData.xml')
->getTable("table");
$this->assertTablesEqual($expectedTable, $queryTable);
$driver->getConnection();
$driver->beginTransaction();
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$driver->insert('table', array('id' => null, 'user' => 'tony', 'content' => 'some test content', 'created' => '2011-11-07 11:35:20'));
$driver->rollback();
$queryTable = $this->getConnection()->createQueryTable(
'table', 'SELECT * FROM `table`'
);
$this->assertTablesEqual($expectedTable, $queryTable);
}
}

View File

@ -0,0 +1,360 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-4
*
* Unit tests for MySQLiStatement class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../util/profiler/CommandProfiler.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/DbStatement.php';
require_once dirname(__FILE__) . '/../../model/MySQLiStatement.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class MySQLiStatementTest extends PHPUnit_Framework_TestCase
{
/**
* @var MySQLiDriver|PHPUnit_Framework_MockObject_MockObject
*/
private $driver;
/**
* @var MySQLiStatement
*/
private $stmt;
private $sql;
private $testData = array(
array('one' => 11, 'two' => 12),
array('one' => 21, 'two' => 22),
array('one' => 31, 'two' => 32),
);
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
if (!isset($this->stmt)) {
$this->driver = $this->getMockBuilder('DbDriverMock')
->disableOriginalConstructor()
->setMethods(array('quote', 'getConnection'))
->getMock();
$this->sql = 'SELECT * :place FROM :place AND :new';
$this->stmt = new MySQLiStatement($this->driver, $this->sql);
}
}
public function testBindParam()
{
$val = $this->getMockBuilder('DbExpr')
->disableOriginalConstructor()
->getMock();
$this->assertFalse($this->stmt->bindParam('var', $val));
$this->assertTrue($this->stmt->bindParam('place', $val));
}
public function testBindParamExceptionParam()
{
$val = 1;
$this->setExpectedException('GeneralException', 'Placeholder must be an integer or string');
$this->stmt->bindParam(array(), $val);
}
public function testBindParamExceptionWrongObject()
{
$val = $this->getMock('NotDbExpr');
$this->setExpectedException('GeneralException', 'Objects excepts DbExpr not allowed.');
$this->stmt->bindParam('paa', $val);
}
/**
* @runInSeparateProcess
*/
public function testExecute()
{
Config::set('PROFILER_DETAILS', false);
$this->driver
->expects($this->any())
->method('quote')
->with($this->anything())
->will($this->returnCallback(array($this, 'driverQuote')));
$this->setDriverGetConnectionMethod();
$result = $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertTrue($result);
}
/**
* @runInSeparateProcess
*/
public function testExecuteNoPlaceholders()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->sql = 'PLAIN SQL';
$result = $this->stmt->execute(array());
$this->assertTrue($result);
}
/**
* @runInSeparateProcess
* @group MySQL
*/
public function testFetchNoResult()
{
Config::set('PROFILER_DETAILS', false);
$this->assertFalse($this->stmt->fetch());
}
/**
* @runInSeparateProcess
* @group MySQL
*/
public function testDriverExecuteNoResult()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionWrongResultMethod();
$this->setExpectedException('GeneralException', 'ERROR');
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
}
/**
* @runInSeparateProcess
* @group MySQL
*/
public function testFetch()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertSame('OBJECT', $this->stmt->fetch());
$this->assertSame('ARRAY', $this->stmt->fetch(Db::FETCH_NUM));
$this->assertSame('ASSOC', $this->stmt->fetch(Db::FETCH_ASSOC));
$this->assertSame('ARRAY', $this->stmt->fetch(Db::FETCH_BOTH));
}
/**
* @runInSeparateProcess
* @group MySQL
*/
public function testFetchObject()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertSame('OBJECT', $this->stmt->fetchObject());
}
/**
* @runInSeparateProcess
* @group MySQL
*/
public function testFetchPairs()
{
Config::set('PROFILER_DETAILS', false);
$resultMock = $this->getMockBuilder('mysqli_result')
->disableOriginalConstructor()
->setMethods(array('fetch_array', 'close'))
->setMockClassName('Mysqli_Result_Mock')
->getMock();
$resultMock
->expects($this->at(0))
->method('fetch_array')
->will($this->returnValue(array('pair', 'value')));
$resultMock
->expects($this->at(1))
->method('fetch_array')
->will($this->returnValue(false));
$resultMock
->expects($this->any())
->method('close')
->will($this->returnValue(TRUE));
$mysqliMock = $this->getMock('MysqliDrvr', array('query'));
$mysqliMock
->expects($this->any())
->method('query')
->with($this->anything())
->will($this->returnValue($resultMock));
$this->driver
->expects($this->any())
->method('getConnection')
->will($this->returnValue($mysqliMock));
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertSame(array('pair' => 'value'), $this->stmt->fetchPairs());
}
/**
* @runInSeparateProcess
*/
public function testFetchWithDebug()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertSame('OBJECT', $this->stmt->fetch());
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
* @group MySQL
*/
public function testClose()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->assertAttributeEquals(null, 'result', $this->stmt);
$this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertAttributeNotEquals(null, 'result', $this->stmt);
$this->stmt->close();
$this->assertAttributeEquals(null, 'result', $this->stmt);
$this->assertContains('Queries not counted.', Profiler::getInstance()->getCli());
}
/**
* @group MySQL
*/
public function testAffectedRows()
{
$mysqliMock = $this->getMockBuilder('MysqliDrvr');
$mysqliMock->affected_rows = 'AFFECTED_ROWS';
$this->driver
->expects($this->any())
->method('getConnection')
->will($this->returnValue($mysqliMock));
$this->assertSame('AFFECTED_ROWS', $this->stmt->affectedRows());
}
/**
* @group MySQL
*/
public function testNumRowsNoResult()
{
$this->assertFalse($this->stmt->numRows());
}
/**
* @runInSeparateProcess
* @TODO: exception just for code coverage - could not mock mysqli properties
* @group MySQL
*/
public function testNumRows()
{
$this->markTestSkipped('Unable to execute a method or access a property of an incomplete object.');
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertNull($this->stmt->numRows());
}
/**
* @runInSeparateProcess
* @group MySQL
*/
public function testFetchInvalidMode()
{
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->setExpectedException('GeneralException');
$this->stmt->fetch(324);
}
private function setDriverGetConnectionMethod()
{
$resultMock = $this->getMockBuilder('mysqli_result')
->disableOriginalConstructor()
->setMethods(array('fetch_object', 'fetch_array', 'fetch_assoc', 'close'))
->setMockClassName('Mysqli_Result_Mock')
->getMock();
$resultMock
->expects($this->any())
->method('fetch_object')
->will($this->returnValue('OBJECT'));
$resultMock
->expects($this->any())
->method('fetch_array')
->will($this->returnValue('ARRAY'));
$resultMock
->expects($this->any())
->method('fetch_assoc')
->will($this->returnValue('ASSOC'));
$resultMock
->expects($this->any())
->method('close')
->will($this->returnValue(TRUE));
$mysqliMock = $this->getMock('MysqliDrvr', array('query'));
$mysqliMock
->expects($this->any())
->method('query')
->with($this->anything())
->will($this->returnValue($resultMock));
$this->driver
->expects($this->any())
->method('getConnection')
->will($this->returnValue($mysqliMock));
return $this;
}
private function setDriverGetConnectionWrongResultMethod()
{
$mysqliMock = $this->getMock('MysqliDrvr', array('query'));
$mysqliMock
->expects($this->any())
->method('query')
->with($this->anything())
->will($this->returnValue(false));
$mysqliMock->error = 'ERROR';
$mysqliMock->errno = 0;
$this->driver
->expects($this->any())
->method('getConnection')
->will($this->returnValue($mysqliMock));
return $this;
}
public function driverQuote($val)
{
return $val;
}
public function dbStatementAssemble($val)
{
return $val;
}
}

View File

@ -0,0 +1,177 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-3
*
* Unit tests for DbDriver class
*/
require_once dirname(__FILE__) . '/../../model/DbExpr.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/SqlDbDriver.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class SqlDbDriverTest extends PHPUnit_Framework_TestCase
{
private $driver;
public function setUp()
{
$conf = array('hostname' => 'localhost', 'database' => 'db', 'username' => 'test', 'password' => '1234');
$this->driver = $this->getMockForAbstractClass('SqlDbDriver', array($conf));
}
public function testConstruct()
{
$conf = array('hostname' => 'localhost', 'database' => 'db', 'username' => 'test', 'password' => '1234');
try {
$this->driver = $this->getMockForAbstractClass('SqlDbDriver', array($conf));
}
catch (GeneralException $expected) {
$this->fail($expected->getMessage());
}
$this->assertInstanceOf('DbDriver', $this->driver);
}
public function testConstructWrongConfig()
{
$conf = array('hostname' => 'localhost', 'database' => 'db');
$this->setExpectedException('GeneralException', 'Configuration must have a "username"');
$this->getMockForAbstractClass('SqlDbDriver', array($conf));
}
public function testGetConnection()
{
$this->assertNull($this->driver->getConnection());
}
public function testBeginTransaction()
{
$this->assertSame($this->driver, $this->driver->beginTransaction());
}
public function testCommit()
{
$this->assertSame($this->driver, $this->driver->commit());
}
public function testRollback()
{
$this->assertSame($this->driver, $this->driver->rollback());
}
public function testQuery()
{
$this->setDriverPrepareFunction();
$stmt = $this->driver->query('SELECT * FROM table');
$this->assertInstanceOf('DbStmt', $stmt);
$this->assertSame('SELECT * FROM table', $stmt->string());
$stmt = $this->driver->query('SELECT * FROM table', 'simple');
$this->assertInstanceOf('DbStmt', $stmt);
$this->assertSame('SELECT * FROM table', $stmt->string());
}
public function testInsert()
{
$this->setDriverPrepareFunction()
->setDriverQuoteFunction();
$bind = array('table.name' => 'tony', 'chair.age' => 21, 'height' => 185);
$sql = $this->driver->insert('users', $bind);
$this->assertSame('INSERT INTO `users` (`table`.`name`, `chair`.`age`, `height`) VALUES (tony, 21, 185)', $sql);
}
public function testUpdate()
{
$this->setDriverPrepareFunction()
->setDriverQuoteFunction();
$bind = array('table.name' => 'tony', 'chair.age' => 21, 'height' => 185);
$sql = $this->driver->update('users', $bind);
$this->assertSame('UPDATE `users` SET `table`.`name`=tony, `chair`.`age`=21, `height`=185', $sql);
}
public function testDeleteNoWHERE()
{
$this->setDriverPrepareFunction();
$sql = $this->driver->delete('users');
$this->assertSame('DELETE FROM `users`', $sql);
}
public function testDeleteWithWHEREArray()
{
$this->setDriverPrepareFunction()
->setDriverQuoteFunction();
$sql = $this->driver->delete('users', array('name?tony' => new DbExpr('='), 'height?185' => '>'));
$this->assertSame('DELETE FROM `users` WHERE name=tony AND height>185', $sql);
}
public function testDeleteWithWHERESimpleCond()
{
$this->setDriverPrepareFunction();
$sql = $this->driver->delete('users', 'name=tony');
$this->assertSame('DELETE FROM `users` WHERE name=tony', $sql);
}
public function testDeleteWithWHEREKeyArray()
{
$this->setDriverPrepareFunction();
$sql = $this->driver->delete('users', array('name=tony' => 0));
$this->assertSame('DELETE FROM `users` WHERE name=tony', $sql);
}
public function testDeleteWithWHEREDbExpr()
{
$this->setDriverPrepareFunction();
$sql = $this->driver->delete('users', new DbExpr('name=tony'));
$this->assertSame('DELETE FROM `users` WHERE name=tony', $sql);
}
protected function setDriverPrepareFunction()
{
$this->driver
->expects($this->any())
->method('prepare')
->with($this->anything())
->will($this->returnCallback(array($this, 'dbDriverPrepare')));
return $this;
}
protected function setDriverQuoteFunction()
{
$this->driver
->expects($this->any())
->method('driverQuote')
->with($this->anything())
->will($this->returnArgument(0));
return $this;
}
public function dbDriverPrepare($sql)
{
$stmt = $this->getMock('DbStmt', array('execute', 'string', 'affectedRows'));
$stmt->expects($this->any())
->method('execute')
->with($this->anything());
$stmt->expects($this->any())
->method('string')
->will($this->returnValue($sql));
$stmt->expects($this->any())
->method('affectedRows')
->will($this->returnValue($sql));
return $stmt;
}
}

View File

@ -0,0 +1,246 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-7
*
* Unit tests for Model class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../cache/Cacher.php';
require_once dirname(__FILE__) . '/../../model/DbExpr.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/MyDbDriver.php';
require_once dirname(__FILE__) . '/../../model/Model.php';
require_once dirname(__FILE__) . '/../../model/SqlModel.php';
class SqlModelTest extends PHPUnit_Framework_TestCase
{
private $model;
public function setUp()
{
$conf = array('default' => array('driver' => 'MockDbDriver', 'hostname' => 'localhost', 'database' => 'db', 'username' => 'test', 'password' => '1234'));
if (!class_exists('MockDbDriver')) {
$this->getMockForAbstractClass('MyDbDriver', array($conf), 'MockDbDriver', false);
}
Config::set('Db', $conf);
if (!class_exists('MockModel')) {
$this->model = $this->getMockForAbstractClass('SqlModel', array(), 'MockModel');
} else {
$this->model = new MockModel();
}
set_new_overload(array($this, 'newCallback'));
}
public function testModel()
{
$this->assertInstanceOf('SqlModel', $this->model);
}
public function testGetInsertId()
{
$this->assertTrue($this->model->getInsertId());
}
public function testIdentify()
{
$param = 'param';
$this->assertSame($param, $this->model->identify($param));
}
public function testQuote()
{
$param = 'param';
$this->assertSame($param, $this->model->quote($param));
}
public function testGet()
{
$this->assertTrue($this->model->get(1));
}
public function testInsert()
{
$this->assertTrue($this->model->insert(array('data')));
}
public function testUpdate()
{
$this->assertSame('mock', $this->model->update(array('var' => 'val'), 1));
}
public function testDelete()
{
$this->assertSame('mock', $this->model->delete(1));
}
public function testOrder()
{
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('order');
$method->setAccessible(true);
$this->assertSame(' ORDER BY id DESC', $method->invoke($this->model, array('sort' => 'id', 'order' => 'desc')));
$this->assertSame(' ORDER BY name ASC', $method->invoke($this->model, array('sort' => 'name'), array('id', 'name')));
$this->assertEmpty($method->invoke($this->model, array()));
$this->assertSame(' ORDER BY name ASC', $method->invoke($this->model, array('sort' => 'name', 'order' => 'DESC'), array('id', 'name')));
}
public function testSearch()
{
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('search');
$method->setAccessible(true);
$this->assertEmpty($method->invoke($this->model, array()));
$this->assertEmpty($method->invoke($this->model, array('q' => 'in', 'qt' => 'name')));
$this->assertSame('test.name LIKE %on%', $method->invoke($this->model, array('qt' => 'name', 'q' => 'on'), array('name'), 'test'));
}
public function testFetch()
{
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('fetch');
$method->setAccessible(true);
$key = $this->getCacheKeyMockGetSet();
$this->assertTrue(true, $method->invoke($this->model, 'SELECT', array(), $key));
}
public function testFetchField()
{
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('fetchField');
$method->setAccessible(true);
$key = $this->getCacheKeyMockGetSet();
$this->assertSame('field', $method->invoke($this->model, 'SELECT', array(), 'field', $key));
}
public function testFetchAll()
{
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('fetchAll');
$method->setAccessible(true);
$key = $this->getCacheKeyMockGetSet();
$this->assertTrue(true, $method->invoke($this->model, 'SELECT', array(), $key));
}
public function testGetCache()
{
$model = new ReflectionClass('MockModel');
$method = $model->getMethod('getCache');
$method->setAccessible(true);
Config::set('Model', 'MockCache');
if (!class_exists('MockCache')) {
$this->getMock('Cache', array(), array(), 'MockCache');
}
$this->assertInstanceOf('MockCache', $method->invoke($this->model));
}
public function testCacheKey()
{
$model = new ReflectionClass('MockModel');
$method = $model->getMethod('cacheKey');
$method->setAccessible(true);
Config::set('Model', 'MockCache');
if (!class_exists('MockCache')) {
$this->getMock('Cache', array(), array(), 'MockCache', false);
}
if (!class_exists('MockCacheKey')) {
$this->getMock('CacheKey', array(), array(), 'MockCacheKey', false);
}
$this->assertInstanceOf('MockCacheKey', $method->invoke($this->model, 'name'));
}
public function testAddCleanCache()
{
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('addCleanCache');
$method->setAccessible(true);
$key = $this->getMock('Key', array('set', 'get'));
$method->invoke($this->model, $key);
$method->invoke($this->model, $key);
$method->invoke($this->model, $key);
$this->assertAttributeEquals(array($key, $key, $key), 'caches_clean', $this->model);
}
public function testCleanCaches()
{
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('addCleanCache');
$method->setAccessible(true);
$key = $this->getCacheKeyMockDel(3);
$method->invoke($this->model, $key);
$method->invoke($this->model, $key);
$method->invoke($this->model, $key);
$this->assertAttributeEquals(array($key, $key, $key), 'caches_clean', $this->model);
$model = new ReflectionClass('SqlModel');
$method = $model->getMethod('cleanCaches');
$method->setAccessible(true);
$method->invoke($this->model, $key);
$this->assertAttributeEquals(array(), 'caches_clean', $this->model);
}
protected function getCacheKeyMockGetSet()
{
$key = $this->getMock('Key', array('set', 'get'));
$key
->expects($this->any())
->method('set')
->with($this->anything())
->will($this->returnValue(true));
$key
->expects($this->any())
->method('get')
->will($this->returnValue(false));
return $key;
}
protected function getCacheKeyMockDel($count)
{
$key = $this->getMock('Key', array('del'));
$key
->expects($this->exactly($count))
->method('del')
->will($this->returnValue(true));
return $key;
}
public function tearDown()
{
Config::getInstance()->offsetUnset('Db');
$config = new ReflectionClass('Db');
$registry = $config->getProperty('connections');
$registry->setAccessible(true);
$registry->setValue('Db', array());
unset_new_overload();
}
protected function newCallback($className)
{
switch ($className) {
case 'MockDbDriver':
return 'MockDbDriver';
case 'CacheKey':
return 'MockCacheKey';
default:
return $className;
}
}
}

5
Tests/model/testData.xml Normal file
View File

@ -0,0 +1,5 @@
<?xml version="1.0" ?>
<dataset>
<table id="1" content="Hello buddy!" user="joe" created="2010-04-24 17:15:23" />
<table id="2" content="I like it!" user="nancy" created="2010-04-26 12:14:20" />
</dataset>

View File

@ -0,0 +1,9 @@
<?xml version="1.0" ?>
<dataset>
<table id="1" content="Hello buddy!" user="joe" created="2010-04-24 17:15:23" />
<table id="2" content="I like it!" user="nancy" created="2010-04-26 12:14:20" />
<table id="3" content="some test content" user="tony" created="2011-11-07 11:35:20" />
<table id="4" content="some test content" user="tony" created="2011-11-07 11:35:20" />
<table id="5" content="some test content" user="tony" created="2011-11-07 11:35:20" />
<table id="6" content="some test content" user="tony" created="2011-11-07 11:35:20" />
</dataset>

19
Tests/model/testdb.sql Normal file
View File

@ -0,0 +1,19 @@
--
-- База данных: `testdb`
--
CREATE DATABASE `testdb` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `testdb`;
-- --------------------------------------------------------
--
-- Структура таблицы `table`
--
CREATE TABLE IF NOT EXISTS `table` (
`id` int(3) NOT NULL AUTO_INCREMENT,
`content` varchar(255) NOT NULL,
`user` varchar(255) NOT NULL,
`created` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

33
Tests/phpunit.xml Normal file
View File

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="bootstrap.php"
backupGlobals="true"
backupStaticAttributes="false"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
forceCoversAnnotation="false"
mapTestClassNameToCoveredClassName="false"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
syntaxCheck="false"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"
strict="true"
verbose="true">
<filter>
<blacklist>
<directory>../util/FirePHPCore-0.3.2</directory>
<directory>.</directory>
<file>../face/cache/autoload.php</file>
</blacklist>
</filter>
<php>
<var name="DB_DSN" value="mysql:dbname=testdb;host=localhost"/>
<var name="DB_USER" value="root"/>
<var name="DB_PASSWD" value="1234"/>
<var name="DB_DBNAME" value="testdb"/>
</php>
</phpunit>

View File

@ -0,0 +1,106 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for RedisDebug class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../util/profiler/CommandProfiler.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
require_once dirname(__FILE__) . '/../../redis/RedisDebug.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class RedisDebugTest extends PHPUnit_Framework_TestCase
{
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
/**
* @group Redis
*/
public function testConstructException()
{
$this->setExpectedException('GeneralException');
$redisDebug = new RedisDebug('redis');
}
/**
* @group Redis
*/
public function testConstructGood()
{
$mock = $this->getMock('Redis');
$redisDebug = new RedisDebug($mock);
$class = new ReflectionClass('RedisDebug');
$redis = $class->getProperty('redis');
$redis->setAccessible(true);
$redis = $redis->getValue($redisDebug);
$this->assertSame($mock, $redis);
}
/**
* @runInSeparateProcess
* @group Redis
*/
public function testCallSimpleParams()
{
Config::set('PROFILER', true);
$mock = $this->getMock('Redis', array('connect'));
$mock->expects($this->once())
->method('connect')
->with($this->equalTo('localhost'), $this->equalTo(4322))
->will($this->returnValue(true));
$redisDebug = new RedisDebug($mock);
$this->assertTrue($redisDebug->connect('localhost', 4322));
}
/**
* @runInSeparateProcess
* @group Redis
*/
public function testCallArrayParam()
{
Config::set('PROFILER', true);
$mock = $this->getMock('Redis', array('connect'));
$mock->expects($this->once())
->method('connect')
->with($this->equalTo(array('localhost', 4322)))
->will($this->returnValue(true));
$redisDebug = new RedisDebug($mock);
$this->assertTrue($redisDebug->connect(array('localhost', 4322)));
}
/**
* @runInSeparateProcess
* @group Redis
*/
public function testCallUndefinedMethod()
{
Config::set('PROFILER', true);
$mock = $this->getMock('Redis', array('connect'));
$redisDebug = new RedisDebug($mock);
$this->setExpectedException('PHPUnit_Framework_Error', 'call_user_func_array() expects parameter 1 to be a valid callback, class \'Mock_Redis_');
$this->assertNull($redisDebug->nothing('localhost', 4322));
}
}

View File

@ -0,0 +1,168 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for RedisManager class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../redis/RedisManager.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class RedisManagerTest extends PHPUnit_Framework_TestCase
{
private $connections;
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
$this->getMock('Redis');
$conf = Config::getInstance();
if ($conf->offsetExists('Redis')) {
$conf->offsetUnset('Redis');
}
$class = new ReflectionClass('RedisManager');
$this->connections = $class->getProperty('connections');
$this->connections->setAccessible(true);
$this->connections->setValue(null, array());
set_new_overload(array($this, 'newCallback'));
}
/**
* @group Redis
*/
public function testConnectNoAnyConfig()
{
$this->setExpectedException('GeneralException', 'Redis config no existence');
RedisManager::connect();
}
/**
* @group Redis
*/
public function testConnectWrongPersistantConfig()
{
Config::set('Redis', array('new' => 'some'));
$this->setExpectedException('GeneralException', 'Connection parameters must be an array');
RedisManager::connect('new');
}
/**
* @group Redis
*/
public function testConnectDefaultConfig()
{
Config::set('Redis', array('default' => 'some'));
$this->setExpectedException('GeneralException', 'Connection parameters must be an array');
RedisManager::connect();
}
/**
* @group Redis
*/
public function testConnectFailedConnection()
{
Config::set('Redis', array('new' => array('host' => 'error', 'port' => 2023, 'database' => 'some')));
$this->setExpectedException('GeneralException', 'Failed to connect to Redis server at');
RedisManager::connect('new');
}
/**
* @group Redis
*/
public function testConnectEstablishedConnectionNoDb()
{
Config::set('Redis', array('new' => array('host' => true, 'port' => 2023, 'database' => 'some')));
$this->setExpectedException('GeneralException', 'Failed to select Redis database with index');
RedisManager::connect('new');
}
/**
* @group Redis
*/
public function testConnectionGood()
{
Config::set('Redis', array('new' => array('host' => true, 'port' => 2023, 'database' => true)));
$redis = RedisManager::connect('new');
$this->assertInstanceOf('RedisMock', $redis);
}
/**
* @runInSeparateProcess
* @group Redis
*/
public function testConnectWithDebug()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('RedisDebug');
Config::set('Redis', array('new' => array('host' => true, 'port' => 2023, 'database' => true)));
$redis = RedisManager::connect('new');
$this->assertInstanceOf('RedisDebugMock', $redis);
}
/**
* @group Redis
*/
public function testConnectWithConfigArray()
{
$config = array('host' => true, 'port' => 2023, 'database' => true);
$redis = RedisManager::connect('nsew', $config);
$this->assertInstanceOf('RedisMock', $redis);
}
protected function newCallback($className)
{
switch ($className) {
case 'Redis':
return 'RedisMock';
case 'RedisDebug':
return 'RedisDebugMock';
default:
return $className;
}
}
public function tearDown()
{
unset_new_overload();
}
}
class RedisMock
{
public function connect($host, $port)
{
if ($host === true) {
return true;
}
return false;
}
public function select($dbname)
{
if ($dbname === true) {
return true;
}
return false;
}
}
class RedisDebugMock extends RedisMock
{
}

View File

@ -0,0 +1,110 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-15
*
* Unit tests for SessionModel class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/DbDriver.php';
require_once dirname(__FILE__) . '/../model/MyDbDriver.php';
require_once dirname(__FILE__) . '/../../model/Model.php';
require_once dirname(__FILE__) . '/../../model/SqlModel.php';
require_once dirname(__FILE__) . '/../../session/Session.model.php';
class SessionModelTest extends PHPUnit_Framework_TestCase
{
protected $model;
public function setUp()
{
$conf = array('default' => array('driver' => 'MockDbDriver', 'hostname' => 'somehost', 'database' => 'db', 'username' => 'test', 'password' => '1234'));
if (!class_exists('MockDbDriver')) {
$this->getMockForAbstractClass('MyDbDriver', array($conf), 'MockDbDriver', false);
}
if (!class_exists('MockDbExpr')) {
$this->getMock('DbExpr', array(), array(), 'MockDbExpr', false);
}
Config::set('Db', $conf);
set_new_overload(array($this, 'newCallback'));
}
public function testOpen()
{
$this->model = new SessionModel();
$this->assertTrue($this->model->open('path', 'name'));
}
public function testClose()
{
$this->model = new SessionModel();
$this->assertTrue($this->model->close());
}
public function testRead()
{
$this->model = new SessionModel();
$this->assertEquals('data', $this->model->read(1));
}
public function testWrite()
{
$this->model = new SessionModel();
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$this->assertEmpty(Env::Server('HTTP_X_FORWARDED_FOR'));
$this->assertTrue($this->model->write(2, 'user|.s:20;id=2;id=2'));
}
public function testDestroy()
{
$this->model = new SessionModel();
$this->assertTrue($this->model->destroy(2));
}
public function testGc()
{
$this->model = new SessionModel();
$this->assertTrue($this->model->gc(2000));
}
public function testDestroyByUserId()
{
$this->model = new SessionModel();
$this->assertEquals('session', $this->model->destroyByUserId(12));
}
public function tearDown()
{
Config::getInstance()->offsetUnset('Db');
$config = new ReflectionClass('Db');
$registry = $config->getProperty('connections');
$registry->setAccessible(true);
$registry->setValue('Db', array());
unset_new_overload();
}
protected function newCallback($className)
{
switch ($className) {
case 'DbExpr':
return 'MockDbExpr';
case 'MockDbDriver':
return 'MockDbDriver';
case 'CacheKey':
return 'MockCacheKey';
default:
return $className;
}
}
}

View File

@ -0,0 +1,187 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-25
*
* Unit tests for Session class
* @TODO: Session::destroy() - check if session was started
* @TODO: Session::destroy() - uncheck started flag after destroy
*/
require_once dirname(__FILE__) . '/../../session/Session.php';
class SessionTest extends PHPUnit_Framework_TestCase
{
private $started = null;
protected function setUp()
{
$class = new ReflectionClass('Session');
$this->started = $class->getProperty('started');
$this->started->setAccessible(true);
Session::start();
$sid = Session::getId();
if (!empty($sid)) {
Session::destroy();
}
$this->started->setValue(null, false);
}
public function testStart()
{
Session::start();
$this->assertAttributeEquals(true, 'started', 'Session');
}
public function testSetGet()
{
Session::set('one', 1);
Session::set('two', 'three');
Session::set(array('first' => '1st', 'second' => '2nd'));
$this->assertSame('1st', Session::get('first'));
$this->assertSame('three', Session::get('two'));
$this->assertNotEquals('three', Session::get('thr'));
}
public function testNullKey()
{
$this->assertNull(Session::get());
Session::start();
$this->assertEmpty(Session::get());
}
public function testReturnDefaultValue()
{
Session::start();
$this->assertSame(1, Session::get('key', 1));
}
public function testDestroyedGet()
{
$this->assertFalse($this->started->getValue());
$_COOKIE[session_name()] = session_name();
$this->assertSame(1, Session::get('key', 1));
}
public function testDel()
{
Session::set('one', 1);
Session::set('two', 'three');
$this->assertSame('three', Session::get('two'));
Session::del('two');
$this->assertNull(Session::get('two'));
}
public function testDestroyedDel()
{
Session::del('two');
$this->assertNull(Session::get('two'));
$this->assertFalse($this->started->getValue());
$_COOKIE[session_name()] = session_name();
Session::del('two');
$this->assertNull(Session::get('two'));
}
public function testRegenerateId()
{
$this->assertEmpty(session_id());
Session::start();
$ssid = Session::getId();
$this->assertNotEmpty($ssid);
Session::regenerateId();
$new_ssid = Session::getId();
$this->assertNotEmpty($new_ssid);
$this->assertNotEquals($new_ssid, $ssid);
}
public function testRememberUntil()
{
Session::start();
$ssid = Session::getId();
$params = session_get_cookie_params();
Session::rememberUntil(400);
$new_ssid = Session::getId();
$new_params = session_get_cookie_params();
$this->assertNotEquals($ssid, $new_ssid);
$this->assertNotEquals($params, $new_params);
$this->assertSame(400, $new_params['lifetime']);
Session::rememberUntil();
$new_params = session_get_cookie_params();
$this->assertSame(0, $new_params['lifetime']);
}
public function testForget()
{
Session::start();
$ssid = Session::getId();
Session::forget();
$new_ssid = Session::getId();
$new_params = session_get_cookie_params();
$this->assertNotEquals($ssid, $new_ssid);
$this->assertSame(0, $new_params['lifetime']);
}
public function testRemember()
{
Session::start();
$ssid = Session::getId();
Session::remember();
$new_params = session_get_cookie_params();
$this->assertSame(1209600, $new_params['lifetime']);
Session::remember(-30);
$new_params = session_get_cookie_params();
$this->assertSame(1209600, $new_params['lifetime']);
Session::remember(530);
$new_params = session_get_cookie_params();
$this->assertSame(530, $new_params['lifetime']);
}
public function testExpireSessionCookie()
{
Session::start();
$params = session_get_cookie_params();
$_COOKIE[session_name()] = true;
Session::expireSessionCookie();
$this->assertNotNull($_COOKIE);
}
public function testSetSessionHandler()
{
Session::setSessionHandler('Handler');
$this->assertTrue(TRUE);
}
}
class Handler
{
public static function open()
{
}
public static function close()
{
}
public static function read()
{
}
public static function write()
{
}
public static function destroy()
{
}
public static function gc()
{
}
}

View File

@ -0,0 +1,176 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-28
*
* Unit tests for AutoloadBuilder class
*/
require_once dirname(__FILE__) . '/../../util/AutoloadBuilder.php';
/**
* @TODO: AutoloadBuilder - fix writing to file: construct array first, write to file next - atomic operation
*/
class AutoloadBuilderTest extends PHPUnit_Framework_TestCase
{
private static $inc_dirs = array();
private static $file;
private static $path;
private static $lib_path;
private static $app;
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
/**
* @TODO: Load->buildAutoload() - uses two paths - PATH . '/' . APP . '/src' and PATH . '/lib' those are not checked. Can couse error.
*/
public static function setUpBeforeClass()
{
self::$path = realpath(dirname(__FILE__) . '/../../../..');
self::$lib_path = realpath(dirname(__FILE__) . '/../..');
self::$app = 'lib/core/tests/face';
self::$file = self::$path . '/' . self::$app . '/cache/autoload.php';
self::$inc_dirs[self::$path . '/' . self::$app . '/src'] = true;
self::$inc_dirs[self::$path . '/' . self::$app . '/cache'] = true;
self::$inc_dirs[self::$lib_path . '/'] = true;
foreach (self::$inc_dirs as $dir => &$is_exist) {
if (!file_exists($dir)) {
$is_exist = false;
mkdir($dir, 0777, true);
}
}
}
/**
* @TODO: AutoloadBuilder - check input params: string for filename, array for dirs
* @runInSeparateProcess
*/
public function testBuildParams()
{
$this->setConstants();
$autoload = self::$file;
$dirs = 'string';
$builder = new AutoloadBuilder($autoload, $dirs);
$this->setExpectedException('PHPUnit_Framework_Error');
$builder->build();
}
/**
* @runInSeparateProcess
*/
public function testBuild()
{
$this->setConstants();
$builder = new AutoloadBuilder(self::$file, array_keys(self::$inc_dirs));
$this->assertFileNotExists(self::$file);
$builder->build();
$this->assertFileExists(self::$file);
$array = require self::$file;
$this->assertFileExists(self::$file);
$this->assertInternalType('array', $array);
$this->assertNotEmpty($array);
$this->assertArrayHasKey('AutoloadBuilder', $array);
$this->assertArrayHasKey('Load', $array);
}
/**
* @runInSeparateProcess
*/
public function testBuildWithExcluded()
{
$this->setConstants();
$builder = new AutoloadBuilder(self::$file, array_keys(self::$inc_dirs), array(self::$lib_path . '/app/'));
$this->assertFileNotExists(self::$file);
$builder->build();
$this->assertFileExists(self::$file);
$array = require self::$file;
$this->assertInternalType('array', $array);
$this->assertNotEmpty($array);
$this->assertArrayHasKey('AutoloadBuilder', $array);
$this->assertArrayNotHasKey('FrontController', $array);
$this->assertArrayNotHasKey('AjaxAction', $array);
}
/**
* @runInSeparateProcess
*/
public function testAccessDenied()
{
$this->setConstants();
$this->assertFileNotExists(self::$file);
$path = dirname(self::$file);
chmod($path, 0400);
$builder = new AutoloadBuilder(self::$file, array(self::$path . '/' . self::$app . '/src', self::$path . '/' . self::$app . '/cache', self::$path . '/lib'));
$this->setExpectedException('PHPUnit_Framework_Error', 'Permission denied');
$builder->build();
chmod(self::$file, 0777);
}
public static function tearDownAfterClass()
{
if (file_exists(self::$file)) {
unlink(self::$file);
}
foreach (self::$inc_dirs as $dir => $is_exist) {
if (!$is_exist) {
self::rrmdir($dir);
}
}
self::rrmdir(self::$path . '/' . self::$app);
}
private function setConstants()
{
if (!defined('PATH')) {
define('PATH', realpath(dirname(__FILE__) . '/../../../..'));
}
if (!defined('APP')) {
define('APP', 'lib/core/tests/face');
}
}
public static function rrmdir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir . "/" . $object) == "dir") {
self::rrmdir($dir . "/" . $object);
} else {
unlink($dir . "/" . $object);
}
}
}
reset($objects);
rmdir($dir);
}
}
}

View File

@ -0,0 +1,128 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-..
*
* Unit tests for AutoloadBuilder class
*/
require_once 'vfsStream/vfsStream.php';
require_once dirname(__FILE__) . '/../../util/AutoloadBuilder.php';
/**
* @TODO: AutoloadBuilder - fix writing to file: construct array first, write to file next - atomic operation
* @TODO: vfsStream doesn't work with SPLFIleObject->getRealPath - $file->getPath .'/'. $file->getFIleName instead
*/
class AutoloadBuilderTestVFS extends PHPUnit_Framework_TestCase
{
private static $inc_dirs = array();
private static $file;
private $root;
private $array = array();
/**
* @TODO: Load->buildAutoload() - uses two paths - PATH . '/' . APP . '/src' and PATH . '/lib' those are not checked. Can couse error.
*/
public function setUp()
{
if (!defined('PATH')) {
define('PATH', realpath(dirname(__FILE__) . '/../../../..'));
}
if (!defined('APP')) {
define('APP', 'lib/core/tests/face');
}
vfsStreamWrapper::register();
$this->root = vfsStream::create(
array(
'cache' => array(
'face' => array()
),
'face' => array(
'src' => array(
'Registry.php' => ' class Registry'
)
),
'lib' => array(
'Registry.php' => ' class Registry',
'Load.php' => 'class Load extends Registry',
'devel.config' => ' development config file'
)
)
);
vfsStreamWrapper::setRoot($this->root);
}
public function testVFS()
{
$builder = new AutoloadBuilder(vfsStream::url('root/cache/face/autoload.php'), array(vfsStream::url('root/lib'), vfsStream::url('root/face/src')));
$this->assertTrue($this->root->hasChild('lib'));
$this->assertFalse($this->root->hasChild('nochild'));
$this->assertFalse($this->root->hasChild('cache/face/autoload.php'));
$handle = fopen(vfsStream::url('root/cache/face/autoload.php'), 'w');
fwrite($handle, 'new string');
fclose($handle);
$this->assertTrue($this->root->hasChild('cache/face/autoload.php'));
$this->assertSame('new string', $this->root->getChild('cache/face/autoload.php')->getContent());
}
public function testBuild()
{
$this->markTestSkipped(
'AutoloadBuilder uses $file->getRealPath method, that doesn`t work properly with vfsStream.'
);
$builder = new AutoloadBuilder(vfsStream::url('root/cache/face/autoload.php'), array(vfsStream::url('root/lib'), vfsStream::url('root/face/src')));
$builder->build();
$this->assertTrue($this->root->hasChild('cache/face/autoload.php'));
$this->assertFileExists(vfsStream::url('root/cache/face/autoload.php'));
}
public function testAutoloadArray()
{
$this->markTestSkipped(
'AutoloadBuilder uses $file->getRealPath method, that doesn`t work properly with vfsStream.'
);
$this->assertFileNotExists(vfsStream::url('root/cache/face/autoload.php'));
$builder = new AutoloadBuilder(vfsStream::url('root/cache/face/autoload.php'), array(vfsStream::url('root/lib'), vfsStream::url('root/face/src')));
$builder->build();
$this->assertFileExists(vfsStream::url('root/cache/face/autoload.php'));
$this->assertEmpty($this->array);
$this->array = require vfsStream::url('root/cache/face/autoload.php');
$this->assertInternalType('array', $this->array);
$this->assertArrayHasKey('Load', $this->array);
$this->assertArrayNotHasKey('Key', $this->array);
$this->assertSame(2, count($this->array));
}
public function testAutoloadHasNoAccess()
{
$this->markTestSkipped(
'AutoloadBuilder uses $file->getRealPath method, that doesn`t work properly with vfsStream.'
);
$this->assertFileNotExists(vfsStream::url('root/cache/face/autoload.php'));
$autoloadFIle = new vfsStreamFile('cache/face/autoload.php', 0400);
$this->root->addChild($autoloadFIle);
$builder = new AutoloadBuilder(vfsStream::url('root/cache/face/autoload.php'), array(vfsStream::url('root/lib'), vfsStream::url('root/face/src')));
$builder->build();
$this->assertFileExists(vfsStream::url('root/cache/face/autoload.php'));
$this->assertEmpty($this->root->getChild('cache/face/autoload.php')->getContent());
$this->array = require vfsStream::url('root/cache/face/autoload.php');
$this->assertInternalType('integer', $this->array);
$autoloadFIle->chmod(0777);
$builder = new AutoloadBuilder(vfsStream::url('root/cache/face/autoload.php'), array(vfsStream::url('root/lib'), vfsStream::url('root/face/src')));
$builder->build();
$this->assertFileExists(vfsStream::url('root/cache/face/autoload.php'));
$this->assertNotEmpty($this->root->getChild('cache/face/autoload.php')->getContent());
$this->array = require vfsStream::url('root/cache/face/autoload.php');
$this->assertInternalType('array', $this->array);
$this->assertNotEmpty($this->array);
}
}

View File

@ -0,0 +1,42 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-28
*
* Unit tests for CommandProfiler class
*/
require_once dirname(__FILE__) . '/../../../util/profiler/CommandProfiler.php';
class CommandProfilerTest extends PHPUnit_Framework_TestCase
{
private $profiler;
public function setUp()
{
$this->profiler = new CommandProfiler('method', 'exec');
$this->profiler->end();
}
public function testGetEllapsed()
{
$this->assertGreaterThan(0, $this->profiler->getElapsed());
}
public function testGetType()
{
$this->assertSame('method', $this->profiler->getType());
$this->assertNotEquals('argument', $this->profiler->getType());
}
public function testGetCommand()
{
$this->assertSame('exec', $this->profiler->getCommand());
$this->assertNotEquals('grep', $this->profiler->getCommand());
}
}

View File

@ -0,0 +1,359 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-28
*
* Unit tests for CommandProfiler class
*/
require_once dirname(__FILE__) . '/../../../Registry.php';
require_once dirname(__FILE__) . '/../../../Config.php';
require_once dirname(__FILE__) . '/../../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../../util/FirePHPCore-0.3.2/lib/FirePHPCore/fb.php';
require_once dirname(__FILE__) . '/../../../util/profiler/Profiler.php';
/**
* @TODO: Profiler->getJson() hardly depends on FB library
*/
class ProfilerTest extends PHPUnit_Framework_TestCase
{
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
return parent::run($result);
}
public function setUp()
{
set_new_overload(array($this, 'newCallback'));
}
/**
* @runInSeparateProcess
*/
public function testGetInstaceNoDebug()
{
Config::set('PROFILER', false);
$this->setExpectedException('GeneralException', 'Need turn PROFILER before use.');
Profiler::getInstance();
}
/**
* @runInSeparateProcess
*/
public function testGetInstance()
{
Config::set('PROFILER', true);
$profiler = Profiler::getInstance();
$this->assertInstanceOf('Profiler', $profiler);
$this->assertSame($profiler, Profiler::getInstance());
}
/**
* @runInSeparateProcess
*/
public function testProfilerCommand()
{
Config::set('PROFILER', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$this->assertInstanceOf('CommandProfiler', $cmdProfiler);
}
/**
* @runInSeparateProcess
*/
public function testStartEndNoCommandProfiler()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$profiler = Profiler::getInstance();
$profiler->start();
$result = $profiler->end('<body></body>');
$this->assertNotEquals('<body></body>', $result);
$this->assertStringStartsWith('<body>', $result);
$this->assertStringEndsWith(']<br/></div></body>', $result);
$this->assertContains('<div style="clear:both; font:12px monospace; margin: 5px; white-space: pre;">', $result);
$this->assertSame('html', $profiler->end('html'));
}
/**
* @runInSeparateProcess
*/
public function testStartEndWithCommandProfiler()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$profiler->start();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$this->assertNotNull($cmdProfiler);
$result = $profiler->end('<body></body>');
$this->assertNotEquals('<body></body>', $result);
$this->assertStringEndsNotWith(']<br/></div></body>', $result);
$this->assertContains('Queries: 1 [0 ms]<br/>() [0ms] <br/>', $result);
}
/**
* @runInSeparateProcess
*/
public function testStartEndWithCommandProfilerWithNonDetails()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$profiler->start();
$result = $profiler->end('<body></body>');
$this->assertNotEquals('<body></body>', $result);
$this->assertContains('Queries not counted.', $result);
}
/**
* @runInSeparateProcess
*/
public function testStartEndWithCommandProfilerWithNonDetailsButExistingQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$profiler->start();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$result = $profiler->end('<body></body>');
$this->assertNotEquals('<body></body>', $result);
$this->assertStringEndsNotWith(']<br/></div></body>', $result);
$this->assertContains('Queries: 1', $result);
}
/**
* @runInSeparateProcess
*/
public function testStartEndWithCommandProfilerWithDetailsButNonQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$profiler->start();
$result = $profiler->end('<body></body>');
$this->assertNotEquals('<body></body>', $result);
$this->assertStringEndsWith(']<br/></div></body>', $result);
$this->assertContains('Queries: 0', $result);
}
/**
* @runInSeparateProcess
*/
public function testGetJSON()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$fire_php_mock = $this->getMockBuilder('FirePHP')
->disableOriginalConstructor()
->setMethods(array('__construct', 'fb'))
->getMock();
$fire_php_mock->expects($this->exactly(2))
->method('fb')
->with($this->anything(), $this->logicalAnd($this->logicalXor($this->anything(), $this->stringContains('Queries not'))), $this->logicalXor($this->anything(), $this->stringContains('Queries: 0'))); // Expected "Queries: 1"
$reflection_property = new ReflectionProperty('FirePHP', 'instance');
$reflection_property->setAccessible(true);
$reflection_property->setValue($fire_php_mock);
$this->assertNull($profiler->getJson());
}
/**
* @runInSeparateProcess
*/
public function testGetJSONWithNonDetails()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$fire_php_mock = $this->getMockBuilder('FirePHP')
->disableOriginalConstructor()
->setMethods(array('__construct', 'fb'))
->getMock();
$fire_php_mock->expects($this->exactly(2))
->method('fb')
->with($this->anything(), $this->logicalAnd($this->logicalXor($this->anything(), $this->stringContains('Queries: 1'))), $this->logicalXor($this->anything(), $this->stringContains('Queries: 0'))); // expected "Queries not counted"
$reflection_property = new ReflectionProperty('FirePHP', 'instance');
$reflection_property->setAccessible(true);
$reflection_property->setValue($fire_php_mock);
$this->assertNull($profiler->getJson());
}
/**
* @runInSeparateProcess
*/
public function testGetJSONWithNonDetailsButExistingQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$fire_php_mock = $this->getMockBuilder('FirePHP')
->disableOriginalConstructor()
->setMethods(array('__construct', 'fb'))
->getMock();
$fire_php_mock->expects($this->exactly(2))
->method('fb')
->with($this->anything(), $this->logicalAnd($this->logicalXor($this->anything(), $this->stringContains('Queries not counted'))), $this->logicalXor($this->anything(), $this->stringContains('Queries: 0'))); // expected "Queries: 1"
$reflection_property = new ReflectionProperty('FirePHP', 'instance');
$reflection_property->setAccessible(true);
$reflection_property->setValue($fire_php_mock);
$this->assertNull($profiler->getJson());
}
/**
* @runInSeparateProcess
*/
public function testGetJSONWithDetailsButNonQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$fire_php_mock = $this->getMockBuilder('FirePHP')
->disableOriginalConstructor()
->setMethods(array('__construct', 'fb'))
->getMock();
$fire_php_mock->expects($this->exactly(2))
->method('fb')
->with($this->anything(), $this->logicalAnd($this->logicalXor($this->anything(), $this->stringContains('Queries not counted'))), $this->logicalXor($this->anything(), $this->stringContains('Queries: 1'))); // expected "Queries: 0"
$reflection_property = new ReflectionProperty('FirePHP', 'instance');
$reflection_property->setAccessible(true);
$reflection_property->setValue($fire_php_mock);
$this->assertNull($profiler->getJson());
}
/**
* @runInSeparateProcess
*/
public function testGetCLI()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
*/
public function testGetCLIWithNonDetails()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries not counted', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
*/
public function testGetCLIWithNonDetailsButExistingQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
*/
public function testGetCLIWithDetailsButNonQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries: 0', Profiler::getInstance()->getCli());
}
public function tearDown()
{
// if (!is_null(Config::get('DEBUG'))) {
// $debug = Config::get('DEBUG') ? 'TRUE' : 'FALSE';
// echo PHP_EOL . __CLASS__ . ' ' . $debug . PHP_EOL;
// } else {
// echo PHP_EOL . __CLASS__ . ' ' . 'DEBUG NOT DEFINED' . PHP_EOL;
// }
unset_new_overload();
}
protected function newCallback($className)
{
switch ($className) {
case 'CommandProfiler':
return 'CommandProfilerMock';
default:
return $className;
}
}
}
//
//
//class CommandProfilerMock
//{
//
// public function __construct($type, $command)
// {
// }
//
// public function getCommand()
// {
// return 'command';
// }
//
// public function getType()
// {
// return 'type';
// }
//
// public function getElapsed()
// {
// return 10;
// }
//}

View File

@ -0,0 +1,27 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-07
*
* Unit tests for RegexValdator class
*/
require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../validator/RegexValidator.php';
require_once dirname(__FILE__) . '/../../validator/EmailValidator.php';
class EmailValidatorTest extends PHPUnit_Framework_TestCase
{
public function testConstruct()
{
$validator = new EmailValidator();
$this->assertTrue($validator->isValid('mail@mail.erw'));
$this->assertFalse($validator->isValid('asdasd'));
}
}

View File

@ -0,0 +1,35 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-07
*
* Unit tests for RegexValdator class
*/
require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../validator/EqualValidator.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
class EqualValidatorTest extends PHPUnit_Framework_TestCase
{
public function testConstructor()
{
$validator = new EqualValidator('token');
$this->assertFalse($validator->isValid('not token'));
$this->assertTrue($validator->isValid('token'));
}
public function testNullToken()
{
$validator = new EqualValidator(null);
$this->setExpectedException('InitializationException','Token not defined');
$validator->isValid('not token');
}
}

View File

@ -0,0 +1,37 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-07
*
* Unit tests for RegexValdator class
*/
require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../validator/NotEmptyValidator.php';
class NotEmptyValidatorTest extends PHPUnit_Framework_TestCase
{
public function testValidator()
{
$validator = new NotEmptyValidator();
$this->assertFalse($validator->isValid(''));
$this->assertTrue($validator->isValid('token'));
$this->assertTrue($validator->isValid(1212));
$this->assertTrue($validator->isValid(array(1,2,2)));
$this->assertFalse($validator->isValid(array()));
$this->assertNotEmpty($validator->getMessage());
}
public function testEmptyValue()
{
$validator = new NotEmptyValidator(null);
$this->assertFalse($validator->isValid(null));
}
}

View File

@ -0,0 +1,75 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-07
*
* Unit tests for RegexValdator class
*/
require_once dirname(__FILE__) . '/../../validator/iValidator.php';
require_once dirname(__FILE__) . '/../../validator/Validator.php';
require_once dirname(__FILE__) . '/../../validator/RegexValidator.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class RegexValidatorTest extends PHPUnit_Framework_TestCase
{
public function testIsValid()
{
$validator = new RegexValidator('/^[a-z]*$/i');
$this->assertTrue($validator->isValid('anTon', array(1,2,3)));
$this->assertFalse($validator->isValid('12ejkas,.21'));
}
public function testGetMessage()
{
$validator = new RegexValidator('/^[a-z0-9]*$/i');
$this->assertTrue($validator->isValid('ton342ad21y'));
$this->assertEmpty($validator->getMessage());
$this->assertFalse($validator->isValid('!!#asd'));
$this->assertNotEmpty($validator->getMessage());
}
public function testSetMessage()
{
$validator = new RegexValidator('/a/i');
$validator->isValid('2sa131');
$this->assertEmpty($validator->getMessage());
$validator->setMessage('i am ok');
$validator->isValid('2131');
$this->assertSame('i am ok', $validator->getMessage());
}
public function testNullMessage()
{
$validator = new RegexValidator('/a/i');
$validator->setMessage(null, null);
$this->setExpectedException('GeneralException', 'Message template "regex_not_match" unknown.');
$validator->isValid('1212');
}
/**
* @TODO: RegexValidator - wrong regex throws an error. Check this.
*/
public function testWrongRegexp()
{
$validator = new RegexValidator('/^[a-z][0-9]$*/i');
$this->setExpectedException('PHPUnit_Framework_Error');
$this->assertFalse($validator->isValid('to423$%ny'));
}
public function testRegexReturnsFalse()
{
$validator = new RegexValidator('/(?:\D+|<\d+>)*[!?]/');
$this->setExpectedException('GeneralException', 'regex');
$this->assertFalse($validator->isValid('foobar foobar foobar'));
}
}

145
Tests/view/PHPViewTest.php Normal file
View File

@ -0,0 +1,145 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for PHPView class
*/
require_once dirname(__FILE__) . '/../../view/iView.php';
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../view/helpers/ViewHelper.php';
require_once dirname(__FILE__) . '/../../view/helpers/TitleViewHelper.php';
require_once dirname(__FILE__) . '/../../view/PHPView.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../exception/InitializationException.php';
require_once 'vfsStream/vfsStream.php';
class PHPViewTest extends PHPUnit_Framework_TestCase
{
private $view;
private $template;
public function setUp()
{
vfsStreamWrapper::register();
vfsStream::setup();
$root = vfsStream::create(array());
vfsStreamWrapper::setRoot($root);
$views_dir = vfsStream::newDirectory('views');
$this->template = new vfsStreamFile('test.phtml');
$this->template->setContent('<?php echo $a ." " . $b . " " . $c; ?>');
$views_dir->addChild($this->template);
$root->addChild($views_dir);
$this->view = new PHPView(array('path' => vfsStream::url('root/views/')));
}
public function testPHPViewConstructor()
{
$this->assertInstanceOf('PHPView', $this->view);
$this->assertSame('vfs://root/views/', $this->view->getPath());
}
public function testPHPViewNullConstructor()
{
$this->setExpectedException('InitializationException', 'Configuration must have a "path" set.');
$view = new PHPView(null);
}
public function testAssign()
{
$this->view->assign('a', 'c');
$this->view->append('b', 'b');
$this->view->prepend('c', 'a');
$this->assertStringStartsWith('c b a', $this->view->fetch('test'));
}
public function testAssignObject()
{
$obj = $this->getMock('NewClass');
$obj->a = 'one';
$obj->b = 'two';
$obj->c = 'three';
$this->view->assignObject($obj);
$this->assertSame('one two three', $this->view->fetch('test'));
}
public function testEscape()
{
$result = $this->view->escape('"<>"');
$this->assertSame('&quot;&lt;&gt;&quot;', $result);
}
public function testCall()
{
$this->view->title('New title');
$this->assertContains('New title', Registry::get('TitleViewHelper'));
}
public function testIllegalCall()
{
$this->setExpectedException('GeneralException', 'View helper "WriteViewHelper" not found.');
$this->view->write('tony');
}
/**
* @TODO: PHPView: check views path for ending slash in getTemplatePath()
*/
public function testFetch()
{
$this->assertNotSame('test phtml view ', $this->template->getContent());
$this->view->assign('a', 'some');
$this->view->assign('b', 'some');
$this->view->assign('c', 'some');
$result = $this->view->fetch('test');
$this->assertNotEmpty($result);
$this->assertSame('some some some', $result);
}
public function testAppend()
{
$this->view->assign('a', 'some');
$this->view->append('b', 'some');
$this->view->assign('c', 'some');
$this->view->append('c', 'end');
$result = $this->view->fetch('test');
$this->assertSame('some some someend', $result);
}
public function testPrepend()
{
$this->view->assign('a', 'some');
$this->view->prepend('b', 'some');
$this->view->assign('c', 'some');
$this->view->prepend('c', 'start');
$result = $this->view->fetch('test');
$this->assertSame('some some startsome', $result);
}
public function testErrorTemplate()
{
$view = new PHPView(array('path' => 'error_path/'));
$this->setExpectedException('GeneralException', 'Template');
$result = $view->fetch('test');
}
}

View File

@ -0,0 +1,62 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for PHPView class
*/
require_once dirname(__FILE__) . '/../../../Registry.php';
require_once dirname(__FILE__) . '/../../../view/helpers/ViewHelper.php';
require_once dirname(__FILE__) . '/../../../view/helpers/BreadcrumbViewHelper.php';
class BreadcrumbViewHelperTest extends PHPUnit_Framework_TestCase
{
/**
* @var BreadcrumbViewHelper
*/
public $helper;
public function setUp()
{
Registry::set('BreadcrumbViewHelper', array());
$this->helper = new BreadcrumbViewHelper(new PHPView('any'));
}
public function testTitle()
{
$this->helper->breadcrumb('Guest page', 'guest.php');
$result = Registry::get('BreadcrumbViewHelper');
$this->assertSame(array('Guest page' => 'guest.php'), Registry::get('BreadcrumbViewHelper'));
$this->helper->prepend('Leave message', 'feedback.php');
$this->assertSame(array('Leave message' => 'feedback.php', 'Guest page' => 'guest.php'), Registry::get('BreadcrumbViewHelper'));
$this->helper->append('Home page', 'home.php');
$this->assertSame(array('Leave message' => 'feedback.php', 'Guest page' => 'guest.php', 'Home page' => 'home.php'), Registry::get('BreadcrumbViewHelper'));
}
public function testToString()
{
$this->helper->prepend('Home page', 'home.php');
$this->helper->breadcrumb('Guest page', 'guest.php');
$this->helper->append('Leave message', 'feedback.php');
$this->assertSame(array('Home page' => 'home.php', 'Guest page' => 'guest.php', 'Leave message' => 'feedback.php'), Registry::get('BreadcrumbViewHelper'));
$result = $this->helper->__toString();
$this->assertSame('<a href="home.php">Home page</a> &gt; <a href="guest.php">Guest page</a> &gt; <a href="feedback.php">Leave message</a>', $result);
$this->helper->setSeparator('-');
$result = $this->helper->__toString();
$this->assertSame('<a href="home.php">Home page</a>-<a href="guest.php">Guest page</a>-<a href="feedback.php">Leave message</a>', $result);
$this->helper->append('Last page', '');
$result = $this->helper->__toString();
$this->assertSame('<a href="home.php">Home page</a>-<a href="guest.php">Guest page</a>-<a href="feedback.php">Leave message</a>-Last page', $result);
}
}

View File

@ -0,0 +1,83 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for PHPView class
*/
require_once dirname(__FILE__) . '/../../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../../view/iView.php';
require_once dirname(__FILE__) . '/../../../view/PHPView.php';
require_once dirname(__FILE__) . '/../../../view/helpers/ViewHelper.php';
require_once dirname(__FILE__) . '/../../../view/helpers/GetViewHelper.php';
class GetViewHelperTest extends PHPUnit_Framework_TestCase
{
/**
* @var GetViewHelper
*/
public $helper;
public function setUp()
{
$this->helper = new GetViewHelper(new PHPView('any'));
}
/**
* @TODO: GetViewHelper: initialize GetViewHelper::$get with empty array()
*/
public function testGetWithNull()
{
$this->setExpectedException('PHPUnit_Framework_Error');
$this->helper->get(null);
}
/**
* @TODO: GetViewHelper: check $_GET not null
*/
public function testGetEmptyGET()
{
$this->setExpectedException('PHPUnit_Framework_Error');
$result = $this->helper->get('param');
}
public function testGetWithSingleParam()
{
$_GET['a'] = 'b';
$result = $this->helper->get(null);
$this->assertSame('?a=b', $result);
$this->helper = new GetViewHelper(new PHPView('any'));
$_GET['a'] = 'b';
$_GET['b'] = 'a';
$result = $this->helper->get(array('a' => 'c'));
$this->assertSame('?a=c&amp;b=a', $result);
$_GET['a'] = 'b';
$_GET['b'] = 'a';
$result = $this->helper->get(array('a'));
$this->assertSame('?b=a', $result);
}
public function testGetWithArray()
{
$_GET['a'] = array('one' => 1, 'two' => 2);
$_GET['b'] = 'a';
$_GET['c'] = array('three' => 'four');
$result = $this->helper->get(array('b' => 'c', 'c' => array('five' => 'six')));
$this->assertSame('?a[one]=1&amp;a[two]=2&amp;b=c&amp;c[five]=six', $result);
}
public function testGetUrlencode()
{
$_GET['a'] = array('one' => 1, 'two' => 2);
$_GET['b'] = 'a';
$_GET['c'] = array('three' => 'four');
$result = $this->helper->get(array('b' => 'c d e', 'c' => array('five' => 'six seven')));
$this->assertSame('?a[one]=1&amp;a[two]=2&amp;b=c+d+e&amp;c[five]=six+seven', $result);
}
}

View File

@ -0,0 +1,50 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for PHPView class
*/
require_once dirname(__FILE__) . '/../../../Registry.php';
require_once dirname(__FILE__) . '/../../../view/helpers/ViewHelper.php';
require_once dirname(__FILE__) . '/../../../view/helpers/HeadViewHelper.php';
class HeadViewHelperTest extends PHPUnit_Framework_TestCase
{
/**
* @var HeadViewHelper
*/
public $helper;
public function setUp()
{
Registry::set('HeadViewHelper', array());
$this->helper = new HeadViewHelper(null);
}
public function testHead()
{
$this->helper->head('<meta />');
$result = Registry::get('HeadViewHelper');
$this->assertSame(array('<meta />'), Registry::get('HeadViewHelper'));
$this->helper->head('<link />');
$this->assertSame(array('<meta />', '<link />'), Registry::get('HeadViewHelper'));
}
public function testToString()
{
$this->helper->head('<meta />');
$this->helper->head('<link />');
$result = $this->helper->__toString();
$this->assertSame("<meta />\n <link />\n", $result);
}
}

View File

@ -0,0 +1,101 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for PHPView class
*/
require_once dirname(__FILE__) . '/../../../session/Session.php';
require_once dirname(__FILE__) . '/../../../view/iView.php';
require_once dirname(__FILE__) . '/../../../view/PHPView.php';
require_once dirname(__FILE__) . '/../../../view/helpers/ViewHelper.php';
require_once dirname(__FILE__) . '/../../../view/helpers/MsgViewHelper.php';
require_once dirname(__FILE__) . '/../../../exception/GeneralException.php';
class MsgViewHelperTest extends PHPUnit_Framework_TestCase
{
/**
* @var MsgViewHelper
*/
public $helper;
public function setUp()
{
Session::del('MsgViewHelper');
$this->helper = new MsgViewHelper(new PHPView(array('path' => 'any')));
}
public function testMsg()
{
$this->helper->msg('new message from test', 'success');
$this->assertSame(array('message' => 'new message from test', 'type' => 'success'), Session::get('MsgViewHelper'));
$this->assertSame($this->helper, $this->helper->msg('error message', 'error'));
$this->assertSame(array('message' => 'error message', 'type' => 'error'), Session::get('MsgViewHelper'));
}
public function testWrongType()
{
$this->setExpectedException('GeneralException', 'Unknown message type');
$this->helper->msg('some message', 'wrong');
}
public function testSuccess()
{
$this->helper->success('success message');
$this->assertSame(array('message' => 'success message', 'type' => 'success'), Session::get('MsgViewHelper'));
}
public function testError()
{
$this->helper->error('error message');
$this->assertSame(array('message' => 'error message', 'type' => 'error'), Session::get('MsgViewHelper'));
$this->assertNull(Session::get('test'));
}
public function testInfo()
{
$this->helper->info('info message');
$this->assertSame(array('message' => 'info message', 'type' => 'info'), Session::get('MsgViewHelper'));
$this->assertNull(Session::get('test'));
}
public function testWarning()
{
$this->helper->warning('warning message');
$this->assertSame(array('message' => 'warning message', 'type' => 'warning'), Session::get('MsgViewHelper'));
$this->assertNull(Session::get('test'));
}
public function testToString()
{
$this->helper->success('yeah');
$result = $this->helper->__toString();
$this->assertSame('<div class="success">yeah</div>', $result);
}
public function testToStringEmpty()
{
$result = $this->helper->__toString();
$this->assertEmpty($result);
}
public function testToStringWithPrefix()
{
$this->helper->success('yeah');
$result = $this->helper->withPrefix('prefix')->__toString();
$this->assertSame('<div class="prefixsuccess">yeah</div>', $result);
}
public function testToStringEmptyWithPrefix()
{
$result = $this->helper->withPrefix('prefix')->__toString();
$this->assertEmpty($result);
}
}

View File

@ -0,0 +1,49 @@
<?php
/*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-10-11
*
* Unit tests for PHPView class
*/
require_once dirname(__FILE__) . '/../../../Registry.php';
require_once dirname(__FILE__) . '/../../../view/helpers/ViewHelper.php';
require_once dirname(__FILE__) . '/../../../view/helpers/TitleViewHelper.php';
class TitleViewHelperTest extends PHPUnit_Framework_TestCase
{
/**
* @var TitleViewHelper
*/
public $helper;
public function setUp()
{
Registry::set('TitleViewHelper', array());
$this->helper = new TitleViewHelper('view');
}
public function testTitle()
{
$this->helper->title('one');
$result = Registry::get('TitleViewHelper');
$this->assertSame(array('one'), Registry::get('TitleViewHelper'));
$this->helper->title('two');
$this->assertSame(array('one', 'two'), Registry::get('TitleViewHelper'));
}
public function testSeparator()
{
$this->helper->title('one');
$this->helper->title('two');
$this->assertSame('one - two', $this->helper->__toString());
$this->helper->setSeparator('=');
$this->assertSame('one=two', $this->helper->__toString());
}
}