Browse Source

Merge branch 'mongo'

master
Anton Terekhov 12 years ago
parent
commit
07206a0365
  1. 5
      Load.php
  2. 70
      app/CliController.php
  3. 7
      app/FrontController.php
  4. 18
      app/iCli.php
  5. 5
      exception/ErrorHandler.php
  6. 2
      logger/Logger.php
  7. 1
      model/Db.php
  8. 3
      model/DbStatement.php
  9. 17
      model/Model.php
  10. 32
      model/MongoDbCommand.php
  11. 20
      model/MongoDriver.php
  12. 157
      model/MongoModel.php
  13. 7
      model/MongoStatement.php
  14. 52
      model/MySQLiDriver.php
  15. 5
      model/MySQLiStatement.php
  16. 14
      model/SqlDbDriver.php
  17. 26
      model/SqlModel.php
  18. 2
      redis/RedisManager.php
  19. 6
      tests/LoadTest.php
  20. 17
      tests/app/ActionTest.php
  21. 2
      tests/app/Action_TestCase.php
  22. 15
      tests/app/AjaxActionTest.php
  23. 101
      tests/app/CliControllerTest.php
  24. 10
      tests/app/ErrorActionTest.php
  25. 5
      tests/app/FrontControllerTest.php
  26. 25
      tests/app/PagerActionTest.php
  27. 10
      tests/app/StaticActionTest.php
  28. 10
      tests/classes/EnvTest.php
  29. 13
      tests/exception/ErrorHandlerTest.php
  30. 12
      tests/layout/ErrorLayoutTest.php
  31. 26
      tests/layout/LayoutTest.php
  32. 6
      tests/logger/CliLoggerTest.php
  33. 13
      tests/logger/FileLoggerTest.php
  34. 11
      tests/model/MongoDbCommandTest.php
  35. 95
      tests/model/MongoDriverTest.php
  36. 277
      tests/model/MongoModelTest.php
  37. 95
      tests/model/MongoStatementTest.php
  38. 32
      tests/model/MySQLiDriverTest.php
  39. 50
      tests/model/MySQLiStatementTest.php
  40. 14
      tests/redis/RedisDebugTest.php
  41. 7
      tests/redis/RedisManagerTest.php
  42. 223
      tests/util/profiler/ProfilerTest.php
  43. 27
      util/profiler/Profiler.php

5
Load.php

@ -39,6 +39,9 @@ class Load
self::buildAutoload();
}
self::$autoload = require(self::$file);
spl_autoload_register(array(
__CLASS__,
'autoload'));
}
static public function autoload($class)
@ -47,7 +50,7 @@ class Load
require(PATH . self::$autoload[$class]);
return;
}
if (defined('DEBUG') && DEBUG == true) {
if (Config::get('DEBUG')) {
if (!isset(self::$autoload[$class])) {
self::buildAutoload();
}

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

7
app/FrontController.php

@ -32,9 +32,6 @@ class FrontController
private function __construct()
{
ErrorHandler::init();
if (DEBUG == true) {
Profiler::getInstance()->start();
}
$this->router = new Router();
}
@ -120,7 +117,7 @@ class FrontController
$layout = new $layout_class();
$html = $layout->fetch($action);
if (DEBUG) {
if (Config::get('PROFILER')) {
if (is_subclass_of($action, 'AjaxAction')) {
Profiler::getInstance()->getJson();
} else {
@ -129,7 +126,7 @@ class FrontController
}
return $html;
} catch (Exception $e) {
if (DEBUG == true) {
if (Config::get('DEBUG')) {
if (!headers_sent()) {
header('HTTP/1.0 500 Internal Server Error');
}

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
exception/ErrorHandler.php

@ -23,7 +23,10 @@ class ErrorHandler
if (!empty($ob_handlers)) {
ob_end_clean();
}
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
if (error_reporting() !== 0) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}
return true;
}
static protected function getSource($file, $hiline)

2
logger/Logger.php

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

1
model/Db.php

@ -31,6 +31,7 @@ class Db
* @param array $config Configuration array.
*
* @return DbDriver
* @throws InitializationException
*/
static public function connect($name = 'default', $config = null)
{

3
model/DbStatement.php

@ -66,6 +66,7 @@ abstract class DbStatement
/**
* @param string $field
* @return array Value of queried field for all matching rows
*/
public function fetchColumn($field)
{
@ -78,6 +79,7 @@ abstract class DbStatement
/**
* @param string $field
* @return mixed Value of queried filed for first matching row
*/
public function fetchField($field)
{
@ -108,6 +110,7 @@ abstract class DbStatement
abstract public function numRows();
/**
* @param mixed $request
* @return bool
*/
abstract protected function driverExecute($request);

17
model/Model.php

@ -63,7 +63,6 @@ abstract class Model
/**
* @param array $data
* @param array $on_duplicate
* @return int Id of inserted row
*/
public function insert($data)
@ -152,22 +151,22 @@ abstract class Model
abstract public function delete($id);
/**
* @param string $sql
* @param array $params
* @param string $field
* @param CacheKey $cache_key
* @param string $data Request
* @param array $params Request parameters
* @param string $field Requested field name
* @param CacheKey $cache_key Key for caching in
*/
abstract protected function fetchField($data, $params = array(), $field, $cache_key = null);
/**
* @param string $sql
* @param array $params
* @param CacheKey $cache_key
* @param string $data Request
* @param array $params Request parameters
* @param CacheKey $cache_key Key for caching in
*/
abstract protected function fetch($data, $params = array(), $cache_key = null);
/**
* @param string $sql
* @param string $data
* @param array $params
* @param CacheKey $cache_key
*/

32
model/MongoDbCommand.php

@ -22,6 +22,12 @@ class MongoCommandBuilder
const COMMAND = 'Command';
/**
* @param string $type
* @param MongoCollection $collection
* @return MongoDbCommand
*/
static public function factory($type, $collection = null)
{
$class = ucfirst($type) . 'MongoCommand';
@ -33,8 +39,18 @@ class MongoCommandBuilder
abstract class MongoDbCommand
{
/**
* @var MongoCollection
*/
protected $collection;
/**
* Execute Mongo command/query
*
* @return mixed
* @throws GeneralException
*/
public function execute()
{
if ($this->checkParams()) {
@ -44,6 +60,12 @@ abstract class MongoDbCommand
}
}
/**
* @param string $name Parameter name
* @param mixed $value Parameter value
* @return MongoDbCommand
*/
public function bindParam($name, $value)
{
if (property_exists($this, $name)) {
@ -52,12 +74,22 @@ abstract class MongoDbCommand
return $this;
}
/**
* @param MongoCollection $collection Mongo collection
* @return MongoDbCommand
*/
public function setCollection($collection)
{
$this->collection = $collection;
return $this;
}
/**
* Convert query parameters array to string
*
* @param array $array
* @return string
*/
protected function arrayToString($array)
{
$string = '[';

20
model/MongoDriver.php

@ -38,6 +38,12 @@ class MongoDriver extends NoSqlDbDriver
return $this->query($command, $params)->affectedRows();
}
/**
* @param string $collection Mongo collection name to search in
* @param array $condition Search conditions
* @param array $fields Fields to return in result set
* @return MongoStatement
*/
public function find($collection, $condition = array(), $fields = array())
{
$command = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->getCollection($collection));
@ -49,17 +55,6 @@ class MongoDriver extends NoSqlDbDriver
return $this->query($command, $params);
}
public function get($collection, $condition, $fields = array())
{
$command = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, $this->getCollection($collection));
$params = array(
'condition' => $condition,
'fields' => $fields,
'multiple' => false
);
return $this->query($command, $params);
}
public function findAndModify($collection, $query, $update, $sort = array(), $field = array(), $upsert = false, $new = false, $remove = false)
{
$command = MongoCommandBuilder::factory(MongoCommandBuilder::COMMAND, $this->getCollection($collection));
@ -123,10 +118,9 @@ class MongoDriver extends NoSqlDbDriver
}
/**
* @param mixed $request
* @return DbStatement
* @return MongoStatement
*/
public function prepare($request)
{

157
model/MongoModel.php

@ -10,9 +10,20 @@
* @since 2011-11-15
*/
/**
* @property MongoDriver $db
*/
abstract class MongoModel extends Model
{
/**
* @var string Mongo id field to use as key
*/
protected $key = '_id';
/**
* @var bool Is Mongo key field uses original MongoId
*/
protected $useMongoId = true;
public function __construct($connection = 'default')
@ -20,16 +31,11 @@ abstract class MongoModel extends Model
parent::__construct($connection);
}
public function count($query = array(), $limit = 0, $skip = 0)
protected function count($query = array(), $limit = 0, $skip = 0)
{
return $this->db->count($this->table(), $query, $limit, $skip);
}
public function find($condition = array(), $fields = array())
{
return $this->db->find($this->table(), $condition, $fields);
}
public function get($id)
{
if ($this->useMongoId) {
@ -37,7 +43,7 @@ abstract class MongoModel extends Model
$id = new MongoId($id);
}
}
return $this->db->get($this->table(), array('_id' => $id))->fetch();
return $this->fetch(array($this->key => $id));
}
public function batchInsert($data)
@ -45,25 +51,42 @@ abstract class MongoModel extends Model
return $this->db->insert($this->table(), $data, true);
}
public function delete($id)
public function update($data, $where)
{
if ($this->useMongoId) {
if (!$id instanceof MongoId) {
$id = new MongoId($id);
if (!$where instanceof MongoId) {
$where = new MongoId($where);
}
}
return $this->db->delete($this->table(), array('_id' => $id));
return $this->db->update($this->table(), $data, array($this->key => $where));
}
public function deleteAll($query = array())
public function delete($id)
{
$this->db->delete($this->table(), $query);
if ($this->useMongoId) {
if (!$id instanceof MongoId) {
$id = new MongoId($id);
}
}
return $this->db->delete($this->table(), array($this->key => $id));
}
/**
* @param array $data Request
* @param array $params Request parameters
* @param string $field Requested field name
* @param CacheKey $cache_key Key for caching in
* @return mixed
*/
protected function fetchField($data, $params = array(), $field, $cache_key = null)
{
if (!$cache_key || !$result = $cache_key->get()) {
$result = $this->db->find($this->table(), $data, array($field => 1))->fetchField($field);
$result = $this->db
->find($this->table(), $data, array($field => 1))
->limit($this->getLimit($params))
->skip($this->getSkip($params))
->order($this->getOrder($params))
->fetchField($field);
if ($cache_key) {
$cache_key->set($result);
}
@ -71,10 +94,21 @@ abstract class MongoModel extends Model
return $result;
}
/**
* @param array $data Request
* @param array $params Request parameters
* @param CacheKey $cache_key Key for caching in
* @return mixed
*/
protected function fetch($data, $params = array(), $cache_key = null)
{
if (!$cache_key || !$result = $cache_key->get()) {
$result = $this->db->find($this->table(), $data)->fetch();
$result = $this->db
->find($this->table(), $data, $this->getFields($params))
->limit(1)
->skip($this->getSkip($params))
->order($this->getOrder($params))
->fetch();
if ($cache_key) {
$cache_key->set($result);
}
@ -82,14 +116,105 @@ abstract class MongoModel extends Model
return $result;
}
/**
* @param array $data
* @param array $params
* @param CacheKey $cache_key
* @return array
*/
protected function fetchAll($data, $params = array(), $cache_key = null)
{
if (!$cache_key || !$result = $cache_key->get()) {
$result = $this->db->find($this->table(), $data)->fetchAll();
$result = $this->db
->find($this->table(), $data, $this->getFields($params))
->limit($this->getLimit($params))
->skip($this->getSkip($params))
->order($this->getOrder($params))
->fetchAll();
if ($cache_key) {
$cache_key->set($result);
}
}
return $result;
}
/**
* @param array $params Parameters for find query
* @return int Query result limits rule
* */
private function getLimit($params = array())
{
return isset($params['limit']) ? (int) $params['limit'] : 0;
}
/**
* @param array $params Parameters for find query
* @return int Query result skip rule
* */
private function getSkip($params = array())
{
return isset($params['skip']) ? (int) $params['skip'] : 0;
}
/**
* @param array $params Parameters for find query
* @return array Query result sort rules
* @throws GeneralException
* */
private function getOrder($params = array())
{
$order = array();
if (isset($params['order'])) {
if (is_string($params['order'])) {
$order = array($params['order'] => 1);
} elseif (is_array($params['order'])) {
$order = $params['order'];
} else {
throw new GeneralException('Wrong order parameter given to query.');
}
}
return $order;
}
/**
* @param array $params Parameters for find query
* @return array Query result sort rules
* @throws GeneralException
* */
private function getFields($params)
{
$fields = array();
if (isset($params['fields'])) {
if (is_string($params['fields'])) {
$fields = array($params['fields'] => 1);
} elseif (is_array($params['fields'])) {
if (array_keys($params['fields']) === range(0, count($params['fields']) - 1)) {
foreach ($params['fields'] as $filed) {
$fields[$filed] = 1;
}
} else {
$fields = $params['fields'];
}
} else {
throw new GeneralException('Wrong fields parameter given to query.');
}
}
return $fields;
}
/**
* Sets the additional condition if it is set
*
* @param array $query Initial query
* @param string $filed Field name to set
* @param mixed $value Field value to set
* @return MongoModel Current model object
*/
protected function addCondition(&$query, $filed, $value)
{
if(!is_null($value) && $value !== false) {
$query[$filed] = $value;
}
return $this;
}
}

7
model/MongoStatement.php

@ -114,7 +114,7 @@ class MongoStatement extends DbStatement
} else {
return false;
}
} elseif (is_int($this->result)) {
} elseif (is_int($this->result) || $this->result instanceof MongoId) {
return $this->result;
}
return false;
@ -138,7 +138,7 @@ class MongoStatement extends DbStatement
$this->result = false;
$mongo = $this->driver->getConnection();
if ($mongo instanceof Mongo) {
if (DEBUG) {
if (Config::get('PROFILER_DETAILS')) {
$profiler = Profiler::getInstance()->profilerCommand('Mongo', $request);
$result = $request->execute();
$profiler->end();
@ -156,6 +156,9 @@ class MongoStatement extends DbStatement
if (is_array($result) && isset($result['values'])) {
$this->result = $result['values'];
}
if (is_array($result) && isset($result['upserted'])) {
$this->result = $result['n'] > 1 ? $result['n'] : $result['upserted'];
}
} elseif (is_int($result)) {
$this->result = $result;
}

52
model/MySQLiDriver.php

@ -14,7 +14,7 @@
*/
class MySQLiDriver extends SqlDbDriver
{
public function insert($table, $bind, $on_duplicate = array())
{
$columns = array();
@ -22,7 +22,7 @@ class MySQLiDriver extends SqlDbDriver
$columns[] = $this->quoteIdentifier($col);
}
$values = array_values($bind);
if ($on_duplicate) {
$update = array();
foreach ($on_duplicate as $col => $val) {
@ -30,16 +30,16 @@ class MySQLiDriver extends SqlDbDriver
}
$on_duplicate = ' ON DUPLICATE KEY UPDATE ' . implode(', ', $update);
}
$sql = 'INSERT INTO ' . $this->quoteIdentifier($table)
. ' (' . implode(', ', $columns) . ') VALUES (' . $this->quote($values) . ')'
. (($on_duplicate) ? $on_duplicate : '');
. ' (' . implode(', ', $columns) . ') VALUES (' . $this->quote($values) . ')'
. (($on_duplicate) ? $on_duplicate : '');
return $this->query($sql)->affectedRows();
}
/**
* @param mixed $sql
* @return DbStatement
* @return MySQLiStatement
*/
public function prepare($sql)
{
@ -50,73 +50,73 @@ class MySQLiDriver extends SqlDbDriver
{
return $this->connection->insert_id;
}
public function isConnected()
{
return ($this->connection instanceof MySQLi);
}
public function disconnect()
{
if ($this->isConnected()) {
$this->connection->close();
}
$this->connection = null;
$this->connection = null;
}
protected function connect()
{
if ($this->connection) {
return;
}
$port = isset($this->config['port']) ? (int) $this->config['port'] : null;
$this->connection = mysqli_init();
$connected = @mysqli_real_connect($this->connection,
$this->config['hostname'],
$this->config['username'],
$this->config['password'],
$this->config['database'],
$port);
@mysqli_real_connect($this->connection,
$this->config['hostname'],
$this->config['username'],
$this->config['password'],
$this->config['database'],
$port);
// Connection errors check
if (mysqli_connect_error()) {
throw new GeneralException(mysqli_connect_error(), mysqli_connect_errno());
}
$charset = (!empty($this->config['charset'])) ? $this->config['charset'] : 'utf8';
$this->connection->set_charset($charset);
}
protected function driverQuote($value)
{
if (is_int($value) || is_float($value)) {
return $value;
}
if (is_bool($value)) {
return (int) $value;
}
if ($value === null) {
return 'NULL';
}
$this->connect();
return '\'' . $this->connection->real_escape_string($value) . '\'';
}
protected function driverBeginTransaction()
{
$this->connect();
$this->connection->autocommit(false);
}
protected function driverCommitTransaction()
{
$this->connection->commit();
$this->connection->autocommit(true);
}
protected function driverRollbackTransaction()
{
$this->connection->rollback();

5
model/MySQLiStatement.php

@ -83,6 +83,7 @@ class MySQLiStatement extends DbStatement
*
* @param mixed $style
* @return mixed
* @throws GeneralException
*/
public function fetch($style = Db::FETCH_OBJ)
{
@ -90,7 +91,6 @@ class MySQLiStatement extends DbStatement
return false;
}
$row = false;
switch ($style) {
case Db::FETCH_OBJ:
$row = $this->result->fetch_object();
@ -112,6 +112,7 @@ class MySQLiStatement extends DbStatement
/**
* @param string $class
* @return object
*/
public function fetchObject($class = 'stdClass')
{
@ -157,7 +158,7 @@ class MySQLiStatement extends DbStatement
* @var MySQLi
*/
$mysqli = $this->driver->getConnection();
if (DEBUG) {
if (Config::get('PROFILER_DETAILS')) {
$profiler = Profiler::getInstance()->profilerCommand('MySQL', $request);
$result = $mysqli->query($request);
$profiler->end();

14
model/SqlDbDriver.php

@ -37,7 +37,7 @@ abstract class SqlDbDriver extends DbDriver
/**
* @param string $table
* @param mixed $bind
* @param mixed $data
* @param mixed $on_duplicate
* @return int Affected rows count
*/
@ -56,9 +56,9 @@ abstract class SqlDbDriver extends DbDriver
/**
* @param string $table
* @param array $bind
* @param mixed $where
* @return int
* @param array $data
* @param mixed $condition
* @return int Number of updated rows
*/
public function update($table, $data, $condition = '')
{
@ -74,7 +74,7 @@ abstract class SqlDbDriver extends DbDriver
/**
* @param string $table
* @param mixed $where
* @param mixed $condition
* @return int
*/
public function delete($table, $condition = '')
@ -152,10 +152,6 @@ abstract class SqlDbDriver extends DbDriver
return implode(' AND ', $where);
}
/**
* @return DbStatement
*/
abstract protected function driverQuote($value);
abstract protected function driverBeginTransaction();

26
model/SqlModel.php

@ -10,6 +10,9 @@
* @since 2011-11-11
*/
/**
* @property SqlDbDriver $db
*/
abstract class SqlModel extends Model
{
@ -105,8 +108,10 @@ abstract class SqlModel extends Model
/**
* This method appends to params table and primary key.
* So they can be accessed thru `:table` and `:pk` placeholders.
* So they can be accessed through `:table` and `:pk` placeholders.
*
* @param string $sql
* @param array $params
* @return DbStatement
*/
protected function query($sql, $params = array())
@ -122,10 +127,11 @@ abstract class SqlModel extends Model
}
/**
* @param string $sql
* @param array $params
* @param string $field
* @param CacheKey $cache_key
* @param string $data Request
* @param array $params Request parameters
* @param string $field Requested field name
* @param CacheKey $cache_key Key for caching in
* @return mixed
*/
protected function fetchField($data, $params = array(), $field, $cache_key = null)
{
@ -139,9 +145,10 @@ abstract class SqlModel extends Model
}
/**
* @param string $sql
* @param array $params
* @param CacheKey $cache_key
* @param string $data Request
* @param array $params Request parameters
* @param CacheKey $cache_key Key for caching in
* @return mixed
*/
protected function fetch($data, $params = array(), $cache_key = null)
{
@ -155,9 +162,10 @@ abstract class SqlModel extends Model
}
/**
* @param string $sql
* @param string $data
* @param array $params
* @param CacheKey $cache_key
* @return array
*/
protected function fetchAll($data, $params = array(), $cache_key = null)
{

2
redis/RedisManager.php

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

6
tests/LoadTest.php

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

17
tests/app/ActionTest.php

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

2
tests/app/Action_TestCase.php

@ -10,6 +10,8 @@
* Action_TestCase class for testing Actions
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../Load.php';
require_once dirname(__FILE__) . '/../../classes/Env.class.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';

15
tests/app/AjaxActionTest.php

@ -21,9 +21,8 @@ class AjaxActionTest extends Action_TestCase
*/
public function testConstruct()
{
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('ajax' => 'AjaxTemplate', 'param2' => 'value2'));
$action = $this->getMockForAbstractClass('AjaxAction' );
$this->assertAttributeEquals('ajax', 'template', $action);
@ -34,9 +33,8 @@ class AjaxActionTest extends Action_TestCase
*/
public function testFetchWithEncode()
{
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$controller = FrontController::getInstance();
$controller->setView('SomeView');
$action = $this->getMockForAbstractClass('AjaxAction' );
@ -51,9 +49,8 @@ class AjaxActionTest extends Action_TestCase
*/
public function testFetchNoEncode()
{
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
Env::setParams(array('encode' => false));
$controller = FrontController::getInstance();
$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()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$exception = $this->getMock('ErrorException');
$controller = FrontController::getInstance();
$controller->setView('SomeView');
@ -123,9 +122,8 @@ class ErrorActionTest extends Action_TestCase
private function setConstants($val = false)
{
if (!defined('DEBUG')) {
define('DEBUG', $val);
}
Config::set('DEBUG', $val);
}
private function header()

5
tests/app/FrontControllerTest.php

@ -210,9 +210,8 @@ class FrontControllerTest extends PHPUnit_Framework_TestCase
private function setConstants($val = false)
{
if (!defined('DEBUG')) {
define('DEBUG', $val);
}
Config::set('DEBUG', $val);
}
public function tearDown()

25
tests/app/PagerActionTest.php

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

10
tests/app/StaticActionTest.php

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

10
tests/classes/EnvTest.php

@ -24,9 +24,8 @@ class EnvTest extends PHPUnit_Framework_TestCase
*/
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';
$this->assertSame('/test/index.php', Env::getRequestUri());
$_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()
{
if(!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$class = new ReflectionClass('Env');
$this->started = $class->getProperty('request');
$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);
}
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
*/

12
tests/layout/ErrorLayoutTest.php

@ -8,6 +8,8 @@
* @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';
@ -40,9 +42,8 @@ class ErrorLayoutTest extends PHPUnit_Framework_TestCase
public function testSetException()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = new ErrorLayout();
$layout->setException(new GeneralException());
$this->assertAttributeInstanceOf('GeneralException', 'exception', $layout);
@ -50,9 +51,8 @@ class ErrorLayoutTest extends PHPUnit_Framework_TestCase
public function testExecute()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$action = $this->getMock('Action', array('fetch'));
$action->expects($this->once())
->method('fetch')

26
tests/layout/LayoutTest.php

@ -10,6 +10,8 @@
* Unit tests for Layout class
*/
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../exception/ErrorHandler.php';
require_once dirname(__FILE__) . '/../../app/FrontController.php';
require_once dirname(__FILE__) . '/../../layout/Layout.php';
@ -40,18 +42,16 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function testConstruct()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout');
$this->assertAttributeInstanceOf('PHPView', 'view', $layout);
}
public function testFetch()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout');
$action = $this->getMock('Action', array('fetch'));
@ -64,9 +64,8 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function testFetchWithTemplate()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout');
$class = new ReflectionClass('Layout');
@ -89,9 +88,8 @@ class LayoutTest extends PHPUnit_Framework_TestCase
public function testAppend()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$layout = $this->getMockForAbstractClass('Layout', array('append', 'prepend'), 'LayoutMock');
$action = $this->getMock('Action', array('fetch'));
@ -128,8 +126,8 @@ class LayoutTest extends PHPUnit_Framework_TestCase
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;
// } else {
// 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()
{
if(!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('LOGGING', true);
Config::set('Logger', array('logger' => 'CliLogger'));
$logger = Logger::getInstance();
ob_start();
$logger->setPid(123);

13
tests/logger/FileLoggerTest.php

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

11
tests/model/MongoDbCommandTest.php

@ -16,7 +16,7 @@ require_once dirname(__FILE__) . '/../../model/MongoDriver.php';
require_once dirname(__FILE__) . '/../../model/MongoDbCommand.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
class MongoDbCommandTest extends PHPUnit_Framework_TestCase
class MongoDbCommandTest extends PHPUnit_Framework_TestCase
{
private $conf = array();
@ -323,11 +323,14 @@ class MongoDbCommandTest extends PHPUnit_Framework_TestCase
*/
public function testToString()
{
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT, new CollectionMock());
$cmd->bindParam('condition', array());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::COUNT);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd->bindParam('collection', new CollectionMock());
$this->assertStringStartsWith("\n" . 'Collection: CollectionMock', $cmd->__toString());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND, new CollectionMock());
$cmd = MongoCommandBuilder::factory(MongoCommandBuilder::FIND);
$this->assertSame('Command properties not set', $cmd->__toString());
$cmd->bindParam('collection', new CollectionMock());
$cmd->bindParam('condition', array());
$this->assertStringStartsWith("\n" . 'Collection: CollectionMock', $cmd->__toString());
$this->assertContains('Condition: ' . '[]' . PHP_EOL, $cmd->__toString());

95
tests/model/MongoDriverTest.php

@ -114,9 +114,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testFind()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
@ -145,9 +143,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testOrderSkipLimit()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
@ -184,9 +180,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testCount()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(5, $mongo->count('items'));
$this->assertEquals(2, $mongo->count('items', array('name' => 'eggs')));
@ -199,9 +193,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testCursorCount()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(5, $mongo->find('items')->count(5));
$this->assertCount(3, $mongo->find('items')->limit(3)->fetchAll());
@ -212,29 +204,9 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
* @runInSeparateProcess
* @group Mongo
*/
public function testGet()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$mongo = new MongoDriver($this->conf);
$eggs = $mongo->get('items', array('name' => 'eggs'))->fetchObject();
$this->assertEquals(20, $eggs->quantity);
$eggs = $mongo->get('items', array('name' => 'eggs'))->fetch();
$this->assertEquals('eggs', $eggs->name);
$this->assertInstanceOf('MongoId', $eggs->_id);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testRemove()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
@ -250,9 +222,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testInsert()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
@ -260,7 +230,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
$this->assertNotEmpty($mongo->getInsertId());
$this->assertEquals(2, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(0, $mongo->insert('items', array('name' => 'meat', 'weight' => 230)));
$this->assertEquals(230, $mongo->get('items', array('name' => 'meat'))->fetch()->weight);
$this->assertEquals(230, $mongo->find('items', array('name' => 'meat'))->fetch()->weight);
}
/**
@ -269,9 +239,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testBatchInsert()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$data = array(
array('name' => 'first object'),
@ -292,9 +260,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testGetInsertId()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(0, $mongo->getInsertId());
@ -316,15 +282,13 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testUpdate()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(1, $mongo->find('items', array('name' => 'bread'))->numRows());
$this->assertEquals(1, $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'fish')));
$this->assertEquals(2, $mongo->update('items', array('$set' => array('price' => 1)), array('name' => 'eggs')));
$fish = $mongo->get('items', array('name' => 'fish'))->fetch();
$fish = $mongo->find('items', array('name' => 'fish'))->fetch();
$this->assertEquals(200, $fish->price);
$this->assertEquals('today', $fish->date);
$this->assertEquals(0, $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'ball')));
@ -336,15 +300,14 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testUpsert()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$mongo->insert('items', array('name' => 'bread'));
$this->assertEquals(1, $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'ball'), true, true));
$this->assertEquals('today', $mongo->get('items', array('name' => 'ball'))->fetch()->date);
$this->assertInstanceOf('MongoId', $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'ball'), true, true));
$this->assertEquals('today', $mongo->find('items', array('name' => 'ball'))->fetch()->date);
$this->assertEquals(2, $mongo->update('items', array('$set' => array('price' => 200, 'date' => 'today')), array('name' => 'eggs'), true, true));
}
/**
@ -353,16 +316,14 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testFindAndModify()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(10, $mongo->get('items', array('name' => 'bread'))->fetch()->quantity);
$this->assertEquals(10, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
$result = $mongo->findAndModify('items', array('name' => 'bread'), array('$set' => array('quantity' => 20)));
$this->assertEquals(10, $result->fetch()->quantity);
$this->assertEquals(20, $mongo->get('items', array('name' => 'bread'))->fetch()->quantity);
$this->assertEquals(20, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
}
/**
@ -371,16 +332,14 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testFindAndModifyNoItem()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$this->assertEquals(10, $mongo->get('items', array('name' => 'bread'))->fetch()->quantity);
$this->assertEquals(10, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
$result = $mongo->findAndModify('items', array('name' => 'breading'), array('$set' => array('quantity' => 20)))->fetch();
$this->assertFalse($result);
$this->assertEquals(10, $mongo->get('items', array('name' => 'bread'))->fetch()->quantity);
$this->assertEquals(10, $mongo->find('items', array('name' => 'bread'))->fetch()->quantity);
}
/**
@ -389,9 +348,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testEvalCommand()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('$eval' => 'function() { return db.items.count();}'));
$this->assertEquals(5, $result->fetch());
@ -406,9 +363,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testEval()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('$eval' => 'function() {return true; }'));
$this->assertTrue($result->fetch());
@ -424,9 +379,7 @@ class MongoDriverTest extends PHPUnit_Framework_TestCase
*/
public function testCommand()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$mongo = new MongoDriver($this->conf);
$result = $mongo->command('items', array('distinct' => 'items', 'key' => 'name'));
$this->assertEquals(4, count($result->fetch(DB::FETCH_ASSOC)));

277
tests/model/MongoModelTest.php

@ -13,6 +13,7 @@
require_once dirname(__FILE__) . '/../../Registry.php';
require_once dirname(__FILE__) . '/../../Config.php';
require_once dirname(__FILE__) . '/../../cache/Cacher.php';
require_once dirname(__FILE__) . '/../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../model/DbExpr.php';
require_once dirname(__FILE__) . '/../../model/Db.php';
require_once dirname(__FILE__) . '/../../model/MongoDbCommand.php';
@ -27,8 +28,21 @@ require_once dirname(__FILE__) . '/../../model/MongoModel.php';
class MongoModelTest extends PHPUnit_Framework_TestCase
{
/**
* @var MongoModel
*/
private $model;
/**
* @var ReflectionMethod
*/
private $method_count;
/**
* @var ReflectionMethod
*/
private $method_fetch;
public function run(PHPUnit_Framework_TestResult $result = NULL)
{
$this->setPreserveGlobalState(false);
@ -47,6 +61,13 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
} else {
$this->model = new MongoMockModel();
}
$model = new ReflectionClass('MongoModel');
$this->method_count = $model->getMethod('count');
$this->method_count->setAccessible(true);
$this->method_fetch = $model->getMethod('fetch');
$this->method_fetch->setAccessible(true);
set_new_overload(array($this, 'newCallback'));
}
@ -62,140 +83,204 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
* @runInSeparateProcess
* @group Mongo
*/
public function testFind()
public function testFetch()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$result = $this->model->find();
$this->assertInstanceOf('MongoStatement', $result);
$this->assertEquals('milk', $result->limit(2)->order(array('name' => -1))->fetch()->name);
$this->assertEquals('fish', $result->fetch()->name);
$result = $this->model->find(array(), array('name'))->fetch();
Config::set('DEBUG', false);
$mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->once())
->method('set')
->will($this->returnValue(true));
$mock->expects($this->once())
->method('get')
->will($this->returnValue(false));
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => -1), 'limit' => 2), $mock);
$this->assertInstanceOf('ArrayObject', $result);
$this->assertEquals('milk', $result->name);
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => array('name')));
$this->assertSame('bread', $result->name);
$result = $this->method_fetch->invoke($this->model, array());
$this->setExpectedException('PHPUnit_Framework_Error');
$this->assertNull($result->price);
$this->assertNull($result->pounds);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testGet()
public function testFetchField()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$result = $this->model->find()->limit(1)->order(array('name' => 1));
$result = $result->fetch();
$this->assertEquals('bread', $result->name);
$id = $result->_id;
$this->assertEquals(10, $this->model->get($id)->quantity);
Config::set('DEBUG', false);
$mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->exactly(2))
->method('set')
->will($this->returnValue(true));
$mock->expects($this->exactly(2))
->method('get')
->will($this->returnValue(false));
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchField');
$method->setAccessible(true);
$result = $method->invoke($this->model, array('name' => 'milk'), array(), 'quantity', $mock);
$this->assertEquals(1, $result);
$result = $method->invoke($this->model, array(), array('skip' => 2), 'quantity', $mock);
$this->assertEquals($result, $this->method_fetch->invoke($this->model, array(), array('skip' => 2))->quantity);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testDelete()
public function testFetchAll()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$result = $this->model->find()->limit(1)->order(array('name' => 1));
$id = $result->fetch()->_id;
$this->assertEquals(1, $this->model->delete($id));
$this->assertFalse($this->model->find(array('name' => 'bread'))->fetch());
Config::set('DEBUG', false);
$mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->once())
->method('set')
->will($this->returnValue(true));
$mock->expects($this->once())
->method('get')
->will($this->returnValue(false));
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchAll');
$method->setAccessible(true);
$result = $method->invoke($this->model, array('name' => 'eggs'), array(), $mock);
$this->assertEquals(2, count($result));
$result = $method->invoke($this->model, array(), array('skip' => 2));
$this->assertEquals(3, count($result));
$this->assertEquals('fish', $result[0]->name);
$this->assertEquals('milk', $result[1]->name);
$this->assertEquals('eggs', $result[2]->name);
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testBatchInsert()
public function testFetchOrderParam()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$data = array(
array('name' => 'first object'),
array('name' => 'second object'),
array('name' => 'equal object'),
array('name' => 'equal object')
);
$this->model->batchInsert($data);
$this->assertEquals(1, $this->model->count(array('name' => 'first object')));
$this->assertEquals(2, $this->model->count(array('name' => 'equal object')));
$this->model->batchInsert(array());
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => 'name'));
$this->assertSame('bread', $result->name);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1, 'quantity' => -1), 'skip' => 1));
$this->assertSame(2.1, $result->price);
$this->setExpectedException('GeneralException', 'Wrong order parameter given to query.');
$this->method_fetch->invoke($this->model, array(), array('order' => 1));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testDeleteAll()
public function testFetchSkipLimitParam()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => 'name'));
$this->assertSame('bread', $result->name);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1, 'quantity' => -1), 'skip' => 1, 'limit' => 1));
$this->assertSame(2.1, $result->price);
$this->assertEquals(2, $this->model->count(array('name' => 'eggs')));
$this->assertEquals(0, $this->model->deleteAll(array('name' => 'eggs')));
$this->assertFalse($this->model->find(array('name' => 'eggs'))->fetch());
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchAll');
$method->setAccessible(true);
$this->assertCount(3, $method->invoke($this->model, array(), array('limit' => 3)));
$this->assertCount(2, $method->invoke($this->model, array(), array('skip' => 3)));
$this->assertCount(5, $method->invoke($this->model, array(), array()));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCount()
public function testFetchFieldsParam()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$this->assertEquals(5, $this->model->count());
$this->assertEquals(2, $this->model->count(array('name' => 'eggs')));
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => 'name'));
$this->assertTrue(!isset($result->quantity));
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => array('name', 'price')));
$this->assertTrue(!isset($result->quantity));
$result = $this->method_fetch->invoke($this->model, array(), array('fields' => array('name' => 1, 'price' => 1)));
$this->assertTrue(!isset($result->quantity));
$this->setExpectedException('GeneralException', 'Wrong fields parameter given to query.');
$this->method_fetch->invoke($this->model, array(), array('fields' => 1));
}
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testFetch()
public function testGet()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
$mock = $this->getMock('CacheKey', array('set', 'get'));
$mock->expects($this->exactly(3))
->method('set')
->will($this->returnValue(true));
$mock->expects($this->exactly(3))
->method('get')
->will($this->returnValue(false));
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchField');
$method->setAccessible(true);
$result = $method->invoke($this->model, array('name' => 'milk'), array(), 'quantity', $mock);
$this->assertEquals(1, $result);
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1)));
$this->assertEquals('bread', $result->name);
$id = $result->_id;
$this->assertEquals(10, $this->model->get($id)->quantity);
}
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetch');
$method->setAccessible(true);
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testDelete()
{
Config::set('DEBUG', false);
$result = $this->method_fetch->invoke($this->model, array(), array('order' => array('name' => 1)));
$id = $result->_id;
$this->assertEquals(1, $this->model->delete($id));
$this->assertFalse($this->method_fetch->invoke($this->model, array('name' => 'bread')));
}
$result = $method->invoke($this->model, array('name' => 'bread'), array(), $mock);
$this->assertEquals('bread', $result->name);
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testUpdate()
{
Config::set('DEBUG', false);
$this->model->insert(array('name' => 'testbread', 'price' => 3.2, 'quantity' => 10));
$result = $this->method_fetch->invoke($this->model, array('name' => 'testbread'));
$this->assertEquals(10, $result->quantity);
$this->model->update(array('$set' => array('quantity' => 3)), $result->_id);
$this->assertEquals(3, $this->model->get($result->_id)->quantity);
$this->model->update(array('$set' => array('quantity' => 13)), (string)$result->_id);
$this->assertEquals(13, $this->model->get($result->_id)->quantity);
}
$model = new ReflectionClass('MongoModel');
$method = $model->getMethod('fetchAll');
$method->setAccessible(true);
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testBatchInsert()
{
Config::set('DEBUG', false);
$data = array(
array('name' => 'first object'),
array('name' => 'second object'),
array('name' => 'equal object'),
array('name' => 'equal object')
);
$this->model->batchInsert($data);
$this->assertEquals(1, $this->method_count->invoke($this->model, array('name' => 'first object')));
$this->assertEquals(2, $this->method_count->invoke($this->model, array('name' => 'equal object')));
}
$result = $method->invoke($this->model, array('name' => 'eggs'), array(), $mock);
$this->assertEquals(2, count($result));
$this->assertEquals('eggs', $result[0]->name);
/**
* @runInSeparateProcess
* @group Mongo
*/
public function testCount()
{
Config::set('DEBUG', false);
$this->assertEquals(5, $this->method_count->invoke($this->model));
$this->assertEquals(2, $this->method_count->invoke($this->model, array('name' => 'eggs')));
}
/**
@ -204,9 +289,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/
public function testUseMongoId()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$this->assertAttributeEquals(true, 'useMongoId', $this->model);
}
@ -217,20 +300,18 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/
public function testId()
{
if (!defined('DEBUG')) {
define('DEBUG', false);
}
Config::set('DEBUG', false);
$class = new ReflectionClass('MongoModel');
$prop = $class->getProperty('useMongoId');
$prop->setAccessible(true);
$this->model->insert(array('_id' => 1, 'name' => 'testbread', 'price' => 3.2, 'quantity' => 10));
$this->model->insert(array('_id' => 2, 'name' => 'testbread', 'price' => 12, 'quantity' => 2));
$this->assertSame(2, $this->model->count(array('name' => 'testbread')));
$this->assertSame(2, $this->method_count->invoke($this->model, array('name' => 'testbread')));
$prop->setValue($this->model, false);
$this->model->delete(1);
$this->assertSame(1, $this->model->count(array('name' => 'testbread')));
$this->assertSame(1, $this->method_count->invoke($this->model, array('name' => 'testbread')));
}
/**
@ -239,19 +320,17 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
*/
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' => 12, 'quantity' => 2));
$this->assertSame(2, $this->model->count(array('name' => 'testbread')));
$id = $this->model->find(array('name' => 'testbread'))->limit(1)->fetch()->_id->__toString();
$this->assertSame(2, $this->method_count->invoke($this->model, array('name' => 'testbread')));
$id = $this->method_fetch->invoke($this->model, array('name' => 'testbread'))->_id->__toString();
$this->assertInternalType('string', $id);
$item = $this->model->get($id);
$this->assertSame('testbread', $item->name);
$this->model->delete($id);
$this->assertSame(1, $this->model->count(array('name' => 'testbread')));
$this->assertSame(1, $this->method_count->invoke($this->model, array('name' => 'testbread')));
}
public function tearDown()
@ -262,7 +341,7 @@ class MongoModelTest extends PHPUnit_Framework_TestCase
$db = $connection->selectDB($conf['database']);
$db->authenticate($conf['username'], $conf['password']);
$collection = 'mongomock';
$db->dropCollection($collection);
$db->selectCollection($collection)->remove(array());
}
protected function newCallback($className)

95
tests/model/MongoStatementTest.php

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

32
tests/model/MySQLiDriverTest.php

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

50
tests/model/MySQLiStatementTest.php

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

14
tests/redis/RedisDebugTest.php

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

7
tests/redis/RedisManagerTest.php

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

223
tests/util/profiler/ProfilerTest.php

@ -10,6 +10,8 @@
* Unit tests for CommandProfiler class
*/
require_once dirname(__FILE__) . '/../../../Registry.php';
require_once dirname(__FILE__) . '/../../../Config.php';
require_once dirname(__FILE__) . '/../../../exception/GeneralException.php';
require_once dirname(__FILE__) . '/../../../util/FirePHPCore-0.3.2/lib/FirePHPCore/fb.php';
require_once dirname(__FILE__) . '/../../../util/profiler/Profiler.php';
@ -36,10 +38,8 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/
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();
}
@ -48,9 +48,7 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/
public function testGetInstance()
{
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
$profiler = Profiler::getInstance();
$this->assertInstanceOf('Profiler', $profiler);
$this->assertSame($profiler, Profiler::getInstance());
@ -61,9 +59,7 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/
public function testProfilerCommand()
{
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
@ -75,9 +71,8 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/
public function testStartEndNoCommandProfiler()
{
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$profiler = Profiler::getInstance();
$profiler->start();
$result = $profiler->end('<body></body>');
@ -95,15 +90,15 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
*/
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);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$profiler->start();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$this->assertNotNull($cmdProfiler);
$result = $profiler->end('<body></body>');
$this->assertNotEquals('<body></body>', $result);
$this->assertStringEndsNotWith(']<br/></div></body>', $result);
@ -113,16 +108,146 @@ class ProfilerTest extends PHPUnit_Framework_TestCase
/**
* @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()
{
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);
$profiler = Profiler::getInstance();
$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()
{
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');
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
*/
public function testGetCLIWithNonDetails()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries not counted', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
*/
public function testGetCLIWithNonDetailsButExistingQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', false);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$cmdProfiler = $profiler->profilerCommand('command', 'type');
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries: 1', Profiler::getInstance()->getCli());
}
/**
* @runInSeparateProcess
*/
public function testGetCLIWithDetailsButNonQueries()
{
Config::set('PROFILER', true);
Config::set('PROFILER_DETAILS', true);
$this->getMock('CommandProfiler', array('getType', 'getCommand', 'getElapsed'), array(), 'CommandProfilerMock', false);
$profiler = Profiler::getInstance();
$result = $profiler->getCli();
$this->assertNotNull($result);
$this->assertContains('Queries: 0', Profiler::getInstance()->getCli());
}
public function tearDown()
{
// if (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;
// } else {
// echo PHP_EOL . __CLASS__ . ' ' . 'DEBUG NOT DEFINED' . PHP_EOL;

27
util/profiler/Profiler.php

@ -22,8 +22,8 @@ class Profiler
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()
{
$this->queries = array();
$this->start = microtime(true);
}
@ -80,8 +81,12 @@ class Profiler
$queriesTime += $query->getElapsed();
}
$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 .= '</div>';
return $html;
@ -99,7 +104,11 @@ class Profiler
$table[] = array($query->getType(), round($query->getElapsed() * 1000, 2), $query->getCommand());
$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()
@ -112,8 +121,12 @@ class Profiler
$queriesTime += $query->getElapsed();
}
$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;
return $html;
}
Loading…
Cancel
Save