DebuggerTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  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\Error;
  16. use Cake\Controller\Controller;
  17. use Cake\Core\Configure;
  18. use Cake\Error\Debugger;
  19. use Cake\Log\Log;
  20. use Cake\TestSuite\TestCase;
  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. Log::drop('stderr');
  51. Log::drop('stdout');
  52. }
  53. /**
  54. * tearDown method
  55. *
  56. * @return void
  57. */
  58. public function tearDown() {
  59. parent::tearDown();
  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\Error\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. $expected = 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->assertHtml($expected, $result[0]);
  141. $this->assertRegExp('/Undefined variable:\s+buzz/', $result[1]);
  142. $this->assertRegExp('/<a[^>]+>Code/', $result[1]);
  143. $this->assertRegExp('/<a[^>]+>Context/', $result[2]);
  144. $this->assertContains('$wrong = &#039;&#039;', $result[3], 'Context should be HTML escaped.');
  145. }
  146. /**
  147. * Tests that changes in output formats using Debugger::output() change the templates used.
  148. *
  149. * @return void
  150. */
  151. public function testChangeOutputFormats() {
  152. set_error_handler('Cake\Error\Debugger::showError');
  153. $this->_restoreError = true;
  154. Debugger::output('js', array(
  155. 'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
  156. '&line={:line}">{:path}</a>, line {:line}'
  157. ));
  158. $result = Debugger::trace();
  159. $this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
  160. Debugger::output('xml', array(
  161. 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
  162. '{:description}</error>',
  163. 'context' => "<context>{:context}</context>",
  164. 'trace' => "<stack>{:trace}</stack>",
  165. ));
  166. Debugger::output('xml');
  167. ob_start();
  168. $foo .= '';
  169. $result = ob_get_clean();
  170. $expected = array(
  171. 'error' => array(),
  172. 'code' => array(), '8', '/code',
  173. 'file' => array(), 'preg:/[^<]+/', '/file',
  174. 'line' => array(), '' . (intval(__LINE__) - 7), '/line',
  175. 'preg:/Undefined variable:\s+foo/',
  176. '/error'
  177. );
  178. $this->assertHtml($expected, $result, true);
  179. }
  180. /**
  181. * Test that outputAs works.
  182. *
  183. * @return void
  184. */
  185. public function testOutputAs() {
  186. Debugger::outputAs('html');
  187. $this->assertEquals('html', Debugger::outputAs());
  188. }
  189. /**
  190. * Test that choosing a non-existent format causes an exception
  191. *
  192. * @expectedException InvalidArgumentException
  193. * @return void
  194. */
  195. public function testOutputAsException() {
  196. Debugger::outputAs('Invalid junk');
  197. }
  198. /**
  199. * Tests that changes in output formats using Debugger::output() change the templates used.
  200. *
  201. * @return void
  202. */
  203. public function testAddFormat() {
  204. set_error_handler('Cake\Error\Debugger::showError');
  205. $this->_restoreError = true;
  206. Debugger::addFormat('js', array(
  207. 'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
  208. '&line={:line}">{:path}</a>, line {:line}'
  209. ));
  210. Debugger::outputAs('js');
  211. $result = Debugger::trace();
  212. $this->assertRegExp('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
  213. Debugger::addFormat('xml', array(
  214. 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
  215. '{:description}</error>',
  216. ));
  217. Debugger::outputAs('xml');
  218. ob_start();
  219. $foo .= '';
  220. $result = ob_get_clean();
  221. $expected = array(
  222. '<error',
  223. '<code', '8', '/code',
  224. '<file', 'preg:/[^<]+/', '/file',
  225. '<line', '' . (intval(__LINE__) - 7), '/line',
  226. 'preg:/Undefined variable:\s+foo/',
  227. '/error'
  228. );
  229. $this->assertHtml($expected, $result, true);
  230. }
  231. /**
  232. * Test adding a format that is handled by a callback.
  233. *
  234. * @return void
  235. */
  236. public function testAddFormatCallback() {
  237. set_error_handler('Cake\Error\Debugger::showError');
  238. $this->_restoreError = true;
  239. Debugger::addFormat('callback', array('callback' => array($this, 'customFormat')));
  240. Debugger::outputAs('callback');
  241. ob_start();
  242. $foo .= '';
  243. $result = ob_get_clean();
  244. $this->assertContains('Notice: I eated an error', $result);
  245. $this->assertContains('DebuggerTest.php', $result);
  246. }
  247. /**
  248. * Test method for testing addFormat with callbacks.
  249. *
  250. * @return void
  251. */
  252. public function customFormat($error, $strings) {
  253. return $error['error'] . ': I eated an error ' . $error['file'];
  254. }
  255. /**
  256. * testTrimPath method
  257. *
  258. * @return void
  259. */
  260. public function testTrimPath() {
  261. $this->assertEquals('APP/', Debugger::trimPath(APP));
  262. $this->assertEquals('CORE' . DS . 'src' . DS, Debugger::trimPath(CAKE));
  263. $this->assertEquals('Some/Other/Path', Debugger::trimPath('Some/Other/Path'));
  264. }
  265. /**
  266. * testExportVar method
  267. *
  268. * @return void
  269. */
  270. public function testExportVar() {
  271. $Controller = new Controller();
  272. $Controller->helpers = array('Html', 'Form');
  273. $View = $Controller->createView();
  274. $View->int = 2;
  275. $View->float = 1.333;
  276. $result = Debugger::exportVar($View);
  277. $expected = <<<TEXT
  278. object(Cake\View\View) {
  279. Blocks => object(Cake\View\ViewBlock) {}
  280. plugin => null
  281. name => ''
  282. passedArgs => []
  283. helpers => [
  284. (int) 0 => 'Html',
  285. (int) 1 => 'Form'
  286. ]
  287. viewPath => ''
  288. view => null
  289. layout => 'default'
  290. layoutPath => null
  291. autoLayout => true
  292. subDir => null
  293. theme => null
  294. hasRendered => false
  295. uuids => []
  296. request => object(Cake\Network\Request) {}
  297. response => object(Cake\Network\Response) {}
  298. elementCache => 'default'
  299. elementCacheSettings => []
  300. viewVars => []
  301. Html => object(Cake\View\Helper\HtmlHelper) {}
  302. Form => object(Cake\View\Helper\FormHelper) {}
  303. int => (int) 2
  304. float => (float) 1.333
  305. [protected] _helpers => object(Cake\View\HelperRegistry) {}
  306. [protected] _ext => '.ctp'
  307. [protected] _passedVars => [
  308. (int) 0 => 'viewVars',
  309. (int) 1 => 'autoLayout',
  310. (int) 2 => 'helpers',
  311. (int) 3 => 'view',
  312. (int) 4 => 'layout',
  313. (int) 5 => 'name',
  314. (int) 6 => 'theme',
  315. (int) 7 => 'layoutPath',
  316. (int) 8 => 'viewPath',
  317. (int) 9 => 'plugin',
  318. (int) 10 => 'passedArgs'
  319. ]
  320. [protected] _paths => []
  321. [protected] _pathsForPlugin => []
  322. [protected] _parents => []
  323. [protected] _current => null
  324. [protected] _currentType => ''
  325. [protected] _stack => []
  326. [protected] _eventManager => object(Cake\Event\EventManager) {}
  327. }
  328. TEXT;
  329. $this->assertTextEquals($expected, $result);
  330. $data = array(
  331. 1 => 'Index one',
  332. 5 => 'Index five'
  333. );
  334. $result = Debugger::exportVar($data);
  335. $expected = <<<TEXT
  336. [
  337. (int) 1 => 'Index one',
  338. (int) 5 => 'Index five'
  339. ]
  340. TEXT;
  341. $this->assertTextEquals($expected, $result);
  342. $data = array(
  343. 'key' => array(
  344. 'value'
  345. )
  346. );
  347. $result = Debugger::exportVar($data, 1);
  348. $expected = <<<TEXT
  349. [
  350. 'key' => [
  351. [maximum depth reached]
  352. ]
  353. ]
  354. TEXT;
  355. $this->assertTextEquals($expected, $result);
  356. $data = false;
  357. $result = Debugger::exportVar($data);
  358. $expected = <<<TEXT
  359. false
  360. TEXT;
  361. $this->assertTextEquals($expected, $result);
  362. $file = fopen('php://output', 'w');
  363. fclose($file);
  364. $result = Debugger::exportVar($file);
  365. $this->assertTextEquals('unknown', $result);
  366. }
  367. /**
  368. * Test exporting various kinds of false.
  369. *
  370. * @return void
  371. */
  372. public function testExportVarZero() {
  373. $data = array(
  374. 'nothing' => '',
  375. 'null' => null,
  376. 'false' => false,
  377. 'szero' => '0',
  378. 'zero' => 0
  379. );
  380. $result = Debugger::exportVar($data);
  381. $expected = <<<TEXT
  382. [
  383. 'nothing' => '',
  384. 'null' => null,
  385. 'false' => false,
  386. 'szero' => '0',
  387. 'zero' => (int) 0
  388. ]
  389. TEXT;
  390. $this->assertTextEquals($expected, $result);
  391. }
  392. /**
  393. * testLog method
  394. *
  395. * @return void
  396. */
  397. public function testLog() {
  398. $mock = $this->getMock('Cake\Log\Engine\BaseLog', ['write']);
  399. Log::config('test', ['engine' => $mock]);
  400. $mock->expects($this->at(0))
  401. ->method('write')
  402. ->with('debug', $this->logicalAnd(
  403. $this->stringContains('DebuggerTest::testLog'),
  404. $this->stringContains('cool')
  405. ));
  406. $mock->expects($this->at(1))
  407. ->method('write')
  408. ->with('debug', $this->logicalAnd(
  409. $this->stringContains('DebuggerTest::testLog'),
  410. $this->stringContains('[main]'),
  411. $this->stringContains("'whatever',"),
  412. $this->stringContains("'here'")
  413. ));
  414. Debugger::log('cool');
  415. Debugger::log(array('whatever', 'here'));
  416. Log::drop('test');
  417. }
  418. /**
  419. * test log() depth
  420. *
  421. * @return void
  422. */
  423. public function testLogDepth() {
  424. $mock = $this->getMock('Cake\Log\Engine\BaseLog', ['write']);
  425. Log::config('test', ['engine' => $mock]);
  426. $mock->expects($this->at(0))
  427. ->method('write')
  428. ->with('debug', $this->logicalAnd(
  429. $this->stringContains('DebuggerTest::testLog'),
  430. $this->stringContains('test'),
  431. $this->logicalNot($this->stringContains('val'))
  432. ));
  433. $val = array(
  434. 'test' => array('key' => 'val')
  435. );
  436. Debugger::log($val, LOG_DEBUG, 0);
  437. }
  438. /**
  439. * testDump method
  440. *
  441. * @return void
  442. */
  443. public function testDump() {
  444. $var = array('People' => array(
  445. array(
  446. 'name' => 'joeseph',
  447. 'coat' => 'technicolor',
  448. 'hair_color' => 'brown'
  449. ),
  450. array(
  451. 'name' => 'Shaft',
  452. 'coat' => 'black',
  453. 'hair' => 'black'
  454. )
  455. ));
  456. ob_start();
  457. Debugger::dump($var);
  458. $result = ob_get_clean();
  459. $open = php_sapi_name() === 'cli' ? "\n" : '<pre>';
  460. $close = php_sapi_name() === 'cli' ? "\n" : '</pre>';
  461. $expected = <<<TEXT
  462. {$open}[
  463. 'People' => [
  464. (int) 0 => [
  465. 'name' => 'joeseph',
  466. 'coat' => 'technicolor',
  467. 'hair_color' => 'brown'
  468. ],
  469. (int) 1 => [
  470. 'name' => 'Shaft',
  471. 'coat' => 'black',
  472. 'hair' => 'black'
  473. ]
  474. ]
  475. ]{$close}
  476. TEXT;
  477. $this->assertTextEquals($expected, $result);
  478. ob_start();
  479. Debugger::dump($var, 1);
  480. $result = ob_get_clean();
  481. $open = php_sapi_name() === 'cli' ? "\n" : '<pre>';
  482. $close = php_sapi_name() === 'cli' ? "\n" : '</pre>';
  483. $expected = <<<TEXT
  484. {$open}[
  485. 'People' => [
  486. [maximum depth reached]
  487. ]
  488. ]{$close}
  489. TEXT;
  490. $this->assertTextEquals($expected, $result);
  491. }
  492. /**
  493. * test getInstance.
  494. *
  495. * @return void
  496. */
  497. public function testGetInstance() {
  498. $result = Debugger::getInstance();
  499. $this->assertInstanceOf('Cake\Error\Debugger', $result);
  500. $result = Debugger::getInstance(__NAMESPACE__ . '\DebuggerTestCaseDebugger');
  501. $this->assertInstanceOf(__NAMESPACE__ . '\DebuggerTestCaseDebugger', $result);
  502. $result = Debugger::getInstance();
  503. $this->assertInstanceOf(__NAMESPACE__ . '\DebuggerTestCaseDebugger', $result);
  504. $result = Debugger::getInstance('Cake\Error\Debugger');
  505. $this->assertInstanceOf('Cake\Error\Debugger', $result);
  506. }
  507. /**
  508. * testNoDbCredentials
  509. *
  510. * If a connection error occurs, the config variable is passed through exportVar
  511. * *** our database login credentials such that they are never visible
  512. *
  513. * @return void
  514. */
  515. public function testNoDbCredentials() {
  516. $config = array(
  517. 'datasource' => 'mysql',
  518. 'persistent' => false,
  519. 'host' => 'void.cakephp.org',
  520. 'login' => 'cakephp-user',
  521. 'password' => 'cakephp-password',
  522. 'database' => 'cakephp-database',
  523. 'prefix' => ''
  524. );
  525. $output = Debugger::exportVar($config);
  526. $expectedArray = array(
  527. 'datasource' => 'mysql',
  528. 'persistent' => false,
  529. 'host' => '*****',
  530. 'login' => '*****',
  531. 'password' => '*****',
  532. 'database' => '*****',
  533. 'prefix' => ''
  534. );
  535. $expected = Debugger::exportVar($expectedArray);
  536. $this->assertEquals($expected, $output);
  537. }
  538. /**
  539. * Test that exportVar() doesn't loop through recursive structures.
  540. *
  541. * @return void
  542. */
  543. public function testExportVarRecursion() {
  544. $output = Debugger::exportVar($GLOBALS);
  545. $this->assertContains("'GLOBALS' => [recursion]", $output);
  546. }
  547. /**
  548. * test trace exclude
  549. *
  550. * @return void
  551. */
  552. public function testTraceExclude() {
  553. $result = Debugger::trace();
  554. $this->assertRegExp('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result);
  555. $result = Debugger::trace(array(
  556. 'exclude' => array('Cake\Test\TestCase\Error\DebuggerTest::testTraceExclude')
  557. ));
  558. $this->assertNotRegExp('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result);
  559. }
  560. /**
  561. * Tests that __debugInfo is used when available
  562. *
  563. * @return void
  564. */
  565. public function testDebugInfo() {
  566. $object = new DebuggableThing();
  567. $result = Debugger::exportVar($object, 2);
  568. $expected = <<<eos
  569. object(Cake\Test\TestCase\Error\DebuggableThing) {
  570. 'foo' => 'bar',
  571. 'inner' => object(Cake\Test\TestCase\Error\DebuggableThing) {}
  572. }
  573. eos;
  574. $this->assertEquals($expected, $result);
  575. }
  576. }