DebuggerTest.php 16 KB

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