DebuggerTest.php 17 KB

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