Implemented Unit tests for Logger class.

Changed a few other classes since some unused functionality was removed.
This commit is contained in:
Abel Hoogeveen 2016-07-23 16:32:11 +02:00
parent 1106f49f35
commit 23f56b524a
6 changed files with 289 additions and 153 deletions

View File

@ -34,8 +34,6 @@
namespace FuzeWorks;
use FuzeWorks\Exception\LayoutException;
use Tracy\Debugger;
/**
* Logger Class.
@ -49,34 +47,6 @@ use Tracy\Debugger;
*/
class Logger {
/**
* Log entries which display information entries.
*
* @var array
*/
public static $infoErrors = array();
/**
* Log entries which display debugging entries.
*
* @var array
*/
public static $debugErrors = array();
/**
* Log entries which display critical error entries.
*
* @var array
*/
public static $criticalErrors = array();
/**
* Log entries which display warning entries.
*
* @var array
*/
public static $warningErrors = array();
/**
* All log entries, unsorted.
*
@ -132,11 +102,13 @@ class Logger {
* Registers the error and exception handler, when required to do so by configuration
*/
public function __construct() {
// Register the error handler
// Register the error handler, Untestable
// @codeCoverageIgnoreStart
if (Config::get('error')->error_reporting == true && self::$useTracy === false) {
set_error_handler(array('\FuzeWorks\Logger', 'errorHandler'), E_ALL);
set_Exception_handler(array('\FuzeWorks\Logger', 'exceptionHandler'));
}
// @codeCoverageIgnoreEnd
error_reporting(false);
@ -147,13 +119,15 @@ class Logger {
if (self::$useTracy)
{
LoggerTracy::register();
LoggerTracyBridge::register();
}
}
/**
* Function to be run upon FuzeWorks shutdown.
*
* @codeCoverageIgnore
*
* Logs data to screen when requested to do so
*/
public static function shutdown() {
@ -174,6 +148,8 @@ class Logger {
/**
* Function to be run upon FuzeWorks shutdown.
*
* @codeCoverageIgnore
*
* Logs a fatal error and outputs the log when configured or requested to do so
*/
public static function shutdownError()
@ -194,10 +170,7 @@ class Logger {
// Log it!
Factory::getInstance()->output->set_output('');
self::errorHandler($errno, $errstr, $errfile, $errline);
if (self::$useTracy === false)
{
self::http_error('500');
}
self::http_error('500');
}
}
@ -237,16 +210,16 @@ class Logger {
$context = $exception->getTraceAsString();
self::logError('Exception thrown: ' . $message . ' | ' . $code, null, $file, $line);
// And return a 500 because this error was fatal
if (self::$useTracy === false)
{
self::http_error('500');
}
// And return a 500 because this error was fatal
self::http_error('500');
}
/**
* Set the template that FuzeWorks should use to parse debug logs
*
* @codeCoverageIgnore
*
* @var string Name of the template file
*/
public static function setLoggerTemplate($templateName)
@ -256,8 +229,7 @@ class Logger {
/**
* Output the entire log to the screen. Used for debugging problems with your code.
*
* @return string Output of the log
* @codeCoverageIgnore
*/
public static function logToScreen() {
// Send a screenLogEvent, allows for new screen log designs
@ -266,16 +238,20 @@ class Logger {
return false;
}
Layout::reset();
Layout::assign('Logs', self::$Logs);
Layout::view(self::$logger_template, Core::$coreDir . DS . 'Views', true);
$logs = self::$Logs;
require(dirname(__DIR__) . '/views/view.' . self::$logger_template . '.php');
}
/**
* Output the entire log to a file. Used for debugging problems with your code.
* @codeCoverageIgnore
*/
public static function logToFile()
{
Layout::reset();
Layout::assign('Logs', self::$Logs);
$contents = Layout::get('logger_cli', Core::$coreDir . DS . 'Views');
ob_start(function () {});
$logs = self::$Logs;
require(dirname(__DIR__) . '/views/view.logger_cli.php');
$contents = ob_get_clean();
$file = Core::$logDir .DS. 'Logs'.DS.'log_latest.php';
if (is_writable($file))
{
@ -283,28 +259,6 @@ class Logger {
}
}
/**
* Backtrace a problem to the source using the trace of an Exception.
*
* @return string HTML backtrace
*/
public static function backtrace() {
$e = new Exception();
$trace = explode("\n", $e->getTraceAsString());
// reverse array to make steps line up chronologically
$trace = array_reverse($trace);
array_shift($trace); // remove {main}
array_pop($trace); // remove call to this method
$length = count($trace);
$result = array();
for ($i = 0; $i < $length; ++$i) {
$result[] = ($i + 1) . ')' . substr($trace[$i], strpos($trace[$i], ' ')); // replace '#someNum' with '$i)', set the right ordering
}
return "<b>BACKTRACE: <br/>\t" . implode('<br/>', $result) . '</b>';
}
/* =========================================LOGGING METHODS============================================================== */
/**
@ -317,7 +271,14 @@ class Logger {
* @return void
*/
public static function mark($name) {
self::$markPoints[$name] = microtime(TRUE);
$LOG = array('type' => 'BMARK',
'message' => (!is_null($name) ? $name : ''),
'logFile' => '',
'logLine' => '',
'context' => '',
'runtime' => round(self::getRelativeTime(), 4),);
self::$Logs[] = $LOG;
}
/**
@ -348,14 +309,7 @@ class Logger {
'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4),);
self::$infoErrors[] = $LOG;
self::$Logs[] = $LOG;
// Use Tracy when we can
if (self::$useTracy === true)
{
Debugger::log($msg, 'info');
}
}
/**
@ -374,14 +328,7 @@ class Logger {
'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4),);
self::$debugErrors[] = $LOG;
self::$Logs[] = $LOG;
// Use Tracy when we can
if (self::$useTracy === true)
{
Debugger::log($msg, 'debug');
}
}
/**
@ -400,14 +347,7 @@ class Logger {
'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4),);
self::$criticalErrors[] = $LOG;
self::$Logs[] = $LOG;
// Use Tracy when we can
if (self::$useTracy === true)
{
Debugger::log($msg, 'error');
}
}
/**
@ -426,14 +366,7 @@ class Logger {
'context' => (!is_null($mod) ? $mod : ''),
'runtime' => round(self::getRelativeTime(), 4),);
self::$warningErrors[] = $LOG;
self::$Logs[] = $LOG;
// Use Tracy when we can
if (self::$useTracy === true)
{
Debugger::log($msg, 'warning');
}
}
/**
@ -453,12 +386,6 @@ class Logger {
'runtime' => round(self::getRelativeTime(), 4),);
self::$Logs[] = $LOG;
// Use Tracy when we can
if (self::$useTracy === true)
{
Debugger::log($msg, 'info');
}
}
/**
@ -607,6 +534,14 @@ class Logger {
self::$print_to_screen = false;
}
/**
* Returns whether screen logging is enabled.
*/
public static function isEnabled()
{
return self::$print_to_screen;
}
/**
* Get the relative time since the framework started.
*
@ -620,39 +555,4 @@ class Logger {
return $time;
}
/**
* Elapsed time
*
* Calculates the time difference between two marked points.
*
* If the first parameter is empty this function instead returns the
* {elapsed_time} pseudo-variable. This permits the full system
* execution time to be shown in a template. The output class will
* swap the real value for this variable.
*
* @param string $point1 A particular marked point
* @param string $point2 A particular marked point
* @param int $decimals Number of decimal places
*
* @return string Calculated elapsed time on success,
* an '{elapsed_string}' if $point1 is empty
* or an empty string if $point1 is not found.
*/
public static function elapsedTime($point1 = '', $point2 = '', $decimals = 4) {
if ($point1 === '') {
return '{elapsed_time}';
}
if (!isset(self::$markPoints[$point1])) {
return '';
}
if (!isset(self::$markPoints[$point2])) {
self::$markPoints[$point2] = microtime(TRUE);
}
return number_format(self::$markPoints[$point2] - self::$markPoints[$point1], $decimals);
}
}
}

View File

@ -35,7 +35,7 @@ use Tracy\IBarPanel;
use Tracy\Debugger;
/**
* LoggerTracy Class.
* LoggerTracyBridge Class.
*
* This class provides a bridge between FuzeWorks\Logger and Tracy Debugging tool.
*
@ -45,7 +45,7 @@ use Tracy\Debugger;
* @author Abel Hoogeveen <abel@techfuze.net>
* @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
*/
class LoggerTracy implements IBarPanel {
class LoggerTracyBridge implements IBarPanel {
/**
* Register the bar and register the event which will block the screen log

View File

@ -435,15 +435,10 @@ class Output {
// --------------------------------------------------------------------
// Parse out the elapsed time and memory usage,
// then swap the pseudo-variables with the data
$elapsed = Logger::elapsedTime('total_execution_time_start', 'total_execution_time_end');
if ($this->parse_exec_vars === TRUE)
{
$memory = round(memory_get_usage() / 1024 / 1024, 2).'MB';
$output = str_replace(array('{elapsed_time}', '{memory_usage}'), array($elapsed, $memory), $output);
$output = str_replace(array('{memory_usage}'), array($memory), $output);
}
// --------------------------------------------------------------------
@ -488,7 +483,6 @@ class Output {
echo $output;
Logger::log('Final output sent to browser');
Logger::logDebug('Total execution time: '.$elapsed);
return;
}
@ -519,7 +513,6 @@ class Output {
echo $output;
Logger::log('Output sent to browser');
Logger::logDebug('Total execution time: '.$elapsed);
}
// --------------------------------------------------------------------

View File

@ -2,7 +2,7 @@
$string = '<h3>FuzeWorks debug log</h3>';
$layer = 0;
foreach ($this->assigned_variables['Logs'] as $log) {
foreach ($logs as $log) {
if ($log['type'] == 'LEVEL_START') {
++$layer;
$color = 255 - ($layer * 25);

242
tests/core_loggerTest.php Normal file
View File

@ -0,0 +1,242 @@
<?php
/**
* FuzeWorks.
*
* The FuzeWorks MVC PHP FrameWork
*
* Copyright (C) 2015 TechFuze
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
* @author TechFuze
* @copyright Copyright (c) 2013 - 2016, Techfuze. (http://techfuze.net)
* @copyright Copyright (c) 1996 - 2015, Free Software Foundation, Inc. (http://www.fsf.org/)
* @license http://opensource.org/licenses/GPL-3.0 GPLv3 License
*
* @link http://fuzeworks.techfuze.net
* @since Version 0.0.1
*
* @version Version 0.0.1
*/
use FuzeWorks\Config;
use FuzeWorks\Logger;
use FuzeWorks\Exception\LoggerException;
/**
* Class ModelTest.
*
* Will test the FuzeWorks Model System.
*/
class loggerTest extends CoreTestAbstract
{
protected $logger;
public function setUp()
{
Config::get('error')->error_reporting = false;
Logger::$Logs = array();
}
public function testGetLogger()
{
$this->assertInstanceOf('FuzeWorks\Logger', new Logger);
}
public function testErrorHandler()
{
Logger::errorHandler(E_ERROR, 'Example error', __FILE__, 1, 'data');
$this->assertCount(1, Logger::$Logs);
$log = Logger::$Logs[0];
$this->assertEquals('ERROR', $log['type']);
$this->assertEquals('Example error', $log['message']);
$this->assertEquals(__FILE__, $log['logFile']);
$this->assertEquals(1, $log['logLine']);
$this->assertEquals('data', $log['context']);
}
/**
* @depends testErrorHandler
*/
public function testErrorHandlerTypes()
{
$types = array(
E_ERROR => 'ERROR',
E_WARNING => 'WARNING',
E_PARSE => 'ERROR',
E_NOTICE => 'WARNING',
E_CORE_ERROR => 'ERROR',
E_CORE_WARNING => 'WARNING',
E_COMPILE_ERROR => 'ERROR',
E_COMPILE_WARNING => 'WARNING',
E_USER_ERROR => 'ERROR',
E_USER_WARNING => 'WARNING',
E_USER_NOTICE => 'WARNING',
E_USER_DEPRECATED => 'WARNING',
E_STRICT => 'ERROR',
E_RECOVERABLE_ERROR => 'ERROR',
E_DEPRECATED => 'WARNING',
'UNKNOWN' => 'Unknown error: UNKNOWN'
);
foreach ($types as $errorType => $output) {
// Clear the log entries
Logger::$Logs = array();
// Log the error
Logger::errorHandler($errorType, 'Log message');
// Fetch the error
$log = Logger::$Logs[0];
// Check the type
$this->assertEquals($output, $log['type']);
}
}
public function testExceptionHandler()
{
// Create the exception
$exception = new LoggerException();
// Prepare output buffering
ob_start(function () {});
// Log the exception
Logger::exceptionHandler($exception);
// Check the output
$this->assertEquals('<h1>500</h1><h3>Internal Server Error</h3>', ob_get_clean());
// Check the logs
$log = Logger::$Logs[0];
}
public function testLog()
{
// Log the message
Logger::log('Log message', 'core_loggerTest', __FILE__, 1);
// Fetch the message
$log = Logger::$Logs[0];
// Assert data
$this->assertEquals('INFO', $log['type']);
$this->assertEquals('Log message', $log['message']);
$this->assertEquals(__FILE__, $log['logFile']);
$this->assertEquals(1, $log['logLine']);
$this->assertEquals('core_loggerTest', $log['context']);
}
/**
* @depends testLog
*/
public function testLogTypes()
{
$types = array(
'newLevel' => 'LEVEL_START',
'stopLevel' => 'LEVEL_STOP',
'logError' => 'ERROR',
'logWarning' => 'WARNING',
'logDebug' => 'DEBUG',
'mark' => 'BMARK'
);
foreach ($types as $method => $returnValue) {
// Clear the log entries
Logger::$Logs = array();
// Log the entry
Logger::{$method}('Log message', 'core_loggerTest', __FILE__, 1);
// Fetch the entry
$log = Logger::$Logs[0];
// Assert the entry
$this->assertEquals($returnValue, $log['type']);
}
}
public function testHttpError()
{
$http_codes = array(
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended',
511 => 'Network Authentication Required',
);
// Test all error codes
foreach ($http_codes as $code => $description) {
// Prepare output buffering
ob_start(function () {});
// Fire the error
Logger::http_error($code);
// Check the output
$this->assertEquals('<h1>'.$code.'</h1><h3>'.$description.'</h3>', ob_get_clean());
}
// Test when not viewing
Logger::http_error(404, false);
}
public function testEnable()
{
Logger::enable();
$this->assertTrue(Logger::isEnabled());
}
public function testDisable()
{
Logger::disable();
$this->assertFalse(Logger::isEnabled());
}
public function tearDown()
{
Logger::$Logs = array();
}
}

View File

@ -32,6 +32,7 @@
<directory suffix=".php">../</directory>
<exclude>
<directory suffix=".php">../vendor/</directory>
<directory suffix=".php">../tests/</directory>
</exclude>
</whitelist>
</filter>