DebuggerTest.php 15 KB

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