DebuggerTest.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Test\TestCase\Utility;
  16. use Cake\Controller\Controller;
  17. use Cake\Core\Configure;
  18. use Cake\Log\Log;
  19. use Cake\TestSuite\TestCase;
  20. use Cake\Utility\Debugger;
  21. use Cake\View\View;
  22. /**
  23. * DebuggerTestCaseDebugger class
  24. *
  25. */
  26. class DebuggerTestCaseDebugger extends Debugger {
  27. }
  28. class DebuggableThing {
  29. public function __debugInfo() {
  30. return ['foo' => 'bar', 'inner' => new self()];
  31. }
  32. }
  33. /**
  34. * DebuggerTest class
  35. *
  36. * !!! Be careful with changing code below as it may
  37. * !!! change line numbers which are used in the tests
  38. *
  39. */
  40. class DebuggerTest extends TestCase {
  41. protected $_restoreError = false;
  42. /**
  43. * setUp method
  44. *
  45. * @return void
  46. */
  47. public function setUp() {
  48. parent::setUp();
  49. Configure::write('debug', true);
  50. Configure::write('log', false);
  51. }
  52. /**
  53. * tearDown method
  54. *
  55. * @return void
  56. */
  57. public function tearDown() {
  58. parent::tearDown();
  59. Configure::write('log', true);
  60. if ($this->_restoreError) {
  61. restore_error_handler();
  62. }
  63. }
  64. /**
  65. * testDocRef method
  66. *
  67. * @return void
  68. */
  69. public function testDocRef() {
  70. ini_set('docref_root', '');
  71. $this->assertEquals(ini_get('docref_root'), '');
  72. new Debugger();
  73. $this->assertEquals(ini_get('docref_root'), 'http://php.net/');
  74. }
  75. /**
  76. * test Excerpt writing
  77. *
  78. * @return void
  79. */
  80. public function testExcerpt() {
  81. $result = Debugger::excerpt(__FILE__, __LINE__, 2);
  82. $this->assertTrue(is_array($result));
  83. $this->assertEquals(5, count($result));
  84. $this->assertRegExp('/function(.+)testExcerpt/', $result[1]);
  85. $result = Debugger::excerpt(__FILE__, 2, 2);
  86. $this->assertTrue(is_array($result));
  87. $this->assertEquals(4, count($result));
  88. $pattern = '/<code>.*?<span style\="color\: \#\d+">.*?&lt;\?php/';
  89. $this->assertRegExp($pattern, $result[0]);
  90. $result = Debugger::excerpt(__FILE__, 11, 2);
  91. $this->assertEquals(5, count($result));
  92. $pattern = '/<span style\="color\: \#\d{6}">\*<\/span>/';
  93. $this->assertRegExp($pattern, $result[0]);
  94. $return = Debugger::excerpt('[internal]', 2, 2);
  95. $this->assertTrue(empty($return));
  96. }
  97. /**
  98. * testOutput method
  99. *
  100. * @return void
  101. */
  102. public function testOutput() {
  103. set_error_handler('Cake\Utility\Debugger::showError');
  104. $this->_restoreError = true;
  105. $result = Debugger::output(false);
  106. $this->assertEquals('', $result);
  107. $out .= '';
  108. $result = Debugger::output(true);
  109. $this->assertEquals('Notice', $result[0]['error']);
  110. $this->assertRegExp('/Undefined variable\:\s+out/', $result[0]['description']);
  111. $this->assertRegExp('/DebuggerTest::testOutput/i', $result[0]['trace']);
  112. ob_start();
  113. Debugger::output('txt');
  114. $other .= '';
  115. $result = ob_get_clean();
  116. $this->assertRegExp('/Undefined variable:\s+other/', $result);
  117. $this->assertRegExp('/Context:/', $result);
  118. $this->assertRegExp('/DebuggerTest::testOutput/i', $result);
  119. ob_start();
  120. Debugger::output('html');
  121. $wrong .= '';
  122. $result = ob_get_clean();
  123. $this->assertRegExp('/<pre class="cake-error">.+<\/pre>/', $result);
  124. $this->assertRegExp('/<b>Notice<\/b>/', $result);
  125. $this->assertRegExp('/variable:\s+wrong/', $result);
  126. ob_start();
  127. Debugger::output('js');
  128. $buzz .= '';
  129. $result = explode('</a>', ob_get_clean());
  130. $this->assertTags($result[0], array(
  131. 'pre' => array('class' => 'cake-error'),
  132. 'a' => array(
  133. 'href' => "javascript:void(0);",
  134. 'onclick' => "preg:/document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display = " .
  135. "\(document\.getElementById\('cakeErr[a-z0-9]+\-trace'\)\.style\.display == 'none'" .
  136. " \? '' \: 'none'\);/"
  137. ),
  138. 'b' => array(), 'Notice', '/b', ' (8)',
  139. ));
  140. $this->assertRegExp('/Undefined variable:\s+buzz/', $result[1]);
  141. $this->assertRegExp('/<a[^>]+>Code/', $result[1]);
  142. $this->assertRegExp('/<a[^>]+>Context/', $result[2]);
  143. $this->assertContains('$wrong = &#039;&#039;', $result[3], 'Context should be HTML escaped.');
  144. }
  145. /**
  146. * Tests that changes in output formats using Debugger::output() change the templates used.
  147. *
  148. * @return void
  149. */
  150. public function testChangeOutputFormats() {
  151. set_error_handler('Cake\Utility\Debugger::showError');
  152. $this->_restoreError = true;
  153. Debugger::output('js', array(
  154. 'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
  155. '&line={:line}">{:path}</a>, line {:line}'
  156. ));
  157. $result = Debugger::trace();
  158. $this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
  159. Debugger::output('xml', array(
  160. 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
  161. '{:description}</error>',
  162. 'context' => "<context>{:context}</context>",
  163. 'trace' => "<stack>{:trace}</stack>",
  164. ));
  165. Debugger::output('xml');
  166. ob_start();
  167. $foo .= '';
  168. $result = ob_get_clean();
  169. $data = array(
  170. 'error' => array(),
  171. 'code' => array(), '8', '/code',
  172. 'file' => array(), 'preg:/[^<]+/', '/file',
  173. 'line' => array(), '' . (intval(__LINE__) - 7), '/line',
  174. 'preg:/Undefined variable:\s+foo/',
  175. '/error'
  176. );
  177. $this->assertTags($result, $data, true);
  178. }
  179. /**
  180. * Test that outputAs works.
  181. *
  182. * @return void
  183. */
  184. public function testOutputAs() {
  185. Debugger::outputAs('html');
  186. $this->assertEquals('html', Debugger::outputAs());
  187. }
  188. /**
  189. * Test that choosing a non-existent format causes an exception
  190. *
  191. * @expectedException \Cake\Error\Exception
  192. * @return void
  193. */
  194. public function testOutputAsException() {
  195. Debugger::outputAs('Invalid junk');
  196. }
  197. /**
  198. * Tests that changes in output formats using Debugger::output() change the templates used.
  199. *
  200. * @return void
  201. */
  202. public function testAddFormat() {
  203. set_error_handler('Cake\Utility\Debugger::showError');
  204. $this->_restoreError = true;
  205. Debugger::addFormat('js', array(
  206. 'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
  207. '&line={:line}">{:path}</a>, line {:line}'
  208. ));
  209. Debugger::outputAs('js');
  210. $result = Debugger::trace();
  211. $this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
  212. Debugger::addFormat('xml', array(
  213. 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
  214. '{:description}</error>',
  215. ));
  216. Debugger::outputAs('xml');
  217. ob_start();
  218. $foo .= '';
  219. $result = ob_get_clean();
  220. $data = array(
  221. '<error',
  222. '<code', '8', '/code',
  223. '<file', 'preg:/[^<]+/', '/file',
  224. '<line', '' . (intval(__LINE__) - 7), '/line',
  225. 'preg:/Undefined variable:\s+foo/',
  226. '/error'
  227. );
  228. $this->assertTags($result, $data, true);
  229. }
  230. /**
  231. * Test adding a format that is handled by a callback.
  232. *
  233. * @return void
  234. */
  235. public function testAddFormatCallback() {
  236. set_error_handler('Cake\Utility\Debugger::showError');
  237. $this->_restoreError = true;
  238. Debugger::addFormat('callback', array('callback' => array($this, 'customFormat')));
  239. Debugger::outputAs('callback');
  240. ob_start();
  241. $foo .= '';
  242. $result = ob_get_clean();
  243. $this->assertContains('Notice: I eated an error', $result);
  244. $this->assertContains('DebuggerTest.php', $result);
  245. }
  246. /**
  247. * Test method for testing addFormat with callbacks.
  248. *
  249. * @return void
  250. */
  251. public function customFormat($error, $strings) {
  252. return $error['error'] . ': I eated an error ' . $error['file'];
  253. }
  254. /**
  255. * testTrimPath method
  256. *
  257. * @return void
  258. */
  259. public function testTrimPath() {
  260. $this->assertEquals('APP/', Debugger::trimPath(APP));
  261. $this->assertEquals('CORE' . DS . 'src' . DS, Debugger::trimPath(CAKE));
  262. $this->assertEquals('Some/Other/Path', Debugger::trimPath('Some/Other/Path'));
  263. }
  264. /**
  265. * testExportVar method
  266. *
  267. * @return void
  268. */
  269. public function testExportVar() {
  270. $Controller = new Controller();
  271. $Controller->helpers = array('Html', 'Form');
  272. $View = $Controller->createView();
  273. $View->int = 2;
  274. $View->float = 1.333;
  275. $result = Debugger::exportVar($View);
  276. $expected = <<<TEXT
  277. object(Cake\View\View) {
  278. Blocks => object(Cake\View\ViewBlock) {}
  279. plugin => null
  280. name => ''
  281. passedArgs => []
  282. helpers => [
  283. (int) 0 => 'Html',
  284. (int) 1 => 'Form'
  285. ]
  286. viewPath => ''
  287. view => null
  288. layout => 'default'
  289. layoutPath => null
  290. autoLayout => true
  291. subDir => null
  292. theme => null
  293. cacheAction => false
  294. validationErrors => []
  295. hasRendered => false
  296. uuids => []
  297. request => object(Cake\Network\Request) {}
  298. response => object(Cake\Network\Response) {}
  299. elementCache => 'default'
  300. elementCacheSettings => []
  301. viewVars => []
  302. Html => object(Cake\View\Helper\HtmlHelper) {}
  303. Form => object(Cake\View\Helper\FormHelper) {}
  304. int => (int) 2
  305. float => (float) 1.333
  306. [protected] _helpers => object(Cake\View\HelperRegistry) {}
  307. [protected] _ext => '.ctp'
  308. [protected] _passedVars => [
  309. (int) 0 => 'viewVars',
  310. (int) 1 => 'autoLayout',
  311. (int) 2 => 'helpers',
  312. (int) 3 => 'view',
  313. (int) 4 => 'layout',
  314. (int) 5 => 'name',
  315. (int) 6 => 'theme',
  316. (int) 7 => 'layoutPath',
  317. (int) 8 => 'viewPath',
  318. (int) 9 => 'plugin',
  319. (int) 10 => 'passedArgs',
  320. (int) 11 => 'cacheAction'
  321. ]
  322. [protected] _scripts => []
  323. [protected] _paths => []
  324. [protected] _pathsForPlugin => []
  325. [protected] _parents => []
  326. [protected] _current => null
  327. [protected] _currentType => ''
  328. [protected] _stack => []
  329. [protected] _eventManager => object(Cake\Event\EventManager) {}
  330. }
  331. TEXT;
  332. $this->assertTextEquals($expected, $result);
  333. $data = array(
  334. 1 => 'Index one',
  335. 5 => 'Index five'
  336. );
  337. $result = Debugger::exportVar($data);
  338. $expected = <<<TEXT
  339. [
  340. (int) 1 => 'Index one',
  341. (int) 5 => 'Index five'
  342. ]
  343. TEXT;
  344. $this->assertTextEquals($expected, $result);
  345. $data = array(
  346. 'key' => array(
  347. 'value'
  348. )
  349. );
  350. $result = Debugger::exportVar($data, 1);
  351. $expected = <<<TEXT
  352. [
  353. 'key' => [
  354. [maximum depth reached]
  355. ]
  356. ]
  357. TEXT;
  358. $this->assertTextEquals($expected, $result);
  359. $data = false;
  360. $result = Debugger::exportVar($data);
  361. $expected = <<<TEXT
  362. false
  363. TEXT;
  364. $this->assertTextEquals($expected, $result);
  365. $file = fopen('php://output', 'w');
  366. fclose($file);
  367. $result = Debugger::exportVar($file);
  368. $this->assertTextEquals('unknown', $result);
  369. }
  370. /**
  371. * Test exporting various kinds of false.
  372. *
  373. * @return void
  374. */
  375. public function testExportVarZero() {
  376. $data = array(
  377. 'nothing' => '',
  378. 'null' => null,
  379. 'false' => false,
  380. 'szero' => '0',
  381. 'zero' => 0
  382. );
  383. $result = Debugger::exportVar($data);
  384. $expected = <<<TEXT
  385. [
  386. 'nothing' => '',
  387. 'null' => null,
  388. 'false' => false,
  389. 'szero' => '0',
  390. 'zero' => (int) 0
  391. ]
  392. TEXT;
  393. $this->assertTextEquals($expected, $result);
  394. }
  395. /**
  396. * testLog method
  397. *
  398. * @return void
  399. */
  400. public function testLog() {
  401. $mock = $this->getMock('Cake\Log\Engine\BaseLog', ['write']);
  402. Log::config('test', ['engine' => $mock]);
  403. $mock->expects($this->at(0))
  404. ->method('write')
  405. ->with('debug', $this->logicalAnd(
  406. $this->stringContains('DebuggerTest::testLog'),
  407. $this->stringContains('cool')
  408. ));
  409. $mock->expects($this->at(1))
  410. ->method('write')
  411. ->with('debug', $this->logicalAnd(
  412. $this->stringContains('DebuggerTest::testLog'),
  413. $this->stringContains('[main]'),
  414. $this->stringContains("'whatever',"),
  415. $this->stringContains("'here'")
  416. ));
  417. Debugger::log('cool');
  418. Debugger::log(array('whatever', 'here'));
  419. Log::drop('test');
  420. }
  421. /**
  422. * test log() depth
  423. *
  424. * @return void
  425. */
  426. public function testLogDepth() {
  427. $mock = $this->getMock('Cake\Log\Engine\BaseLog', ['write']);
  428. Log::config('test', ['engine' => $mock]);
  429. $mock->expects($this->at(0))
  430. ->method('write')
  431. ->with('debug', $this->logicalAnd(
  432. $this->stringContains('DebuggerTest::testLog'),
  433. $this->stringContains('test'),
  434. $this->logicalNot($this->stringContains('val'))
  435. ));
  436. $val = array(
  437. 'test' => array('key' => 'val')
  438. );
  439. Debugger::log($val, LOG_DEBUG, 0);
  440. }
  441. /**
  442. * testDump method
  443. *
  444. * @return void
  445. */
  446. public function testDump() {
  447. $var = array('People' => array(
  448. array(
  449. 'name' => 'joeseph',
  450. 'coat' => 'technicolor',
  451. 'hair_color' => 'brown'
  452. ),
  453. array(
  454. 'name' => 'Shaft',
  455. 'coat' => 'black',
  456. 'hair' => 'black'
  457. )
  458. ));
  459. ob_start();
  460. Debugger::dump($var);
  461. $result = ob_get_clean();
  462. $open = php_sapi_name() === 'cli' ? "\n" : '<pre>';
  463. $close = php_sapi_name() === 'cli' ? "\n" : '</pre>';
  464. $expected = <<<TEXT
  465. {$open}[
  466. 'People' => [
  467. (int) 0 => [
  468. 'name' => 'joeseph',
  469. 'coat' => 'technicolor',
  470. 'hair_color' => 'brown'
  471. ],
  472. (int) 1 => [
  473. 'name' => 'Shaft',
  474. 'coat' => 'black',
  475. 'hair' => 'black'
  476. ]
  477. ]
  478. ]{$close}
  479. TEXT;
  480. $this->assertTextEquals($expected, $result);
  481. ob_start();
  482. Debugger::dump($var, 1);
  483. $result = ob_get_clean();
  484. $open = php_sapi_name() === 'cli' ? "\n" : '<pre>';
  485. $close = php_sapi_name() === 'cli' ? "\n" : '</pre>';
  486. $expected = <<<TEXT
  487. {$open}[
  488. 'People' => [
  489. [maximum depth reached]
  490. ]
  491. ]{$close}
  492. TEXT;
  493. $this->assertTextEquals($expected, $result);
  494. }
  495. /**
  496. * test getInstance.
  497. *
  498. * @return void
  499. */
  500. public function testGetInstance() {
  501. $result = Debugger::getInstance();
  502. $this->assertInstanceOf('Cake\Utility\Debugger', $result);
  503. $result = Debugger::getInstance(__NAMESPACE__ . '\DebuggerTestCaseDebugger');
  504. $this->assertInstanceOf(__NAMESPACE__ . '\DebuggerTestCaseDebugger', $result);
  505. $result = Debugger::getInstance();
  506. $this->assertInstanceOf(__NAMESPACE__ . '\DebuggerTestCaseDebugger', $result);
  507. $result = Debugger::getInstance('Cake\Utility\Debugger');
  508. $this->assertInstanceOf('Cake\Utility\Debugger', $result);
  509. }
  510. /**
  511. * testNoDbCredentials
  512. *
  513. * If a connection error occurs, the config variable is passed through exportVar
  514. * *** our database login credentials such that they are never visible
  515. *
  516. * @return void
  517. */
  518. public function testNoDbCredentials() {
  519. $config = array(
  520. 'datasource' => 'mysql',
  521. 'persistent' => false,
  522. 'host' => 'void.cakephp.org',
  523. 'login' => 'cakephp-user',
  524. 'password' => 'cakephp-password',
  525. 'database' => 'cakephp-database',
  526. 'prefix' => ''
  527. );
  528. $output = Debugger::exportVar($config);
  529. $expectedArray = array(
  530. 'datasource' => 'mysql',
  531. 'persistent' => false,
  532. 'host' => '*****',
  533. 'login' => '*****',
  534. 'password' => '*****',
  535. 'database' => '*****',
  536. 'prefix' => ''
  537. );
  538. $expected = Debugger::exportVar($expectedArray);
  539. $this->assertEquals($expected, $output);
  540. }
  541. /**
  542. * Test that exportVar() doesn't loop through recursive structures.
  543. *
  544. * @return void
  545. */
  546. public function testExportVarRecursion() {
  547. $output = Debugger::exportVar($GLOBALS);
  548. $this->assertContains("'GLOBALS' => [recursion]", $output);
  549. }
  550. /**
  551. * test trace exclude
  552. *
  553. * @return void
  554. */
  555. public function testTraceExclude() {
  556. $result = Debugger::trace();
  557. $this->assertRegExp('/^Cake\\\Test\\\TestCase\\\Utility\\\DebuggerTest::testTraceExclude/', $result);
  558. $result = Debugger::trace(array(
  559. 'exclude' => array('Cake\Test\TestCase\Utility\DebuggerTest::testTraceExclude')
  560. ));
  561. $this->assertNotRegExp('/^Cake\\\Test\\\TestCase\\\Utility\\\DebuggerTest::testTraceExclude/', $result);
  562. }
  563. /**
  564. * Tests that __debugInfo is used when available
  565. *
  566. * @return void
  567. */
  568. public function testDebugInfo() {
  569. $object = new DebuggableThing();
  570. $result = Debugger::exportVar($object, 2);
  571. $expected = <<<eos
  572. object(Cake\Test\TestCase\Utility\DebuggableThing) {
  573. 'foo' => 'bar',
  574. 'inner' => object(Cake\Test\TestCase\Utility\DebuggableThing) {
  575. [maximum depth reached]
  576. }
  577. }
  578. eos;
  579. $this->assertEquals($expected, $result);
  580. }
  581. }