Merge branch 'bugfix/user-preference-and-license-writer-4592-4603-4598'

fixes #4592
fixes #4603
fixes #4598
resolves #4625
This commit is contained in:
Eric Lippmann 2013-08-26 10:36:33 +02:00
commit 6219ebfbaa
9 changed files with 547 additions and 237 deletions

View File

@ -101,6 +101,7 @@ class PreferenceController extends BasePreferenceController
$this->view->exceptionMessage = $e->getMessage();
}
}
$this->view->form = $form;
}
}

View File

@ -1,4 +1,30 @@
#!/usr/bin/python
# {{{ICINGA_LICENSE_HEADER}}}
# This file is part of Icinga 2 Web.
#
# Icinga 2 Web - Head for multiple monitoring backends.
# Copyright (C) 2013 Icinga Development Team
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# @copyright 2013 Icinga Development Team <info@icinga.org>
# @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
# @author Icinga Development Team <info@icinga.org>
# {{{ICINGA_LICENSE_HEADER}}}
import sys
import logging
import optparse
@ -14,12 +40,17 @@ FILE_TYPE_CONFIG = {
'php': {'prefix': ' * ',
'firstComment': '/**',
'lastComment': ' */',
'linesFirst': 0,
'linesBefore': 0,
'linesAfter': 0},
'js': {'prefix': ' * ',
'firstComment': '/**',
'lastComment': ' */',
'linesFirst': 0,
'linesBefore': 0,
'linesAfter': 0},
'py': {'prefix': '# ',
'firstComment': None,
'lastComment': None,
'linesBefore': 0,
'linesAfter': 0}
}
@ -156,11 +187,17 @@ def get_license(type):
except(KeyError):
config = FILE_TYPE_CONFIG[type]
license_data = []
license_data.extend([''] * config['linesFirst'])
license_data.append(config['firstComment'])
license_data.extend([''] * config['linesBefore'])
if config['firstComment'] != None:
license_data.append(config['firstComment'])
for line in LICENSE_DATA.split('\n'):
license_data.append(config['prefix'] + line)
license_data.append(config['lastComment'])
if line:
license_data.append(config['prefix'] + line)
else:
# Whitespace is uselses in this case (#4603)
license_data.append(config['prefix'].rstrip())
if config['lastComment'] != None:
license_data.append(config['lastComment'])
license_data.extend([''] * config['linesAfter'])
__LICENSE_STORE[type] = '\n'.join(license_data)
__LICENSE_STORE[type] = __LICENSE_STORE[type] % REPLACE_TOKENS

View File

@ -1,6 +1,30 @@
#!/usr/bin/php
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
require_once dirname(__FILE__) . '/../library/Icinga/Application/Cli.php';

View File

@ -1,6 +1,30 @@
#!/usr/bin/php
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
set_include_path(

View File

@ -30,14 +30,14 @@ namespace Icinga\Application;
use \DateTimeZone;
use \Exception;
use Zend_Loader_Autoloader;
use Icinga\Application\Modules\Manager as ModuleManager;
use Icinga\Application\Platform;
use \Zend_Loader_Autoloader;
use \Icinga\Application\Modules\Manager as ModuleManager;
use \Icinga\Application\Platform;
use \Icinga\Application\Config;
use Icinga\Exception\ProgrammingError;
use \Icinga\Exception\ProgrammingError;
use \Icinga\Application\DbAdapterFactory;
use Icinga\Exception\ConfigurationError;
use Icinga\Util\DateTimeFactory;
use \Icinga\Exception\ConfigurationError;
use \Icinga\Util\DateTimeFactory;
/**
* This class bootstraps a thin Icinga application layer
@ -121,8 +121,6 @@ abstract class ApplicationBootstrap
/**
* Constructor
*
* The constructor is protected to avoid incorrect usage
*/
protected function __construct($configDir)
{
@ -212,8 +210,9 @@ abstract class ApplicationBootstrap
*
* Optional append sub directory
*
* @param null|string $subdir optional subdir
* @return string
* @param string $subdir optional subdir
*
* @return string
*/
public function getApplicationDir($subdir = null)
{
@ -222,8 +221,10 @@ abstract class ApplicationBootstrap
/**
* Getter for config dir
* @param string|null $subdir
* @return string
*
* @param string $subdir
*
* @return string
*/
public function getConfigDir($subdir = null)
{
@ -233,9 +234,10 @@ abstract class ApplicationBootstrap
/**
* Helper to glue directories together
*
* @param string $dir
* @param string|null $subdir
* @return string
* @param string $dir
* @param string $subdir
*
* @return string
*/
private function getDirWithSubDir($dir, $subdir = null)
{
@ -249,20 +251,52 @@ abstract class ApplicationBootstrap
/**
* Starting concrete bootstrap classes
*
* @param string $configDir
* @return ApplicationBootstrap
* @param string $configDir
*
* @return ApplicationBootstrap
*/
public static function start($configDir)
{
$class = get_called_class();
/** @var ApplicationBootstrap $obj */
$obj = new $class($configDir);
$obj->bootstrap();
return $obj;
$application = new $class($configDir);
$application->bootstrap();
if (Logger::hasErrorsOccurred()) {
$application->stopApplication(Logger::getQueue());
}
return $application;
}
/**
* Setup icinga auto loader
* Stop application and show information about errors
*
* @param array $errors
*/
public function stopApplication(array $errors = array())
{
$msg = "Application could not be started!\n\n";
if (count($errors)) {
foreach ($errors as $error) {
$msg .= $error[0]. "\n";
}
} else {
$msg .= "Further information about the error may have been written to the application's log file.\n"
. 'Please check it in order to analyse the problem.';
}
if ($this->isWeb()) {
$msg = nl2br($msg);
}
echo $msg;
die();
}
/**
* Setup Icinga auto loader
*
* @return self
*/
@ -357,8 +391,8 @@ abstract class ApplicationBootstrap
/**
* Setup default timezone
*
* @return self
* @throws ConfigurationError if the timezone in config.ini isn't valid
* @return self
* @throws ConfigurationError if the timezone in config.ini isn't valid
*/
protected function setupTimezone()
{

View File

@ -28,53 +28,74 @@
namespace Icinga\Application;
use Icinga\Exception\ConfigurationError;
use \Zend_Config;
use \Zend_Log;
use \Zend_Log_Filter_Priority;
use \Zend_Log_Writer_Abstract;
use \Zend_Log_Exception;
use \Icinga\Exception\ConfigurationError;
/**
* Class Logger
* @package Icinga\Application
* Singleton logger
*/
class Logger
final class Logger
{
/**
*
* Default log type
*/
const DEFAULT_LOG_TYPE = "stream";
/**
*
* Default log target
*/
const DEFAULT_LOG_TARGET = "./var/log/icinga.log";
/**
*
* Default debug target
*/
const DEFAULT_DEBUG_TARGET = "./var/log/icinga.debug.log";
/**
* Array of writers
*
* @var array
*/
private $writers = array();
/**
* @var null
* Instance of Zend_Log
*
* @var Zend_Log
*/
private $logger = null;
private $logger;
/**
* @var
* Singleton instance
*
* @var Logger
*/
private static $instance;
/**
* Queue of unwritten messages
*
* @var array
*/
private static $queue = array();
/**
* @param \Zend_Config $config
* Flag indicate that errors occurred in the past
*
* @var bool
*/
public function __construct(\Zend_Config $config)
private static $errorsOccurred = false;
/**
* Create a new logger object
*
* @param Zend_Config $config
*/
public function __construct(Zend_Config $config)
{
$this->overwrite($config);
}
@ -88,9 +109,13 @@ class Logger
}
/**
* @param \Zend_Config $config
* Overwrite config to initiated logger
*
* @param Zend_Config $config
*
* @return self
*/
public function overwrite(\Zend_Config $config)
public function overwrite(Zend_Config $config)
{
$this->clearLog();
try {
@ -98,82 +123,112 @@ class Logger
$this->setupDebugLog($config);
}
} catch (ConfigurationError $e) {
$this->warn("Could not create debug log: {$e->getMessage()}");
$this->warn('Could not create debug log: ' . $e->getMessage());
}
$this->setupLog($config);
$this->flushQueue();
return $this;
}
/**
* @param \Zend_Config $config
* Configure debug log
*
* @param Zend_Config $config
*/
private function setupDebugLog(\Zend_Config $config)
private function setupDebugLog(Zend_Config $config)
{
$type = $config->debug->get("type", self::DEFAULT_LOG_TYPE);
$target = $config->debug->get("target", self::DEFAULT_LOG_TARGET);
if ($target == self::DEFAULT_LOG_TARGET) {
$type == self::DEFAULT_LOG_TYPE;
$type = self::DEFAULT_LOG_TYPE;
}
$this->addWriter($type, $target, \Zend_Log::DEBUG);
$this->addWriter($type, $target, Zend_Log::DEBUG);
}
/**
* @param \Zend_Config $config
* Configure log
*
* @param Zend_Config $config
*/
private function setupLog(\Zend_Config $config)
private function setupLog(Zend_Config $config)
{
$type = $config->get("type", self::DEFAULT_LOG_TYPE);
$target = $config->get("target", self::DEFAULT_DEBUG_TARGET);
if ($target == self::DEFAULT_DEBUG_TARGET) {
$type == self::DEFAULT_LOG_TYPE;
$type = self::DEFAULT_LOG_TYPE;
}
$level = \Zend_Log::WARN;
$level = Zend_Log::WARN;
if ($config->get("verbose", 0) == 1) {
$level = \Zend_Log::INFO;
$level = Zend_Log::INFO;
}
$this->addWriter($type, $target, $level);
}
/**
* @param $type
* @param $target
* @param $priority
* @throws ConfigurationError
* Add writer to log instance
*
* @param string $type Type, e.g. stream
* @param string $target Target, e.g. filename
* @param int $priority Value of Zend::* constant
* @throws ConfigurationError
*/
private function addWriter($type, $target, $priority)
{
$type[0] = strtoupper($type[0]);
$writerClass = "\Zend_Log_Writer_" . $type;
if (!class_exists($writerClass)) {
throw new ConfigurationError("Could not create log: Unknown type " . $type);
$writerClass = "Zend_Log_Writer_" . $type;
if (!@class_exists($writerClass)) {
self::fatal(
'Could not add log writer of type "%s". Type does not exist.',
$type
);
return;
}
$writer = new $writerClass($target);
$writer->addFilter(new \Zend_Log_Filter_Priority($priority));
$this->logger->addWriter($writer);
$this->writers[] = $writer;
try {
/** @var Zend_Log_Writer_Abstract $writer */
$writer = new $writerClass($target);
$writer->addFilter(new Zend_Log_Filter_Priority($priority));
$this->logger->addWriter($writer);
$this->writers[] = $writer;
} catch (Zend_Log_Exception $e) {
self::fatal(
'Could not add log writer of type %s. An exception was thrown: %s',
$type,
$e->getMessage()
);
}
}
/**
* flushQueue
* Flush pending messages to writer
*/
public function flushQueue()
{
foreach (self::$queue as $msgTypePair) {
$this->logger->log($msgTypePair[0], $msgTypePair[1]);
try {
foreach (self::$queue as $msgTypePair) {
$this->logger->log($msgTypePair[0], $msgTypePair[1]);
}
} catch (Zend_Log_Exception $e) {
self::fatal(
'Could not flush logs to output. An exception was thrown: %s',
$e->getMessage()
);
}
}
/**
* @param array $argv
* @return string
* Format output message
*
* @param array $argv
*
* @return string
*/
public static function formatMessage(array $argv)
{
if (count($argv) == 1) {
$format = $argv[0];
} else {
@ -192,20 +247,23 @@ class Logger
}
/**
* clearLog
* Reset object configuration
*/
public function clearLog()
{
$this->logger = null;
$this->writers = array();
$this->logger = new \Zend_Log();
$this->logger = new Zend_Log();
}
/**
* @param \Zend_Config $config
* @return Logger
* Create an instance
*
* @param Zend_Config $config
*
* @return Logger
*/
public static function create(\Zend_Config $config)
public static function create(Zend_Config $config)
{
if (self::$instance) {
return self::$instance->overwrite($config);
@ -214,54 +272,60 @@ class Logger
}
/**
* debug
* Log message with severity debug
*/
public static function debug()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::DEBUG);
self::log(self::formatMessage(func_get_args()), Zend_Log::DEBUG);
}
/**
*
* Log message with severity warn
*/
public static function warn()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::WARN);
self::log(self::formatMessage(func_get_args()), Zend_Log::WARN);
}
/**
*
* Log message with severity info
*/
public static function info()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::INFO);
self::log(self::formatMessage(func_get_args()), Zend_Log::INFO);
}
/**
*
* Log message with severity error
*/
public static function error()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::ERR);
self::log(self::formatMessage(func_get_args()), Zend_Log::ERR);
}
/**
*
* Log message with severity fatal
*/
public static function fatal()
{
self::log(self::formatMessage(func_get_args()), \Zend_Log::EMERG);
self::log(self::formatMessage(func_get_args()), Zend_Log::EMERG);
}
/**
* @param $msg
* @param int $level
* Log message
*
* @param string $msg Message
* @param int $level Log level
*/
private static function log($msg, $level = \Zend_Log::INFO)
private static function log($msg, $level = Zend_Log::INFO)
{
$logger = self::$instance;
if (!$logger) {
if ($level < Zend_Log::WARN && self::$errorsOccurred === false) {
self::$errorsOccurred =true;
}
if (!$logger || !count($logger->getWriters())) {
array_push(self::$queue, array($msg, $level));
return;
}
@ -270,7 +334,29 @@ class Logger
}
/**
* Flag if messages > warning occurred
*
* @return bool
*/
public static function hasErrorsOccurred()
{
return self::$errorsOccurred;
}
/**
* Access the log queue
*
* The log queue holds messages that could not be written to output
*
* @return array
*/
public static function getQueue()
{
return self::$queue;
}
/**
* Reset object state
*/
public static function reset()
{

View File

@ -28,25 +28,27 @@
namespace Icinga\Application;
use Icinga\Authentication\Manager as AuthenticationManager;
use Icinga\Exception\ConfigurationError;
use Icinga\User\Preferences;
use Icinga\User;
use Icinga\Web\Request;
use Zend_Controller_Front;
use Zend_Layout;
use Zend_Config;
use Zend_Paginator;
use Zend_View_Helper_PaginationControl;
use Zend_Controller_Action_HelperBroker;
use Zend_Controller_Router_Route;
use Zend_Controller_Action_Helper_ViewRenderer;
use Icinga\Web\View;
use Icinga\User\Preferences\StoreFactory;
use Icinga\User\Preferences\SessionStore;
use \Exception;
use \Zend_Layout;
use \Zend_Config;
use \Zend_Paginator;
use \Zend_View_Helper_PaginationControl;
use \Zend_Controller_Action_HelperBroker;
use \Zend_Controller_Router_Route;
use \Zend_Controller_Action_Helper_ViewRenderer;
use \Zend_Controller_Front;
use \Icinga\Authentication\Manager as AuthenticationManager;
use \Icinga\Exception\ConfigurationError;
use \Icinga\User\Preferences;
use \Icinga\User\Preferences\LoadInterface;
use \Icinga\User;
use \Icinga\Web\Request;
use \Icinga\Web\View;
use \Icinga\User\Preferences\StoreFactory;
use \Icinga\User\Preferences\SessionStore;
/**
* Use this if you want to make use of Icinga funtionality in other web projects
* Use this if you want to make use of Icinga functionality in other web projects
*
* Usage example:
* <code>
@ -77,6 +79,13 @@ class Web extends ApplicationBootstrap
*/
private $request;
/**
* User object
*
* @var User
*/
private $user;
/**
* Identify web bootstrap
*
@ -95,6 +104,7 @@ class Web extends ApplicationBootstrap
->setupErrorHandling()
->setupTimezone()
->setupResourceFactories()
->setupUser()
->setupRequest()
->setupZendMvc()
->setupTranslation()
@ -207,9 +217,8 @@ class Web extends ApplicationBootstrap
/**
* Create user object and inject preference interface
*
* @return User
*
* @throws ConfigurationError
* @return self
* @throws ConfigurationError
*/
private function setupUser()
{
@ -221,43 +230,80 @@ class Web extends ApplicationBootstrap
);
if ($authenticationManager->isAuthenticated() === true) {
if ($this->getConfig()->preferences === null) {
throw new ConfigurationError('Preferences not configured in config.ini');
}
$user = $authenticationManager->getUser();
$this->getConfig()->preferences->configPath = Config::app()
->get('preferences', new Zend_Config(array()))
->get('configPath', $this->getConfigDir('preferences'));
$preferenceStore = StoreFactory::create(
$this->getConfig()->preferences,
$user
);
// Needed to update values in user session
$sessionStore = new SessionStore($authenticationManager->getSession());
// Performance: Do not ask provider if we've preferences
// stored in session
$initialPreferences = array();
$preferencesLoaded = false;
if (count($sessionStore->load())) {
$initialPreferences = $sessionStore->load();
} else {
$initialPreferences = $preferenceStore->load();
$sessionStore->writeAll($initialPreferences);
$preferencesLoaded = true;
}
$preferences = new Preferences($initialPreferences);
$preferences->attach($sessionStore);
$preferences->attach($preferenceStore);
if ($this->getConfig()->preferences !== null) {
if (is_dir($this->getConfig()->preferences->configPath) === false) {
Logger::error(
'Path for preferences not found (IniStore, "%s"). Using default one: "%s"',
$this->getConfig()->preferences->configPath,
$this->getConfigDir('preferences')
);
$this->getConfig()->preferences->configPath = $this->getConfigDir('preferences');
}
$preferenceStore = null;
try {
$preferenceStore = StoreFactory::create(
$this->getConfig()->preferences,
$user
);
$preferences->attach($preferenceStore);
} catch (Exception $e) {
Logger::fatal(
'Could not create create preferences provider. '
. 'An exception during bootstrap was thrown: %s',
$e->getMessage()
);
}
if ($preferencesLoaded === false && $preferenceStore instanceof LoadInterface) {
try {
$initialPreferences = $preferenceStore->load();
} catch (Exception $e) {
Logger::fatal(
'%s::%s: Could not load preferences from provider. '
. 'An exception during bootstrap was thrown: %s',
__CLASS__,
__FUNCTION__,
$e->getMessage()
);
}
$sessionStore->writeAll($initialPreferences);
}
} else {
Logger::error(
'Preferences are not configured. Refer to the documentation to setup a valid provider. '
. 'We will use session store only. Preferences are not persisted after logout'
);
}
$user->setPreferences($preferences);
return $user;
$this->user = $user;
}
return $this;
}
/**
@ -269,9 +315,8 @@ class Web extends ApplicationBootstrap
{
$this->request = new Request();
$user = $this->setupUser();
if ($user instanceof User) {
$this->request->setUser($user);
if ($this->user instanceof User) {
$this->request->setUser($this->user);
}
return $this;

View File

@ -111,7 +111,9 @@ class Manager
if (isset($options["groupBackendClass"])) {
$this->groupBackend = $options["groupBackendClass"];
} else {
$this->groupBackend = $this->initBestBackend(self::BACKEND_TYPE_GROUP, $config);
// @TODO(mh): Re-enable when ready (#4624)
// Deactivated, logging error messages breaks bootstrap
// $this->groupBackend = $this->initBestBackend(self::BACKEND_TYPE_GROUP, $config);
}
if (!isset($options["sessionClass"])) {

View File

@ -1,24 +1,49 @@
<?php
// {{{ICINGA_LICENSE_HEADER}}}
/**
* This file is part of Icinga 2 Web.
*
* Icinga 2 Web - Head for multiple monitoring backends.
* Copyright (C) 2013 Icinga Development Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* @copyright 2013 Icinga Development Team <info@icinga.org>
* @license http://www.gnu.org/licenses/gpl-2.0.txt GPL, version 2
* @author Icinga Development Team <info@icinga.org>
*/
// {{{ICINGA_LICENSE_HEADER}}}
namespace Tests\Icinga\Application;
require_once("Zend/Log.php");
require_once("Zend/Config.php");
require_once("Zend/Log/Writer/Mock.php");
require_once("Zend/Log/Writer/Null.php");
require_once("Zend/Log/Filter/Priority.php");
require_once 'Zend/Log.php';
require_once 'Zend/Config.php';
require_once 'Zend/Log/Writer/Mock.php';
require_once 'Zend/Log/Writer/Null.php';
require_once 'Zend/Log/Filter/Priority.php';
require_once("../../library/Icinga/Application/Logger.php");
require_once("../../library/Icinga/Exception/ConfigurationError.php");
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Application/Logger.php');
require_once realpath(__DIR__ . '/../../../../../library/Icinga/Exception/ConfigurationError.php');
use \Icinga\Application\Logger;
use \Icinga\Application\Logger as Logger;
/**
*
* Test class for Logger
* Created Thu, 07 Feb 2013 10:07:13 +0000
*
**/
* Test class for Logger
*
* @backupStaticAttributes enabled
**/
class LoggerTest extends \PHPUnit_Framework_TestCase
{
private $timeZone;
@ -26,134 +51,166 @@ class LoggerTest extends \PHPUnit_Framework_TestCase
protected function setUp()
{
date_default_timezone_set('GMT');
Logger::reset();
}
public function testOverwrite() {
$cfg1 = new \Zend_Config(array(
"debug" => array("enable" => 0),
"type" => "mock",
"target" => "target2"
));
$cfg2 = new \Zend_Config(array(
"debug" => array(
"enable" => 1,
"type"=>"mock",
"target"=>"target3"
),
"type" => "mock",
"target" => "target4"
));
public function testOverwrite()
{
$cfg1 = new \Zend_Config(
array(
'debug' => array('enable' => 0),
'type' => 'mock',
'target' => 'target2'
)
);
$cfg2 = new \Zend_Config(
array(
'debug' => array(
'enable' => 1,
'type'=>'mock',
'target'=>'target3'
),
'type' => 'mock',
'target' => 'target4'
)
);
$logger = new Logger($cfg1);
$writers = $logger->getWriters();
$this->assertEquals(1,count($writers));
$this->assertEquals(1, count($writers));
$logger = new Logger($cfg1);
$writers2 = $logger->getWriters();
$this->assertEquals(1,count($writers));
$this->assertNotEquals($writers[0],$writers2[0]);
$this->assertEquals(1, count($writers));
$this->assertNotEquals($writers[0], $writers2[0]);
$logger = new Logger($cfg2);
$writers2 = $logger->getWriters();
$this->assertEquals(2,count($writers2));
$this->assertEquals(2, count($writers2));
}
public function testFormatMessage()
{
$message = Logger::formatMessage(array('Testmessage'));
$this->assertEquals('Testmessage', $message);
$message = Logger::formatMessage(array('Testmessage %s %s', 'test1', 'test2'));
$this->assertEquals('Testmessage test1 test2', $message);
$message = Logger::formatMessage(array('Testmessage %s', array('test1', 'test2')));
$this->assertEquals('Testmessage '.json_encode(array('test1', 'test2')), $message);
}
public function testFormatMessage() {
$message = Logger::formatMessage(array("Testmessage"));
$this->assertEquals("Testmessage",$message);
public function testLoggingOutput()
{
$cfg1 = new \Zend_Config(
array(
'debug' => array('enable' => 0),
'type' => 'mock',
'target' => 'target2'
)
);
$message = Logger::formatMessage(array("Testmessage %s %s","test1","test2"));
$this->assertEquals("Testmessage test1 test2",$message);
$message = Logger::formatMessage(array("Testmessage %s",array("test1","test2")));
$this->assertEquals("Testmessage ".json_encode(array("test1","test2")),$message);
}
public function testLoggingOutput() {
$cfg1 = new \Zend_Config(array(
"debug" => array("enable" => 0),
"type" => "mock",
"target" => "target2"
));
Logger::reset();
$logger = Logger::create($cfg1);
$writers = $logger->getWriters();
$logger->warn("Warning");
$logger->error("Error");
$logger->info("Info");
$logger->debug("Debug");
$logger->warn('Warning');
$logger->error('Error');
$logger->info('Info');
$logger->debug('Debug');
$writer = $writers[0];
$this->assertEquals(2,count($writer->events));
$this->assertEquals($writer->events[0]["message"],"Warning");
$this->assertEquals($writer->events[1]["message"],"Error");
Logger::reset();
$this->assertEquals(2, count($writer->events));
$this->assertEquals($writer->events[0]['message'], 'Warning');
$this->assertEquals($writer->events[1]['message'], 'Error');
}
public function testLogQueuing() {
$cfg1 = new \Zend_Config(array(
"debug" => array("enable" => 0),
"type" => "mock",
"target" => "target2"
));
public function testLogQueuing()
{
$cfg1 = new \Zend_Config(
array(
'debug' => array('enable' => 0),
'type' => 'mock',
'target' => 'target2'
)
);
Logger::reset();
Logger::warn("Warning");
Logger::error("Error");
Logger::info("Info");
Logger::debug("Debug");
Logger::warn('Warning');
Logger::error('Error');
Logger::info('Info');
Logger::debug('Debug');
$logger = Logger::create($cfg1);
$writers = $logger->getWriters();
$writer = $writers[0];
$this->assertEquals(2,count($writer->events));
$this->assertEquals($writer->events[0]["message"],"Warning");
$this->assertEquals($writer->events[1]["message"],"Error");
Logger::reset();
$this->assertEquals(2, count($writer->events));
$this->assertEquals($writer->events[0]['message'], 'Warning');
$this->assertEquals($writer->events[1]['message'], 'Error');
}
public function testDebugLogErrorCatching()
{
$cfg1 = new \Zend_Config(array(
"debug" => array(
"enable" => 1,
"type" => 'Invalid',
"target" => "..."
),
"type" => "mock",
"target" => "target2"
));
Logger::reset();
$cfg1 = new \Zend_Config(
array(
'debug' => array(
'enable' => 1,
'type' => 'Invalid',
'target' => '...'
),
'type' => 'mock',
'target' => 'target2'
)
);
$logger = Logger::create($cfg1);
$writers = $logger->getWriters();
$this->assertEquals(1,count($writers));
$this->assertEquals(1,count($writers[0]->events));
$exceptionStart = "Could not create debug log:";
$this->assertEquals(substr($writers[0]->events[0]["message"],0,strlen($exceptionStart)),$exceptionStart);
Logger::reset();
$this->assertEquals(1, count($writers));
$this->assertEquals(1, count($writers[0]->events));
$this->assertEquals(
'Could not add log writer of type "Invalid". Type does not exist.',
$writers[0]->events[0]['message']
);
}
/**
* @expectedException \Icinga\Exception\ConfigurationError
*/
public function testGeneralLogException() {
$cfg1 = new \Zend_Config(array(
"debug" => array(
"enable" => 0,
"type" => 'Invalid',
"target" => "..."
),
"type" => "invalid",
"target" => "target2"
));
Logger::reset();
public function testNotLoggedMessagesQueue()
{
$cfg1 = new \Zend_Config(
array(
'debug' => array(
'enable' => 0,
'type' => 'Invalid',
'target' => '...'
),
'type' => 'invalid',
'target' => 'target2'
)
);
$logger = Logger::create($cfg1);
Logger::reset();
}
$this->assertTrue(Logger::hasErrorsOccurred());
$queue = Logger::getQueue();
$this->assertCount(2, $queue);
$this->assertSame(
'Could not add log writer of type "Invalid". Type does not exist.',
$queue[0][0],
'Log message of an invalid writer'
);
$this->assertSame(0, $queue[0][1], 'Log level "fatal"');
$this->assertSame(
'Could not flush logs to output. An exception was thrown: No writers were added',
$queue[1][0],
'Log message that no writer was added to logger'
);
$this->assertSame(0, $queue[1][1], 'Log level "fatal"');
}
}