Skip to content

Commit

Permalink
add some tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lekoala committed Jan 4, 2017
1 parent d379f79 commit 3af8f46
Show file tree
Hide file tree
Showing 3 changed files with 154 additions and 34 deletions.
44 changes: 25 additions & 19 deletions _config.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,19 @@
* Helpful debugging helper. Pass as many arguments as you need.
* Keep the call on one line to be able to output arguments names
* Without arguments, it will display all object instances in the backtrace
*
*
* @return void
*/
function d()
{
$args = func_get_args();

// Prevent exit in test session
$isTest = !empty($args) && $args[0] instanceof SapphireTest;

// Clean buffer that may be in the way
if (ob_get_contents()) ob_end_clean();
if (!$isTest && ob_get_contents())
ob_end_clean();

$bt = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT);

Expand All @@ -26,10 +32,10 @@ function d()

// Caller
$caller_function = isset($bt[1]['function']) ? $bt[1]['function'] : null;
$caller_class = isset($bt[1]['class']) ? $bt[1]['class'] : null;
$caller = $caller_function;
$caller_class = isset($bt[1]['class']) ? $bt[1]['class'] : null;
$caller = $caller_function;
if ($caller_class) {
$caller = $caller_class.'::'.$caller_function;
$caller = $caller_class . '::' . $caller_function;
}

// Probably best to avoid using this in live websites...
Expand All @@ -39,15 +45,14 @@ function d()
}

// Arguments passed to the function are stored in matches
$src = file($file);
$src = file($file);
$src_line = $src[$line - 1];
preg_match("/d\((.+)\)/", $src_line, $matches);

// Find all arguments, ignore variables within parenthesis
$arguments_name = [];
if (!empty($matches[1])) {
$arguments_name = array_map('trim',
preg_split("/(?![^(]*\)),/", $matches[1]));
$arguments_name = array_map('trim', preg_split("/(?![^(]*\)),/", $matches[1]));
}

$isAjax = Director::is_ajax();
Expand Down Expand Up @@ -78,16 +83,14 @@ function d()
$print("$file:$line ($caller)");

// Display data in a friendly manner
$args = func_get_args();
if (empty($args)) {
$arguments_name = [];
foreach ($bt as $trace) {
if (!empty($trace['object'])) {
$line = isset($trace['line']) ? $trace['line'] : 0;
$function = isset($trace['function']) ? $trace['function']
: 'unknown function';
$arguments_name[] = $function.':'.$line;
$args[] = $trace['object'];
$line = isset($trace['line']) ? $trace['line'] : 0;
$function = isset($trace['function']) ? $trace['function'] : 'unknown function';
$arguments_name[] = $function . ':' . $line;
$args[] = $trace['object'];
}
}
}
Expand All @@ -96,9 +99,9 @@ function d()
foreach ($args as $arg) {
// Echo name of the variable
$len = 20;
$varname = isset($arguments_name[$i]) ? $arguments_name[$i]: null;
if($varname) {
$print('Value for: '.$varname);
$varname = isset($arguments_name[$i]) ? $arguments_name[$i] : null;
if ($varname) {
$print('Value for: ' . $varname);
$len = strlen($varname);
}
// For ajax requests, a good old print_r is much better
Expand All @@ -109,15 +112,18 @@ function d()
$print(str_repeat('-', $len));
}
} else {
if ($varname && is_string($arg) && strpos($varname,'sql') !== false) {
if ($varname && is_string($arg) && strpos($varname, 'sql') !== false) {
echo JdornSqlFormatter::format($arg);
} else {
dump($arg);
}
}
$i++;
}
exit();

if (!$isTest) {
exit();
}
}
}

Expand Down
56 changes: 41 additions & 15 deletions code/DebugBar.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
class DebugBar extends Object
{

/**
* @var DebugBar\StandardDebugBar
*/
Expand Down Expand Up @@ -39,21 +40,41 @@ public static function getDebugBar()
return self::$debugbar;
}

if (!Director::isDev() || self::IsDisabled() || self::VendorNotInstalled()
|| self::NotLocalIp() || Director::is_cli() || self::IsDevUrl() || (self::IsAdminUrl()
&& !self::config()->enabled_in_admin)
if (!Director::isDev() || self::IsDisabled() || self::VendorNotInstalled() || self::NotLocalIp() || Director::is_cli() || self::IsDevUrl() || (self::IsAdminUrl() && !self::config()->enabled_in_admin)
) {
self::$debugbar = false; // No need to check again
return;
}

self::initDebugBar();

if (!self::$debugbar) {
throw new Exception("Failed to initialize the DebugBar");
}

return self::$debugbar;
}

/**
* Init the debugbar instance
*
* @global array $databaseConfig
* @return DebugBar\StandardDebugBar
*/
public static function initDebugBar()
{
// Prevent multiple inits
if (self::$debugbar) {
return self::$debugbar;
}

// Add the controller extension programmaticaly because it might not be added properly through yml
Controller::add_extension('DebugBarControllerExtension');

// Add a custom logger that logs everything under the Messages tab
SS_Log::add_writer(new DebugBarLogWriter(), SS_Log::DEBUG, '<=');

self::$debugbar = $debugbar = new DebugBar\DebugBar();
self::$debugbar = $debugbar = new DebugBar\DebugBar();

if (isset($_REQUEST['showqueries'])) {
self::setShowQueries(true);
Expand All @@ -79,8 +100,8 @@ public static function getDebugBar()
$connector = DB::get_connector();
if (!self::config()->force_proxy && $connector instanceof PDOConnector) {
// Use a little bit of magic to replace the pdo instance
$refObject = new ReflectionObject($connector);
$refProperty = $refObject->getProperty('pdoConnection');
$refObject = new ReflectionObject($connector);
$refProperty = $refObject->getProperty('pdoConnection');
$refProperty->setAccessible(true);
$traceablePdo = new DebugBar\DataCollector\PDO\TraceablePDO($refProperty->getValue($connector));
$refProperty->setValue($connector, $traceablePdo);
Expand All @@ -107,12 +128,12 @@ public static function getDebugBar()
$debugbar->addCollector(new DebugBarSilverStripeCollector());

if (self::config()->enable_storage) {
$debugbar->setStorage(new DebugBar\Storage\FileStorage(TEMP_FOLDER.'/debugbar'));
$debugbar->setStorage(new DebugBar\Storage\FileStorage(TEMP_FOLDER . '/debugbar'));
}

// Since we buffer everything, why not enable all dev options ?
if (self::config()->auto_debug) {
$_REQUEST['debug'] = true;
$_REQUEST['debug'] = true;
$_REQUEST['debug_request'] = true;
}

Expand All @@ -124,6 +145,11 @@ public static function getDebugBar()
return $debugbar;
}

public static function clearDebugBar()
{
self::$debugbar = null;
}

public static function getShowQueries()
{
return self::$showQueries;
Expand All @@ -143,15 +169,15 @@ public static function includeRequirements()
}

// Already called
if(self::$renderer) {
if (self::$renderer) {
return;
}

$renderer = $debugbar->getJavascriptRenderer();

// We don't need the true path since we are going to use Requirements API that appends the BASE_PATH
$renderer->setBasePath(DEBUGBAR_DIR.'/assets');
$renderer->setBaseUrl(DEBUGBAR_DIR.'/assets');
$renderer->setBasePath(DEBUGBAR_DIR . '/assets');
$renderer->setBaseUrl(DEBUGBAR_DIR . '/assets');

$renderer->disableVendor('jquery');
$renderer->setEnableJqueryNoConflict(false);
Expand Down Expand Up @@ -193,7 +219,7 @@ public static function renderDebugBar()

/**
* Determine why DebugBar is disabled
*
*
* @return string
*/
public static function WhyDisabled()
Expand Down Expand Up @@ -258,7 +284,7 @@ public static function IsAdminUrl()

/**
* Avoid triggering data collection for open handler
*
*
* @return boolean
*/
public static function IsDebugBarRequest()
Expand All @@ -271,7 +297,7 @@ public static function IsDebugBarRequest()

/**
* Get request url
*
*
* @return string
*/
public static function getRequestUrl()
Expand All @@ -296,4 +322,4 @@ public static function withDebugBar($callback)
$callback(self::getDebugBar());
}
}
}
}
88 changes: 88 additions & 0 deletions tests/DebugBarTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php

/**
* Tests for DebugBar
*/
class DebugBarTest extends SapphireTest
{

public function setUp()
{
parent::setUp();

// Init manually because we are running tests
DebugBar::initDebugBar();
}

public function testInitIsWorking()
{
// De we have a debugbar instance
$this->assertNotEmpty(DebugBar::getDebugBar());

// Do we have a logger?
/* @var $logger SS_ZendLog */
$logger = SS_Log::get_logger();
$found = false;
foreach ($logger->getWriters() as $writer) {
if ($writer instanceof DebugBarLogWriter) {
$found = true;
}
}
$this->assertTrue($found);

// Do we have a db proxy
if (method_exists('DB', 'get_conn')) {
$conn = DB::get_conn();
} else {
$conn = DB::getConn();
}

$class = get_class($conn);
$this->assertContains($class, ['DebugBarDatabaseNewProxy', 'DebugBarDatabaseProxy']);
}

public function testLHelper()
{
$msg = 'Test me';
l($msg);

$debugbar = DebugBar::getDebugBar();

/* @var $messagesCollector DebugBar\DataCollector\MessagesCollector */
$messagesCollector = $debugbar['messages'];
$messages = $messagesCollector->getMessages();
$found = false;
foreach ($messages as $message) {
$txt = $message['message'];
if (strpos($txt, $msg) !== false) {
$found = true;
}
}
$this->assertTrue($found);
}

public function testDHelper()
{
$sql = 'SELECT * FROM Member';

ob_start();

// Passing a SapphireTest as first arg prevent exit
d($this, 'test', $sql);

$content = ob_get_clean();

$this->assertTrue((bool) strpos($content, "Value for: 'test'"), "Value for test not found");
$this->assertTrue((bool) strpos($content, 'sf-dump'), "Symfony dumper not found");
$this->assertTrue((bool) strpos($content, '<span style="font-weight:bold;">SELECT</span>'), "Sql formatted query not found");
}

public function testShowOnHomepage()
{
$content = file_get_contents(Director::absoluteBaseURL());

$this->assertTrue((bool) strpos($content, '"/debugbar/assets/debugbar.js'), "Base script not found");
$this->assertTrue((bool) strpos($content, 'var phpdebugbar = new PhpDebugBar.DebugBar();'), "Init script not found");
}
}

0 comments on commit 3af8f46

Please sign in to comment.