Browse Source

Merge branch 'init_to_bootstrap' into mongo

master
Anton Grebnev 12 years ago
parent
commit
efb6c2d34c
  1. 11
      Load.php
  2. 70
      app/CliController.php
  3. 23
      app/FrontController.php
  4. 18
      app/iCli.php
  5. 5
      app/router/Route.php
  6. 70
      app/router/Router.php
  7. 16
      exception/ErrorHandler.php
  8. 17
      layout/Error.layout.php
  9. 2
      logger/Logger.php
  10. 12
      model/MongoDbCommand.php
  11. 2
      model/MongoStatement.php
  12. 2
      model/MySQLiStatement.php
  13. 2
      redis/RedisManager.php
  14. 6
      tests/LoadTest.php
  15. 17
      tests/app/ActionTest.php
  16. 2
      tests/app/Action_TestCase.php
  17. 15
      tests/app/AjaxActionTest.php
  18. 101
      tests/app/CliControllerTest.php
  19. 10
      tests/app/ErrorActionTest.php
  20. 13
      tests/app/FrontControllerTest.php
  21. 25
      tests/app/PagerActionTest.php
  22. 10
      tests/app/StaticActionTest.php
  23. 13
      tests/app/router/RouteTest.php
  24. 58
      tests/app/router/RouterTest.php
  25. 10
      tests/classes/EnvTest.php
  26. 13
      tests/exception/ErrorHandlerTest.php
  27. 82
      tests/layout/ErrorLayoutTest.php
  28. 26
      tests/layout/LayoutTest.php
  29. 6
      tests/logger/CliLoggerTest.php
  30. 13
      tests/logger/FileLoggerTest.php
  31. 22
      tests/model/MongoDbCommandTest.php
  32. 64
      tests/model/MongoDriverTest.php
  33. 40
      tests/model/MongoModelTest.php
  34. 95
      tests/model/MongoStatementTest.php
  35. 32
      tests/model/MySQLiDriverTest.php
  36. 50
      tests/model/MySQLiStatementTest.php
  37. 14
      tests/redis/RedisDebugTest.php
  38. 7
      tests/redis/RedisManagerTest.php
  39. 30
      tests/util/AutoloadBuilderTest.php
  40. 223
      tests/util/profiler/ProfilerTest.php
  41. 9
      tests/view/helpers/GetViewHelperTest.php
  42. 21
      util/AutoloadBuilder.php
  43. 27
      util/profiler/Profiler.php
  44. 4
      view/helpers/GetViewHelper.php

11
Load.php

@ -16,7 +16,7 @@ class Load
static protected $autoload; static protected $autoload;
static protected $exclude = array('/.git', '/lib/core/tests', '/lib/core/.git');
static protected $exclude = array();
/** /**
* Add exclude path for autoload. Should be called before setAutoloadFrom * Add exclude path for autoload. Should be called before setAutoloadFrom
@ -39,6 +39,9 @@ class Load
self::buildAutoload(); self::buildAutoload();
} }
self::$autoload = require(self::$file); self::$autoload = require(self::$file);
spl_autoload_register(array(
__CLASS__,
'autoload'));
} }
static public function autoload($class) static public function autoload($class)
@ -47,7 +50,7 @@ class Load
require(PATH . self::$autoload[$class]); require(PATH . self::$autoload[$class]);
return; return;
} }
if (defined('DEBUG') && DEBUG == true) {
if (Config::get('DEBUG')) {
if (!isset(self::$autoload[$class])) { if (!isset(self::$autoload[$class])) {
self::buildAutoload(); self::buildAutoload();
} }
@ -71,9 +74,11 @@ class Load
} }
$scan = array(PATH . '/' . APP . '/src', PATH . '/lib'); $scan = array(PATH . '/' . APP . '/src', PATH . '/lib');
$exclude = array_merge(self::$exclude, array(PATH . '/.git', PATH . '/lib/core/tests', PATH . '/lib/core/.git'));
require_once(PATH . '/lib/core/util/AutoloadBuilder.php'); require_once(PATH . '/lib/core/util/AutoloadBuilder.php');
$builder = new AutoloadBuilder(self::$file, $scan, self::$exclude);
$builder = new AutoloadBuilder(self::$file, $scan, $exclude);
$builder->build(); $builder->build();
ignore_user_abort(false); ignore_user_abort(false);
} }

70
app/CliController.php

@ -0,0 +1,70 @@
<?php
/**
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage App
* @since 27.06.12
*
*/
/**
* @desc CliController (run cli_class, end profiler)
* @author Aleksandr Demidov
*/
class CliController
{
/**
* @var CliController
*/
protected static $instance;
protected $error_stream;
protected function __construct()
{
ErrorHandler::init();
$this->error_stream = Config::get('ErrorStream', 'php://stderr');
}
/**
* @static
* @return CliController
*/
public static function getInstance()
{
if (!isset(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* @param iCli $cli_class
* @throws ErrorException
*/
public function execute($cli_class)
{
try {
if (!in_array('iCli', class_implements($cli_class))) {
throw new ErrorException('Runner "' . get_class($cli_class) . '" need implement of "iCli" interface.');
}
$cli_class->run();
if (Config::get('PROFILER')) {
$profile = Profiler::getInstance()->getCli();
if (Config::get('LOGGING')) {
Logger::getInstance()->log($profile);
} else {
echo $profile;
}
}
} catch (Exception $e) {
$code = $e->getCode();
if ($e instanceof ErrorException) {
$code = $e->getSeverity();
}
file_put_contents($this->error_stream, PHP_EOL . 'Error ' . '#' . $code . ': ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
file_put_contents($this->error_stream, PHP_EOL . 'Stack trace: ' . PHP_EOL . $e->getTraceAsString() . PHP_EOL, FILE_APPEND);
}
}
}

23
app/FrontController.php

@ -32,17 +32,16 @@ class FrontController
private function __construct() private function __construct()
{ {
ErrorHandler::init(); ErrorHandler::init();
if (DEBUG == true) {
Profiler::getInstance()->start();
}
$this->router = new Router(); $this->router = new Router();
} }
/** /**
* Refuse cloning * Refuse cloning
*/ */
private function __clone(){}
private function __clone()
{
}
/** /**
* @return FrontController * @return FrontController
*/ */
@ -118,7 +117,7 @@ class FrontController
$layout = new $layout_class(); $layout = new $layout_class();
$html = $layout->fetch($action); $html = $layout->fetch($action);
if (DEBUG) {
if (Config::get('PROFILER')) {
if (is_subclass_of($action, 'AjaxAction')) { if (is_subclass_of($action, 'AjaxAction')) {
Profiler::getInstance()->getJson(); Profiler::getInstance()->getJson();
} else { } else {
@ -126,14 +125,20 @@ class FrontController
} }
} }
return $html; return $html;
} catch(Exception $e) {
if (DEBUG == true) {
} catch (Exception $e) {
if (Config::get('DEBUG')) {
if (!headers_sent()) { if (!headers_sent()) {
header('HTTP/1.0 500 Internal Server Error'); header('HTTP/1.0 500 Internal Server Error');
} }
return ErrorHandler::showDebug($e); return ErrorHandler::showDebug($e);
} }
$layout = new ErrorLayout();
$layout_class = $this->getRouter()->getErrorLayout();
/**
* @var ErrorLayout $layout
*/
$layout = new $layout_class();
$layout->setException($e);
return $layout->fetch(new ErrorAction($e)); return $layout->fetch(new ErrorAction($e));
} }
} }

18
app/iCli.php

@ -0,0 +1,18 @@
<?php
/**
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage App
* @since 10.07.12
*
*/
/**
* @desc Starter cli point need implement iCli
* @author Aleksandr Demidov
*/
interface iCli
{
public function run();
}

5
app/router/Route.php

@ -54,6 +54,11 @@ class Route
return true; return true;
} }
public function getUri()
{
return '/' . $this->route;
}
public function getAction() public function getAction()
{ {

70
app/router/Router.php

@ -13,16 +13,18 @@ class Router
{ {
protected $routes = array(); protected $routes = array();
protected $route_name; protected $route_name;
protected $default_layout = 'Default'; protected $default_layout = 'Default';
protected $error_layout = 'Error';
/** /**
* @var Route * @var Route
*/ */
protected $route; protected $route;
public function add($name, $route, $action, $params = array(), $layout = null) public function add($name, $route, $action, $params = array(), $layout = null)
{ {
if (!$layout) { if (!$layout) {
@ -30,11 +32,11 @@ class Router
} }
$this->routes[$name] = new Route($route, $action, $params, $layout); $this->routes[$name] = new Route($route, $action, $params, $layout);
} }
public function route($request) public function route($request)
{ {
$req = explode('/', trim($request, '/')); $req = explode('/', trim($request, '/'));
foreach ($this->routes as $name => $route) { foreach ($this->routes as $name => $route) {
if ($route->match($req)) { if ($route->match($req)) {
$this->route_name = $name; $this->route_name = $name;
@ -45,22 +47,68 @@ class Router
} }
return false; return false;
} }
public function setDefaultLayout($layout = 'Default') public function setDefaultLayout($layout = 'Default')
{ {
$this->default_layout = $layout; $this->default_layout = $layout;
} }
/**
* Sets the name of error page layout
* @param string $layout
*/
public function setErrorLayout($layout = 'Error')
{
$this->error_layout = $layout;
}
/**
* Returns error layout name
* @return string Error layout name
*/
public function getErrorLayout()
{
return $this->error_layout . 'Layout';
}
public function getRouteName() public function getRouteName()
{ {
return $this->route_name; return $this->route_name;
} }
/**
* @param null|string $name
* @return Route
* @throws ErrorException
*/
public function getRoute($name = null)
{
if (is_null($name)) {
return $this->route;
} else {
if ($this->routeIsExists($name)) {
return $this->getRouteByName($name);
} else {
throw new ErrorException('Unknown route name: "' . $name . '".');
}
}
}
/**
* @param string $name
* @return bool
*/
public function routeIsExists($name)
{
return array_key_exists($name, $this->routes);
}
/** /**
* @param string $name
* @return Route * @return Route
*/ */
public function getRoute()
protected function getRouteByName($name)
{ {
return $this->route;
return $this->routes[$name];
} }
} }

16
exception/ErrorHandler.php

@ -19,9 +19,14 @@ class ErrorHandler
static public function error_handler($errno, $errstr, $errfile, $errline) static public function error_handler($errno, $errstr, $errfile, $errline)
{ {
ob_clean();
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
return false;
$ob_handlers = ob_get_status();
if (!empty($ob_handlers)) {
ob_end_clean();
}
if (error_reporting() !== 0) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
return true;
} }
static protected function getSource($file, $hiline) static protected function getSource($file, $hiline)
@ -71,7 +76,10 @@ class ErrorHandler
*/ */
static public function showDebug($exception) static public function showDebug($exception)
{ {
ob_clean();
$ob_handlers = ob_get_status();
if (!empty($ob_handlers)) {
ob_end_clean();
}
$class = get_class($exception); $class = get_class($exception);
$method = Env::Server('REQUEST_METHOD', ''); $method = Env::Server('REQUEST_METHOD', '');

17
layout/Error.layout.php

@ -11,5 +11,20 @@
class ErrorLayout extends Layout class ErrorLayout extends Layout
{ {
protected function execute(){}
/**
* @var GeneralException
*/
protected $exception;
protected function execute()
{
}
/**
* @param Exception $exception
*/
public function setException(Exception $exception)
{
$this->exception = $exception;
}
} }

2
logger/Logger.php

@ -43,7 +43,7 @@ abstract class Logger
*/ */
public function log($message) public function log($message)
{ {
if (DEBUG) {
if (Config::get('LOGGING')) {
$this->concreteLog($message); $this->concreteLog($message);
} }
} }

12
model/MongoDbCommand.php

@ -105,7 +105,7 @@ class FindMongoCommand extends MongoDbCommand
public function __toString() public function __toString()
{ {
if ($this->checkParams()) { if ($this->checkParams()) {
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
$result .= 'Condition: ' . $this->arrayToString($this->condition); $result .= 'Condition: ' . $this->arrayToString($this->condition);
$result .= 'Type: FIND' . PHP_EOL; $result .= 'Type: FIND' . PHP_EOL;
$result .= 'Fields: ' . $this->arrayToString($this->fields); $result .= 'Fields: ' . $this->arrayToString($this->fields);
@ -145,7 +145,7 @@ class CountMongoCommand extends MongoDbCommand
public function __toString() public function __toString()
{ {
if ($this->checkParams()) { if ($this->checkParams()) {
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
$result .= 'Type: COUNT' . PHP_EOL; $result .= 'Type: COUNT' . PHP_EOL;
$result .= 'Condition: ' . $this->arrayToString($this->condition); $result .= 'Condition: ' . $this->arrayToString($this->condition);
$result .= 'Limit: ' . $this->limit . PHP_EOL; $result .= 'Limit: ' . $this->limit . PHP_EOL;
@ -198,7 +198,7 @@ class InsertMongoCommand extends MongoDbCommand
public function __toString() public function __toString()
{ {
if ($this->checkParams()) { if ($this->checkParams()) {
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
$result .= 'Type: INSERT' . PHP_EOL; $result .= 'Type: INSERT' . PHP_EOL;
$result .= 'Data: ' . $this->arrayToString($this->data); $result .= 'Data: ' . $this->arrayToString($this->data);
$mult = $this->multiple ? 'TRUE' : 'FALSE'; $mult = $this->multiple ? 'TRUE' : 'FALSE';
@ -244,7 +244,7 @@ class UpdateMongoCommand extends MongoDbCommand
public function __toString() public function __toString()
{ {
if ($this->checkParams()) { if ($this->checkParams()) {
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
$result .= 'Type: UPDATE' . PHP_EOL; $result .= 'Type: UPDATE' . PHP_EOL;
$result .= 'Condition: ' . $this->arrayToString($this->condition); $result .= 'Condition: ' . $this->arrayToString($this->condition);
$result .= 'Data: ' . $this->arrayToString($this->data); $result .= 'Data: ' . $this->arrayToString($this->data);
@ -284,7 +284,7 @@ class RemoveMongoCommand extends MongoDbCommand
public function __toString() public function __toString()
{ {
if ($this->checkParams()) { if ($this->checkParams()) {
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
$result .= 'Type: REMOVE' . PHP_EOL; $result .= 'Type: REMOVE' . PHP_EOL;
$result .= 'Condition: ' . $this->arrayToString($this->condition); $result .= 'Condition: ' . $this->arrayToString($this->condition);
$safe = $this->safe ? 'TRUE' : 'FALSE'; $safe = $this->safe ? 'TRUE' : 'FALSE';
@ -322,7 +322,7 @@ class CommandMongoCommand extends MongoDbCommand
public function __toString() public function __toString()
{ {
if ($this->checkParams()) { if ($this->checkParams()) {
$result = PHP_EOL . 'Collection: ' . $this->collection . PHP_EOL;
$result = PHP_EOL . 'Collection: ' . trim($this->collection, "\n") . PHP_EOL;
$result .= 'Type: COMMAND' . PHP_EOL; $result .= 'Type: COMMAND' . PHP_EOL;
$result .= 'Command: ' . $this->arrayToString($this->command); $result .= 'Command: ' . $this->arrayToString($this->command);
return $result; return $result;

2
model/MongoStatement.php

@ -138,7 +138,7 @@ class MongoStatement extends DbStatement
$this->result = false; $this->result = false;
$mongo = $this->driver->getConnection(); $mongo = $this->driver->getConnection();
if ($mongo instanceof Mongo) { if ($mongo instanceof Mongo) {
if (DEBUG) {
if (Config::get('PROFILER_DETAILS')) {
$profiler = Profiler::getInstance()->profilerCommand('Mongo', $request); $profiler = Profiler::getInstance()->profilerCommand('Mongo', $request);
$result = $request->execute(); $result = $request->execute();
$profiler->end(); $profiler->end();

2
model/MySQLiStatement.php

@ -157,7 +157,7 @@ class MySQLiStatement extends DbStatement
* @var MySQLi * @var MySQLi
*/ */
$mysqli = $this->driver->getConnection(); $mysqli = $this->driver->getConnection();
if (DEBUG) {
if (Config::get('PROFILER_DETAILS')) {
$profiler = Profiler::getInstance()->profilerCommand('MySQL', $request); $profiler = Profiler::getInstance()->profilerCommand('MySQL', $request);
$result = $mysqli->query($request); $result = $mysqli->query($request);
$profiler->end(); $profiler->end();

2
redis/RedisManager.php

@ -49,7 +49,7 @@ class RedisManager
* @var Redis * @var Redis
*/ */
$connection = new Redis(); $connection = new Redis();
if (defined('DEBUG') && DEBUG == true) {
if (Config::get('PROFILER_DETAILS')) {
$connection = new RedisDebug($connection); $connection = new RedisDebug($connection);
} }
if (!$connection->connect($host, $port)) { if (!$connection->connect($host, $port)) {

6
tests/LoadTest.php

@ -10,6 +10,8 @@
* Unit tests for Load class * 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 dirname(__FILE__) . '/../Load.php';
require_once 'vfsStream/vfsStream.php'; require_once 'vfsStream/vfsStream.php';
@ -164,9 +166,7 @@ class LoadTest extends PHPUnit_Framework_TestCase
$autoload = require(self::$file); $autoload = require(self::$file);
$this->assertNotEmpty($autoload); $this->assertNotEmpty($autoload);
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('DEBUG', true);
Load::autoload('Some'); Load::autoload('Some');
Load::autoload('DbDriver'); Load::autoload('DbDriver');
} }

17
tests/app/ActionTest.php

@ -20,9 +20,7 @@ class ActionTest extends Action_TestCase
*/ */
public function testActionConstructWithParams() public function testActionConstructWithParams()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('param1' => 'value1', 'param2' => 'value2')); Env::setParams(array('param1' => 'value1', 'param2' => 'value2'));
$action = $this->getMockForAbstractClass('Action' ); $action = $this->getMockForAbstractClass('Action' );
$this->assertSame('value1', $action->param1); $this->assertSame('value1', $action->param1);
@ -33,9 +31,7 @@ class ActionTest extends Action_TestCase
*/ */
public function testFetch() public function testFetch()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$load = new ReflectionClass('Load'); $load = new ReflectionClass('Load');
$classes = $load->getProperty('autoload'); $classes = $load->getProperty('autoload');
$classes->setAccessible(true); $classes->setAccessible(true);
@ -53,9 +49,7 @@ class ActionTest extends Action_TestCase
*/ */
public function testFetchNoTemplate() public function testFetchNoTemplate()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('template' => '')); Env::setParams(array('template' => ''));
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');
@ -70,9 +64,8 @@ class ActionTest extends Action_TestCase
public function testRedirect() public function testRedirect()
{ {
set_exit_overload(function() { return false; }); set_exit_overload(function() { return false; });
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$load = new ReflectionClass('Action'); $load = new ReflectionClass('Action');
$redirect = $load->getMethod('redirect'); $redirect = $load->getMethod('redirect');
$redirect->setAccessible(true); $redirect->setAccessible(true);

2
tests/app/Action_TestCase.php

@ -10,6 +10,8 @@
* Action_TestCase class for testing Actions * 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__) . '/../../Load.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php'; require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php'; require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';

15
tests/app/AjaxActionTest.php

@ -21,9 +21,8 @@ class AjaxActionTest extends Action_TestCase
*/ */
public function testConstruct() public function testConstruct()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('ajax' => 'AjaxTemplate', 'param2' => 'value2')); Env::setParams(array('ajax' => 'AjaxTemplate', 'param2' => 'value2'));
$action = $this->getMockForAbstractClass('AjaxAction' ); $action = $this->getMockForAbstractClass('AjaxAction' );
$this->assertAttributeEquals('ajax', 'template', $action); $this->assertAttributeEquals('ajax', 'template', $action);
@ -34,9 +33,8 @@ class AjaxActionTest extends Action_TestCase
*/ */
public function testFetchWithEncode() public function testFetchWithEncode()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');
$action = $this->getMockForAbstractClass('AjaxAction' ); $action = $this->getMockForAbstractClass('AjaxAction' );
@ -51,9 +49,8 @@ class AjaxActionTest extends Action_TestCase
*/ */
public function testFetchNoEncode() public function testFetchNoEncode()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('encode' => false)); Env::setParams(array('encode' => false));
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');

101
tests/app/CliControllerTest.php

@ -0,0 +1,101 @@
<?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/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';
/**
* @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);
}
/**
* @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.');
}
}

10
tests/app/ErrorActionTest.php

@ -80,9 +80,8 @@ class ErrorActionTest extends Action_TestCase
*/ */
public function testFetchNoTemplate() public function testFetchNoTemplate()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$exception = $this->getMock('ErrorException'); $exception = $this->getMock('ErrorException');
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');
@ -123,9 +122,8 @@ class ErrorActionTest extends Action_TestCase
private function setConstants($val = false) private function setConstants($val = false)
{ {
if (!defined('DEBUG')) {
define('DEBUG', $val);
}
Config::set('DEBUG', $val);
} }
private function header() private function header()

13
tests/app/FrontControllerTest.php

@ -44,7 +44,7 @@ class FrontControllerTest extends PHPUnit_Framework_TestCase
$this->getMock('View'); $this->getMock('View');
} }
if (!class_exists('ErrorLayout')) { if (!class_exists('ErrorLayout')) {
$this->getMock('ErrorLayout', array('fetch'), array(), 'ErrorLayoutMock');
$this->getMock('ErrorLayout', array('fetch', 'setException'), array(), 'ErrorLayoutMock');
} }
if (!class_exists('ErrorActionMock')) { if (!class_exists('ErrorActionMock')) {
$this->getMock('ErrorAction', array(), array(), 'ErrorActionMock', false); $this->getMock('ErrorAction', array(), array(), 'ErrorActionMock', false);
@ -190,7 +190,7 @@ class FrontControllerTest extends PHPUnit_Framework_TestCase
$router = $controller->getRouter(); $router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'user'); $router->add('user', 'user/account/:id', 'user');
$result = $controller->execute(); $result = $controller->execute();
$this->assertEmpty($result);
$this->assertNull($result);
} }
/** /**
* @runInSeparateProcess * @runInSeparateProcess
@ -205,14 +205,13 @@ class FrontControllerTest extends PHPUnit_Framework_TestCase
$router = $controller->getRouter(); $router = $controller->getRouter();
$router->add('user', 'user/account/:id', 'NewAjax'); $router->add('user', 'user/account/:id', 'NewAjax');
$result = $controller->execute(); $result = $controller->execute();
$this->assertEmpty($result);
$this->assertNull($result);
} }
private function setConstants($val = false) private function setConstants($val = false)
{ {
if (!defined('DEBUG')) {
define('DEBUG', $val);
}
Config::set('DEBUG', $val);
} }
public function tearDown() public function tearDown()
@ -227,8 +226,6 @@ class FrontControllerTest extends PHPUnit_Framework_TestCase
return 'PHPViewMock'; return 'PHPViewMock';
case 'DefaultLayout': case 'DefaultLayout':
return 'DefaultLayoutMock'; return 'DefaultLayoutMock';
case 'userAction':
return 'userAction';
case 'ErrorAction': case 'ErrorAction':
return 'ErrorActionMock'; return 'ErrorActionMock';
case 'ErrorLayout': case 'ErrorLayout':

25
tests/app/PagerActionTest.php

@ -21,9 +21,8 @@ class PagerActionTest extends Action_TestCase
*/ */
public function testConstructWithParams() public function testConstructWithParams()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$action = $this->getMockForAbstractClass('PagerAction'); $action = $this->getMockForAbstractClass('PagerAction');
$this->assertSame(20, $action->getLimit()); $this->assertSame(20, $action->getLimit());
$action = $this->getMockForAbstractClass('PagerAction', array(50)); $action = $this->getMockForAbstractClass('PagerAction', array(50));
@ -35,9 +34,8 @@ class PagerActionTest extends Action_TestCase
*/ */
public function testSetCount() public function testSetCount()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$action = $this->getMockForAbstractClass('PagerAction'); $action = $this->getMockForAbstractClass('PagerAction');
$action->setCount(50); $action->setCount(50);
$this->assertSame(1, $action->page); $this->assertSame(1, $action->page);
@ -60,9 +58,8 @@ class PagerActionTest extends Action_TestCase
*/ */
public function testGetOffset() public function testGetOffset()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$action = $this->getMockForAbstractClass('PagerAction'); $action = $this->getMockForAbstractClass('PagerAction');
$this->assertSame(0, $action->getOffset()); $this->assertSame(0, $action->getOffset());
} }
@ -72,9 +69,8 @@ class PagerActionTest extends Action_TestCase
*/ */
public function testFetchNoTemplate() public function testFetchNoTemplate()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('template' => '')); Env::setParams(array('template' => ''));
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');
@ -88,9 +84,8 @@ class PagerActionTest extends Action_TestCase
*/ */
public function testFetchWithTemplate() public function testFetchWithTemplate()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('template' => 'SomeTemplate')); Env::setParams(array('template' => 'SomeTemplate'));
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');

10
tests/app/StaticActionTest.php

@ -21,9 +21,8 @@ class StaticActionTest extends Action_TestCase
*/ */
public function testFetchNoTemplate() public function testFetchNoTemplate()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('template' => '')); Env::setParams(array('template' => ''));
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');
@ -37,9 +36,8 @@ class StaticActionTest extends Action_TestCase
*/ */
public function testFetchWithTemplate() public function testFetchWithTemplate()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('template' => 'SomeTemplate')); Env::setParams(array('template' => 'SomeTemplate'));
$controller = FrontController::getInstance(); $controller = FrontController::getInstance();
$controller->setView('SomeView'); $controller->setView('SomeView');

13
tests/app/router/RouteTest.php

@ -77,4 +77,17 @@ class RouteTest extends PHPUnit_Framework_TestCase
$this->setExpectedException('PHPUnit_Framework_Error'); $this->setExpectedException('PHPUnit_Framework_Error');
$route->match(''); $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());
}
} }

58
tests/app/router/RouterTest.php

@ -61,4 +61,62 @@ class RouterTest extends PHPUnit_Framework_TestCase
$router->setDefaultLayout('userLayout'); $router->setDefaultLayout('userLayout');
$this->assertAttributeEquals('userLayout', 'default_layout', $router); $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());
}
} }

10
tests/classes/EnvTest.php

@ -24,9 +24,8 @@ class EnvTest extends PHPUnit_Framework_TestCase
*/ */
public function testGetRequestUri() public function testGetRequestUri()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$_SERVER['REQUEST_URI'] = '/test/index.php?id=1&test=wet&id_theme=512'; $_SERVER['REQUEST_URI'] = '/test/index.php?id=1&test=wet&id_theme=512';
$this->assertSame('/test/index.php', Env::getRequestUri()); $this->assertSame('/test/index.php', Env::getRequestUri());
$_SERVER['REQUEST_URI'] = '/tes?t/index.php?id=1&test=wet&id_theme=512'; $_SERVER['REQUEST_URI'] = '/tes?t/index.php?id=1&test=wet&id_theme=512';
@ -38,9 +37,8 @@ class EnvTest extends PHPUnit_Framework_TestCase
*/ */
public function testTrimBaseRequestUri() public function testTrimBaseRequestUri()
{ {
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$class = new ReflectionClass('Env'); $class = new ReflectionClass('Env');
$this->started = $class->getProperty('request'); $this->started = $class->getProperty('request');
$this->started->setAccessible(true); $this->started->setAccessible(true);

13
tests/exception/ErrorHandlerTest.php

@ -39,6 +39,19 @@ class ErrorHandlerTest extends PHPUnit_Framework_TestCase
trigger_error("test error", E_USER_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 * @TODO: ErrorHandler->wrapTrace() not used
*/ */

82
tests/layout/ErrorLayoutTest.php

@ -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();
}
}

26
tests/layout/LayoutTest.php

@ -10,6 +10,8 @@
* Unit tests for Layout class * 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__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php'; require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../layout/Layout.php'; require_once dirname(__FILE__) . '/../../layout/Layout.php';
@ -40,18 +42,16 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function testConstruct() public function testConstruct()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout'); $layout = $this->getMockForAbstractClass('Layout');
$this->assertAttributeInstanceOf('PHPView', 'view', $layout); $this->assertAttributeInstanceOf('PHPView', 'view', $layout);
} }
public function testFetch() public function testFetch()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout'); $layout = $this->getMockForAbstractClass('Layout');
$action = $this->getMock('Action', array('fetch')); $action = $this->getMock('Action', array('fetch'));
@ -64,9 +64,8 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function testFetchWithTemplate() public function testFetchWithTemplate()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout'); $layout = $this->getMockForAbstractClass('Layout');
$class = new ReflectionClass('Layout'); $class = new ReflectionClass('Layout');
@ -89,9 +88,8 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function testAppend() public function testAppend()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout', array('append', 'prepend'), 'LayoutMock'); $layout = $this->getMockForAbstractClass('Layout', array('append', 'prepend'), 'LayoutMock');
$action = $this->getMock('Action', array('fetch')); $action = $this->getMock('Action', array('fetch'));
@ -128,8 +126,8 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function tearDown() public function tearDown()
{ {
// if (defined('DEBUG')) {
// $debug = DEBUG ? 'TRUE' : 'FALSE';
// if (!is_null(Config::get('DEBUG'))) {
// $debug = Config::get('DEBUG') ? 'TRUE' : 'FALSE';
// echo PHP_EOL . __CLASS__ . ' DEBUG = ' . $debug . PHP_EOL; // echo PHP_EOL . __CLASS__ . ' DEBUG = ' . $debug . PHP_EOL;
// } else { // } else {
// echo PHP_EOL . __CLASS__ . ' ' . 'DEBUG NOT DEFINED' . PHP_EOL; // echo PHP_EOL . __CLASS__ . ' ' . 'DEBUG NOT DEFINED' . PHP_EOL;

6
tests/logger/CliLoggerTest.php

@ -43,9 +43,9 @@ class CliLoggerTest extends PHPUnit_Framework_TestCase
*/ */
public function testLog() public function testLog()
{ {
if(!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('LOGGING', true);
Config::set('Logger', array('logger' => 'CliLogger'));
$logger = Logger::getInstance(); $logger = Logger::getInstance();
ob_start(); ob_start();
$logger->setPid(123); $logger->setPid(123);

13
tests/logger/FileLoggerTest.php

@ -33,6 +33,7 @@ class FileLoggerTest extends PHPUnit_Framework_TestCase
vfsStream::setup(); vfsStream::setup();
$root = vfsStream::create(array()); $root = vfsStream::create(array());
vfsStreamWrapper::setRoot($root); vfsStreamWrapper::setRoot($root);
Config::set('LOGGING', true);
$this->conf = array('logger' => 'FileLogger', 'filepath' => vfsStream::url('root/log.txt')); $this->conf = array('logger' => 'FileLogger', 'filepath' => vfsStream::url('root/log.txt'));
Config::set('Logger', $this->conf); Config::set('Logger', $this->conf);
if ($root->hasChild('log.txt')) { if ($root->hasChild('log.txt')) {
@ -54,9 +55,7 @@ class FileLoggerTest extends PHPUnit_Framework_TestCase
*/ */
public function testCannotWrite() public function testCannotWrite()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('DEBUG', true);
$conf = array('logger' => 'FileLogger', 'filepath' => '/log.txt'); $conf = array('logger' => 'FileLogger', 'filepath' => '/log.txt');
Config::set('Logger', $conf); Config::set('Logger', $conf);
@ -71,9 +70,7 @@ class FileLoggerTest extends PHPUnit_Framework_TestCase
*/ */
public function testLog() public function testLog()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('DEBUG', true);
$this->assertFileNotExists($this->conf['filepath']); $this->assertFileNotExists($this->conf['filepath']);
$logger = Logger::getInstance(); $logger = Logger::getInstance();
$logger->setPid(123); $logger->setPid(123);
@ -86,9 +83,7 @@ class FileLoggerTest extends PHPUnit_Framework_TestCase
*/ */
public function testDestruct() public function testDestruct()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('DEBUG', true);
$my_pid = posix_getpid(); $my_pid = posix_getpid();
$fd_command = 'lsof -n -p ' . $my_pid . ' | wc -l'; $fd_command = 'lsof -n -p ' . $my_pid . ' | wc -l';
$fd_count_start = (int) `$fd_command`; $fd_count_start = (int) `$fd_command`;

22
tests/model/MongoDbCommandTest.php

@ -1,14 +1,14 @@
<?php <?php
/* /*
* @copyright NetMonsters <team@netmonsters.ru>
* @link http://netmonsters.ru
* @package Majestic
* @subpackage UnitTests
* @since 2011-11-10
*
* Unit tests for MongoDriver class
*/
* @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/DbDriver.php';
require_once dirname(__FILE__) . '/../../model/NoSqlDbDriver.php'; require_once dirname(__FILE__) . '/../../model/NoSqlDbDriver.php';
@ -110,7 +110,6 @@ class MongoDbCommandTest extends PHPUnit_Framework_TestCase
$this->assertEquals(0, $count_result); $this->assertEquals(0, $count_result);
$this->assertEquals($count_result, $find_result->count()); $this->assertEquals($count_result, $find_result->count());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection); $cmd = MongoCommandBuilder::factory(MongoCommandBuilder::INSERT, $this->collection);
$cmd $cmd
->bindParam('data', array('name' => 'insert')) ->bindParam('data', array('name' => 'insert'))
@ -126,7 +125,6 @@ class MongoDbCommandTest extends PHPUnit_Framework_TestCase
$this->assertEquals(2, $count_cmd->execute()); $this->assertEquals(2, $count_cmd->execute());
$find_cmd->bindParam('condition', array('name' => 'insert')); $find_cmd->bindParam('condition', array('name' => 'insert'));
$this->assertEquals($find_cmd->execute()->count(), $count_cmd->execute()); $this->assertEquals($find_cmd->execute()->count(), $count_cmd->execute());
} }
/** /**
@ -186,8 +184,6 @@ class MongoDbCommandTest extends PHPUnit_Framework_TestCase
$cmd->bindParam('condition', array('name' => 'equal object'))->bindParam('fields', array()); $cmd->bindParam('condition', array('name' => 'equal object'))->bindParam('fields', array());
$result = $cmd->execute(); $result = $cmd->execute();
$this->assertEquals(2, $result->count()); $this->assertEquals(2, $result->count());
} }
/** /**
@ -385,6 +381,6 @@ class CollectionMock
public function __toString() public function __toString()
{ {
return 'CollectionMock';
return PHP_EOL . 'CollectionMock';
} }
} }

64
tests/model/MongoDriverTest.php

@ -114,9 +114,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testFind() public function testFind()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows()); $this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
@ -145,9 +143,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testOrderSkipLimit() public function testOrderSkipLimit()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
@ -184,9 +180,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testCount() public function testCount()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$this->assertEquals(5, $mongo->count('items')); $this->assertEquals(5, $mongo->count('items'));
$this->assertEquals(2, $mongo->count('items', array('name' => 'eggs'))); $this->assertEquals(2, $mongo->count('items', array('name' => 'eggs')));
@ -199,9 +193,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testCursorCount() public function testCursorCount()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$this->assertEquals(5, $mongo->find('items')->count(5)); $this->assertEquals(5, $mongo->find('items')->count(5));
$this->assertCount(3, $mongo->find('items')->limit(3)->fetchAll()); $this->assertCount(3, $mongo->find('items')->limit(3)->fetchAll());
@ -214,9 +206,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testGet() public function testGet()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$eggs = $mongo->get('items', array('name' => 'eggs'))->fetchObject(); $eggs = $mongo->get('items', array('name' => 'eggs'))->fetchObject();
@ -232,9 +222,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testRemove() public function testRemove()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows()); $this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
@ -250,9 +238,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testInsert() public function testInsert()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows()); $this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
@ -269,9 +255,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testBatchInsert() public function testBatchInsert()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$data = array( $data = array(
array('name' => 'first object'), array('name' => 'first object'),
@ -292,9 +276,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testGetInsertId() public function testGetInsertId()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$this->assertEquals(0, $mongo->getInsertId()); $this->assertEquals(0, $mongo->getInsertId());
@ -316,9 +298,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testUpdate() public function testUpdate()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows()); $this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
@ -336,9 +316,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testUpsert() public function testUpsert()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
@ -353,9 +331,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testFindAndModify() public function testFindAndModify()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
@ -371,9 +347,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testFindAndModifyNoItem() public function testFindAndModifyNoItem()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
@ -389,9 +363,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testEvalCommand() public function testEvalCommand()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('$eval' => 'function() { return db.items.count();}')); $result = $mongo->command('items', array('$eval' => 'function() { return db.items.count();}'));
$this->assertEquals(5, $result->fetch()); $this->assertEquals(5, $result->fetch());
@ -406,9 +378,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testEval() public function testEval()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('$eval' => 'function() {return true; }')); $result = $mongo->command('items', array('$eval' => 'function() {return true; }'));
$this->assertTrue($result->fetch()); $this->assertTrue($result->fetch());
@ -424,9 +394,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/ */
public function testCommand() public function testCommand()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf); $mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('distinct' => 'items', 'key' => 'name')); $result = $mongo->command('items', array('distinct' => 'items', 'key' => 'name'));
$this->assertEquals(4, count($result->fetch(DB::FETCH_ASSOC))); $this->assertEquals(4, count($result->fetch(DB::FETCH_ASSOC)));

40
tests/model/MongoModelTest.php

@ -64,9 +64,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testFind() public function testFind()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$result = $this->model->find(); $result = $this->model->find();
$this->assertInstanceOf('MongoStatement', $result); $this->assertInstanceOf('MongoStatement', $result);
$this->assertEquals('milk', $result->limit(2)->order(array('name' => -1))->fetch()->name); $this->assertEquals('milk', $result->limit(2)->order(array('name' => -1))->fetch()->name);
@ -83,9 +81,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testGet() public function testGet()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$result = $this->model->find()->limit(1)->order(array('name' => 1)); $result = $this->model->find()->limit(1)->order(array('name' => 1));
$result = $result->fetch(); $result = $result->fetch();
$this->assertEquals('bread', $result->name); $this->assertEquals('bread', $result->name);
@ -99,9 +95,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testDelete() public function testDelete()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$result = $this->model->find()->limit(1)->order(array('name' => 1)); $result = $this->model->find()->limit(1)->order(array('name' => 1));
$id = $result->fetch()->_id; $id = $result->fetch()->_id;
$this->assertEquals(1, $this->model->delete($id)); $this->assertEquals(1, $this->model->delete($id));
@ -114,9 +108,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testBatchInsert() public function testBatchInsert()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$data = array( $data = array(
array('name' => 'first object'), array('name' => 'first object'),
array('name' => 'second object'), array('name' => 'second object'),
@ -135,9 +127,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testDeleteAll() public function testDeleteAll()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$this->assertEquals(2, $this->model->count(array('name' => 'eggs'))); $this->assertEquals(2, $this->model->count(array('name' => 'eggs')));
$this->assertEquals(0, $this->model->deleteAll(array('name' => 'eggs'))); $this->assertEquals(0, $this->model->deleteAll(array('name' => 'eggs')));
@ -150,9 +140,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testCount() public function testCount()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$this->assertEquals(5, $this->model->count()); $this->assertEquals(5, $this->model->count());
$this->assertEquals(2, $this->model->count(array('name' => 'eggs'))); $this->assertEquals(2, $this->model->count(array('name' => 'eggs')));
} }
@ -163,9 +151,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetch() public function testFetch()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mock = $this->getMock('CacheKey', array('set', 'get')); $mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->exactly(3)) $mock->expects($this->exactly(3))
@ -204,9 +190,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testUseMongoId() public function testUseMongoId()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$this->assertAttributeEquals(true, 'useMongoId', $this->model); $this->assertAttributeEquals(true, 'useMongoId', $this->model);
} }
@ -217,9 +201,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testId() public function testId()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$class = new ReflectionClass('MongoModel'); $class = new ReflectionClass('MongoModel');
$prop = $class->getProperty('useMongoId'); $prop = $class->getProperty('useMongoId');
$prop->setAccessible(true); $prop->setAccessible(true);
@ -239,9 +221,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/ */
public function testIdToMongoId() public function testIdToMongoId()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$this->model->insert(array('name' => 'testbread', 'price' => 3.2, 'quantity' => 10)); $this->model->insert(array('name' => 'testbread', 'price' => 3.2, 'quantity' => 10));
$this->model->insert(array('name' => 'testbread', 'price' => 12, 'quantity' => 2)); $this->model->insert(array('name' => 'testbread', 'price' => 12, 'quantity' => 2));

95
tests/model/MongoStatementTest.php

@ -10,6 +10,8 @@
* Unit tests for MySQLiStatement class * 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/CommandProfiler.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php'; require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
require_once dirname(__FILE__) . '/../../model/Db.php'; require_once dirname(__FILE__) . '/../../model/Db.php';
@ -49,7 +51,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
->getMock(); ->getMock();
$this->request = $this->getMockBuilder('MongoDbCommandMock') $this->request = $this->getMockBuilder('MongoDbCommandMock')
->disableOriginalConstructor() ->disableOriginalConstructor()
->setMethods(array('execute', 'bindParam', 'getInsertId'))
->setMethods(array('execute', 'bindParam', 'getInsertId', '__toString'))
->getMock(); ->getMock();
$this->stmt = new MongoStatement($this->driver, $this->request); $this->stmt = new MongoStatement($this->driver, $this->request);
} }
@ -61,9 +63,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testAffectedNumRowsNoResult() public function testAffectedNumRowsNoResult()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->assertFalse($this->stmt->affectedRows()); $this->assertFalse($this->stmt->affectedRows());
$this->assertFalse($this->stmt->numRows()); $this->assertFalse($this->stmt->numRows());
@ -82,9 +82,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testAffectedNumRows() public function testAffectedNumRows()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->request $this->request
->expects($this->once()) ->expects($this->once())
@ -100,9 +98,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testGetInsertId() public function testGetInsertId()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->request = $this->getMockBuilder('InsertMongoCommand') $this->request = $this->getMockBuilder('InsertMongoCommand')
@ -131,9 +127,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testExecute() public function testExecute()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod()->setRequestExecuteMethod(); $this->setDriverGetConnectionMethod()->setRequestExecuteMethod();
$this->assertTrue($this->stmt->execute()); $this->assertTrue($this->stmt->execute());
@ -145,9 +139,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testExecuteNoResult() public function testExecuteNoResult()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->request $this->request
->expects($this->any()) ->expects($this->any())
@ -163,9 +155,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testExecuteNoConnection() public function testExecuteNoConnection()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->driver $this->driver
->expects($this->any()) ->expects($this->any())
->method('getConnection') ->method('getConnection')
@ -180,12 +170,12 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testExecuteWithDebug() public function testExecuteWithDebug()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod()->setRequestExecuteMethod(); $this->setDriverGetConnectionMethod()->setRequestExecuteMethod();
$this->assertTrue($this->stmt->execute()); $this->assertTrue($this->stmt->execute());
$this->assertEquals(10, $this->stmt->numRows()); $this->assertEquals(10, $this->stmt->numRows());
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
} }
/** /**
@ -194,9 +184,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testBindParam() public function testBindParam()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->request $this->request
->expects($this->once()) ->expects($this->once())
@ -217,9 +206,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetch() public function testFetch()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->assertFalse($this->stmt->fetch()); $this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod()->setRequestForFetch(); $this->setDriverGetConnectionMethod()->setRequestForFetch();
@ -228,6 +216,7 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
$result = $this->stmt->fetch(); $result = $this->stmt->fetch();
$this->assertEquals('prev', $result->next); $this->assertEquals('prev', $result->next);
$this->assertFalse($this->stmt->fetch()); $this->assertFalse($this->stmt->fetch());
$this->assertContains('Queries not counted.', Profiler::getInstance()->getCli());
} }
/** /**
@ -236,9 +225,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchWithInitialArray() public function testFetchWithInitialArray()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch()); $this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
@ -257,9 +245,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchAssocFromCursor() public function testFetchAssocFromCursor()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch()); $this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod()->setRequestForFetch(); $this->setDriverGetConnectionMethod()->setRequestForFetch();
@ -276,9 +263,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchAssocFromArray() public function testFetchAssocFromArray()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch()); $this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
@ -298,9 +284,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchWrongMode() public function testFetchWrongMode()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->assertFalse($this->stmt->fetch()); $this->assertFalse($this->stmt->fetch());
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
@ -320,9 +305,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testSkipOrderLimit() public function testSkipOrderLimit()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod()->setRequestForFetch(); $this->setDriverGetConnectionMethod()->setRequestForFetch();
$this->stmt->execute(); $this->stmt->execute();
@ -340,9 +324,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testCount() public function testCount()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod()->setRequestForFetch(); $this->setDriverGetConnectionMethod()->setRequestForFetch();
$this->stmt->execute(); $this->stmt->execute();
@ -357,9 +340,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testCountException() public function testCountException()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->request $this->request
->expects($this->once()) ->expects($this->once())
@ -377,9 +359,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testOrderException() public function testOrderException()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->request $this->request
->expects($this->once()) ->expects($this->once())
@ -397,9 +378,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testSkipException() public function testSkipException()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->request $this->request
->expects($this->once()) ->expects($this->once())
@ -417,9 +397,8 @@ class MongoStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testLimitException() public function testLimitException()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->request $this->request
->expects($this->once()) ->expects($this->once())

32
tests/model/MySQLiDriverTest.php

@ -57,9 +57,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testDriver() public function testDriver()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);
@ -78,9 +76,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testGetConnection() public function testGetConnection()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);
$this->assertInstanceOf('mysqli', $driver->getConnection()); $this->assertInstanceOf('mysqli', $driver->getConnection());
@ -91,9 +87,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testGetConnectionWrongConfig() public function testGetConnectionWrongConfig()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$this->conf['database'] = 'nodb'; $this->conf['database'] = 'nodb';
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);
@ -106,9 +100,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testDisconnect() public function testDisconnect()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);
@ -125,9 +117,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testInsert() public function testInsert()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);
@ -147,9 +137,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testGetInsertId() public function testGetInsertId()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);
@ -161,9 +149,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testTransaction() public function testTransaction()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);
@ -194,9 +180,7 @@ class MySQLiDriverTest extends PHPUnit_Extensions_Database_TestCase
*/ */
public function testRollback() public function testRollback()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$driver = new MySQLiDriver($this->conf); $driver = new MySQLiDriver($this->conf);

50
tests/model/MySQLiStatementTest.php

@ -10,6 +10,8 @@
* Unit tests for MySQLiStatement class * 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/CommandProfiler.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php'; require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
require_once dirname(__FILE__) . '/../../model/Db.php'; require_once dirname(__FILE__) . '/../../model/Db.php';
@ -81,9 +83,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testExecute() public function testExecute()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->driver $this->driver
->expects($this->any()) ->expects($this->any())
@ -102,9 +102,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testExecuteNoPlaceholders() public function testExecuteNoPlaceholders()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->sql = 'PLAIN SQL'; $this->sql = 'PLAIN SQL';
@ -118,9 +116,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchNoResult() public function testFetchNoResult()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->assertFalse($this->stmt->fetch()); $this->assertFalse($this->stmt->fetch());
} }
@ -130,9 +126,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testDriverExecuteNoResult() public function testDriverExecuteNoResult()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionWrongResultMethod(); $this->setDriverGetConnectionWrongResultMethod();
$this->setExpectedException('GeneralException', 'ERROR'); $this->setExpectedException('GeneralException', 'ERROR');
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val')); $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
@ -144,9 +138,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetch() public function testFetch()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val')); $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertSame('OBJECT', $this->stmt->fetch()); $this->assertSame('OBJECT', $this->stmt->fetch());
@ -161,9 +153,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchObject() public function testFetchObject()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val')); $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertSame('OBJECT', $this->stmt->fetchObject()); $this->assertSame('OBJECT', $this->stmt->fetchObject());
@ -175,9 +165,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchPairs() public function testFetchPairs()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$resultMock = $this->getMockBuilder('mysqli_result') $resultMock = $this->getMockBuilder('mysqli_result')
->disableOriginalConstructor() ->disableOriginalConstructor()
@ -218,12 +206,12 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchWithDebug() public function testFetchWithDebug()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val')); $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertSame('OBJECT', $this->stmt->fetch()); $this->assertSame('OBJECT', $this->stmt->fetch());
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
} }
/** /**
@ -232,15 +220,15 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testClose() public function testClose()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->assertAttributeEquals(null, 'result', $this->stmt); $this->assertAttributeEquals(null, 'result', $this->stmt);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val')); $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertAttributeNotEquals(null, 'result', $this->stmt); $this->assertAttributeNotEquals(null, 'result', $this->stmt);
$this->stmt->close(); $this->stmt->close();
$this->assertAttributeEquals(null, 'result', $this->stmt); $this->assertAttributeEquals(null, 'result', $this->stmt);
$this->assertContains('Queries not counted.', Profiler::getInstance()->getCli());
} }
/** /**
@ -275,9 +263,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
public function testNumRows() public function testNumRows()
{ {
$this->markTestSkipped('Unable to execute a method or access a property of an incomplete object.'); $this->markTestSkipped('Unable to execute a method or access a property of an incomplete object.');
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val')); $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));
$this->assertNull($this->stmt->numRows()); $this->assertNull($this->stmt->numRows());
@ -289,9 +275,7 @@ class MySQLiStatementTest extends PHPUnit_Framework_TestCase
*/ */
public function testFetchInvalidMode() public function testFetchInvalidMode()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('PROFILER_DETAILS', false);
$this->setDriverGetConnectionMethod(); $this->setDriverGetConnectionMethod();
$this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val')); $this->stmt->execute(array('place' => 'place_val', 'new' => 'new_val'));

14
tests/redis/RedisDebugTest.php

@ -10,6 +10,8 @@
* Unit tests for RedisDebug class * 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__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../util/profiler/CommandProfiler.php'; require_once dirname(__FILE__) . '/../../util/profiler/CommandProfiler.php';
require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php'; require_once dirname(__FILE__) . '/../../util/profiler/Profiler.php';
@ -57,9 +59,7 @@ class RedisDebugTest extends PHPUnit_Framework_TestCase
*/ */
public function testCallSimpleParams() public function testCallSimpleParams()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
$mock = $this->getMock('Redis', array('connect')); $mock = $this->getMock('Redis', array('connect'));
$mock->expects($this->once()) $mock->expects($this->once())
@ -77,9 +77,7 @@ class RedisDebugTest extends PHPUnit_Framework_TestCase
*/ */
public function testCallArrayParam() public function testCallArrayParam()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
$mock = $this->getMock('Redis', array('connect')); $mock = $this->getMock('Redis', array('connect'));
$mock->expects($this->once()) $mock->expects($this->once())
@ -97,9 +95,7 @@ class RedisDebugTest extends PHPUnit_Framework_TestCase
*/ */
public function testCallUndefinedMethod() public function testCallUndefinedMethod()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
$mock = $this->getMock('Redis', array('connect')); $mock = $this->getMock('Redis', array('connect'));
$redisDebug = new RedisDebug($mock); $redisDebug = new RedisDebug($mock);

7
tests/redis/RedisManagerTest.php

@ -1,4 +1,4 @@
<?php
<?php
/* /*
* @copyright NetMonsters <team@netmonsters.ru> * @copyright NetMonsters <team@netmonsters.ru>
@ -107,9 +107,8 @@ class RedisManagerTest extends PHPUnit_Framework_TestCase
*/ */
public function testConnectWithDebug() public function testConnectWithDebug()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('RedisDebug'); $this->getMock('RedisDebug');
Config::set('Redis', array('new' => array('host' => true, 'port' => 2023, 'database' => true))); Config::set('Redis', array('new' => array('host' => true, 'port' => 2023, 'database' => true)));

30
tests/util/AutoloadBuilderTest.php

@ -75,7 +75,7 @@ class AutoloadBuilderTest extends PHPUnit_Framework_TestCase
public function testBuild() public function testBuild()
{ {
$this->setConstants(); $this->setConstants();
$builder = new AutoloadBuilder(self::$file, array(self::$path . '/' . self::$app . '/src', self::$path . '/' . self::$app . '/cache', self::$path . '/lib'));
$builder = new AutoloadBuilder(self::$file, array_keys(self::$inc_dirs));
$this->assertFileNotExists(self::$file); $this->assertFileNotExists(self::$file);
$builder->build(); $builder->build();
@ -92,18 +92,38 @@ class AutoloadBuilderTest extends PHPUnit_Framework_TestCase
/** /**
* @runInSeparateProcess * @runInSeparateProcess
*/ */
public function testAccessDenied()
public function testBuildWithExcluded()
{ {
$this->setConstants(); $this->setConstants();
$builder = new AutoloadBuilder(self::$file, array_keys(self::$inc_dirs), array(self::$path . '/lib/core/app/'));
$this->setExpectedException('PHPUnit_Framework_Error');
$this->assertFileNotExists(self::$file); $this->assertFileNotExists(self::$file);
$builder->build();
touch(self::$file);
$this->assertFileExists(self::$file); $this->assertFileExists(self::$file);
chmod(self::$file, 0400);
$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')); $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(); $builder->build();
chmod(self::$file, 0777); chmod(self::$file, 0777);
} }

223
tests/util/profiler/ProfilerTest.php

@ -10,6 +10,8 @@
* Unit tests for CommandProfiler class * 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__) . '/../../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../../util/FirePHPCore-0.3.2/lib/FirePHPCore/fb.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__) . '/../../../util/profiler/Profiler.php';
@ -36,10 +38,8 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/ */
public function testGetInstaceNoDebug() public function testGetInstaceNoDebug()
{ {
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$this->setExpectedException('GeneralException', 'Need to turn on DEBUG before use.');
Config::set('PROFILER', false);
$this->setExpectedException('GeneralException', 'Need turn PROFILER before use.');
Profiler::getInstance(); Profiler::getInstance();
} }
@ -48,9 +48,7 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/ */
public function testGetInstance() public function testGetInstance()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
$profiler = Profiler::getInstance(); $profiler = Profiler::getInstance();
$this->assertInstanceOf('Profiler', $profiler); $this->assertInstanceOf('Profiler', $profiler);
$this->assertSame($profiler, Profiler::getInstance()); $this->assertSame($profiler, Profiler::getInstance());
@ -61,9 +59,7 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/ */
public function testProfilerCommand() public function testProfilerCommand()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false); $this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance(); $profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type'); $cmdProfiler = $profiler->profilerCommand('command', 'type');
@ -75,9 +71,8 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/ */
public function testStartEndNoCommandProfiler() public function testStartEndNoCommandProfiler()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$profiler = Profiler::getInstance(); $profiler = Profiler::getInstance();
$profiler->start(); $profiler->start();
$result = $profiler->end('<body></body>'); $result = $profiler->end('<body></body>');
@ -95,15 +90,15 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/ */
public function testStartEndWithCommandProfiler() public function testStartEndWithCommandProfiler()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false); $this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance(); $profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$profiler->start(); $profiler->start();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$this->assertNotNull($cmdProfiler);
$result = $profiler->end('<body></body>'); $result = $profiler->end('<body></body>');
$this->assertNotEquals('<body></body>', $result); $this->assertNotEquals('<body></body>', $result);
$this->assertStringEndsNotWith(']<br/></div></body>', $result); $this->assertStringEndsNotWith(']<br/></div></body>', $result);
@ -113,16 +108,146 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
/** /**
* @runInSeparateProcess * @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() public function testGetJSON()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
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); $this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance(); $profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type'); $cmdProfiler = $profiler->profilerCommand('command', 'type');
$this->assertNull($profiler->getJson());
$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());
} }
/** /**
@ -130,21 +255,67 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/ */
public function testGetCLI() public function testGetCLI()
{ {
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false); $this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance(); $profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type'); $cmdProfiler = $profiler->profilerCommand('command', 'type');
$result = $profiler->getCli(); $result = $profiler->getCli();
$this->assertNotNull($result); $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() public function tearDown()
{ {
// if (defined('DEBUG')) {
// $debug = DEBUG ? 'TRUE' : 'FALSE';
// if (!is_null(Config::get('DEBUG'))) {
// $debug = Config::get('DEBUG') ? 'TRUE' : 'FALSE';
// echo PHP_EOL . __CLASS__ . ' ' . $debug . PHP_EOL; // echo PHP_EOL . __CLASS__ . ' ' . $debug . PHP_EOL;
// } else { // } else {
// echo PHP_EOL . __CLASS__ . ' ' . 'DEBUG NOT DEFINED' . PHP_EOL; // echo PHP_EOL . __CLASS__ . ' ' . 'DEBUG NOT DEFINED' . PHP_EOL;

9
tests/view/helpers/GetViewHelperTest.php

@ -68,5 +68,14 @@ class GetViewHelperTest extends PHPUnit_Framework_TestCase
$result = $this->helper->get(array('b' => 'c', 'c' => array('five' => 'six'))); $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); $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);
}
} }

21
util/AutoloadBuilder.php

@ -46,7 +46,7 @@ class AutoloadBuilder
foreach ($iterator as $file) { foreach ($iterator as $file) {
if($this->isExcluded($file->getRealPath())) {
if ($this->isExcluded($file->getRealPath())) {
continue; continue;
} }
// skip non php files // skip non php files
@ -70,30 +70,37 @@ class AutoloadBuilder
} }
} }
} }
unset($file); // without this line trigger_error throws 'Serialization of 'SplFileInfo' is not allowed' exception under PHPUnit
} }
$array_string .= ');'; $array_string .= ');';
$this->writeAutoload($array_string); $this->writeAutoload($array_string);
$this->isFileConsistent();
if (!$this->isFileConsistent()) {
unlink($this->autoload);
trigger_error("Error while generating autoload file.", E_USER_ERROR);
}
} }
protected function writeAutoload($string) protected function writeAutoload($string)
{ {
file_put_contents($this->autoload, $string);
$pid = getmypid();
$tmp = dirname($this->autoload) . '/' . md5(time() + $pid);
file_put_contents($tmp, $string);
rename($tmp, $this->autoload);
} }
protected function isFileConsistent() protected function isFileConsistent()
{ {
$autoload_array = include($this->autoload); $autoload_array = include($this->autoload);
if(!is_array($autoload_array)) {
unlink($this->autoload);
trigger_error("Error while generating autoload file.", E_USER_ERROR);
if (!is_array($autoload_array)) {
return false;
} }
return true;
} }
protected function isExcluded($file) protected function isExcluded($file)
{ {
foreach ($this->exclude as $dir) { foreach ($this->exclude as $dir) {
if (stripos($file, PATH . $dir) === 0) {
if (stripos($file, $dir) === 0) {
return true; return true;
} }
} }

27
util/profiler/Profiler.php

@ -22,8 +22,8 @@ class Profiler
private function __construct() private function __construct()
{ {
if (DEBUG == false) {
throw new GeneralException('Need to turn on DEBUG before use.');
if (Config::get('PROFILER') == false) {
throw new GeneralException('Need turn PROFILER before use.');
} }
} }
@ -59,6 +59,7 @@ class Profiler
public function start() public function start()
{ {
$this->queries = array();
$this->start = microtime(true); $this->start = microtime(true);
} }
@ -80,8 +81,12 @@ class Profiler
$queriesTime += $query->getElapsed(); $queriesTime += $query->getElapsed();
} }
$html = '<div style="clear:both; font:12px monospace; margin: 5px; white-space: pre;">' $html = '<div style="clear:both; font:12px monospace; margin: 5px; white-space: pre;">'
. 'Elapsed time: ' . round(($this->end - $this->start) * 1000, 2) . 'ms.<br/>'
. 'Queries: ' . count($this->queries) . ' [' . round($queriesTime * 1000, 2) . ' ms]<br/>';
. 'Elapsed time: ' . round(($this->end - $this->start) * 1000, 2) . 'ms.<br/>';
if (count($this->queries) == 0 && !Config::get('PROFILER_DETAILS')) {
$html .= 'Queries not counted. Turn PROFILER_DETAILS if you want to profile queries.<br/>';
} else {
$html .= 'Queries: ' . count($this->queries) . ' [' . round($queriesTime * 1000, 2) . ' ms]<br/>';
}
$html .= $temp; $html .= $temp;
$html .= '</div>'; $html .= '</div>';
return $html; return $html;
@ -99,7 +104,11 @@ class Profiler
$table[] = array($query->getType(), round($query->getElapsed() * 1000, 2), $query->getCommand()); $table[] = array($query->getType(), round($query->getElapsed() * 1000, 2), $query->getCommand());
$queriesTime += $query->getElapsed(); $queriesTime += $query->getElapsed();
} }
FB::table('Queries: ' . count($this->queries) . ' [' . round($queriesTime * 1000, 2) . ' ms]', $table);
if (count($this->queries) == 0 && !Config::get('PROFILER_DETAILS')) {
FB::table('Queries not counted. Turn PROFILER_DETAILS if you want to profile queries.', $table);
} else {
FB::table('Queries: ' . count($this->queries) . ' [' . round($queriesTime * 1000, 2) . ' ms]', $table);
}
} }
public function getCli() public function getCli()
@ -112,8 +121,12 @@ class Profiler
$queriesTime += $query->getElapsed(); $queriesTime += $query->getElapsed();
} }
$html = str_pad(PHP_EOL, 60, '-', STR_PAD_LEFT); $html = str_pad(PHP_EOL, 60, '-', STR_PAD_LEFT);
$html .= 'Elapsed time: ' . round(($this->end - $this->start) * 1000, 2) . 'ms.' . PHP_EOL
. 'Queries: ' . count($this->queries) . ' [' . round($queriesTime * 1000, 2) . ' ms] ' . PHP_EOL;
$html .= 'Elapsed time: ' . round(($this->end - $this->start) * 1000, 2) . 'ms.' . PHP_EOL;
if (count($this->queries) == 0 && !Config::get('PROFILER_DETAILS')) {
$html .= 'Queries not counted. Turn PROFILER_DETAILS if you want to profile queries.' . PHP_EOL;
} else {
$html .= 'Queries: ' . count($this->queries) . ' [' . round($queriesTime * 1000, 2) . ' ms] ' . PHP_EOL;
}
$html .= $temp; $html .= $temp;
return $html; return $html;
} }

4
view/helpers/GetViewHelper.php

@ -46,11 +46,11 @@ class GetViewHelper extends ViewHelper
if (is_array($value)){ if (is_array($value)){
$result = array(); $result = array();
foreach ($value as $key => $val) { foreach ($value as $key => $val) {
$result[] = $name . '[' . $key . ']=' . $val;
$result[] = $name . '[' . $key . ']=' . urlencode($val);
} }
$result = implode('&', $result); $result = implode('&', $result);
} else { } else {
$result = $name . '=' . $value;
$result = $name . '=' . urlencode($value);
} }
return $result; return $result;
} }
Loading…
Cancel
Save