DebuggerTest.php 15 KB

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