DebuggerTest.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice.
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP Project
  13. * @since 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Error;
  17. use Cake\Controller\Controller;
  18. use Cake\Core\Configure;
  19. use Cake\Error\Debug\NodeInterface;
  20. use Cake\Error\Debug\ScalarNode;
  21. use Cake\Error\Debug\SpecialNode;
  22. use Cake\Error\Debug\TextFormatter;
  23. use Cake\Error\Debugger;
  24. use Cake\Form\Form;
  25. use Cake\Log\Log;
  26. use Cake\TestSuite\TestCase;
  27. use RuntimeException;
  28. use SplFixedArray;
  29. use stdClass;
  30. use TestApp\Error\TestDebugger;
  31. use TestApp\Error\Thing\DebuggableThing;
  32. use TestApp\Error\Thing\SecurityThing;
  33. use TestApp\Utility\ThrowsDebugInfo;
  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. /**
  43. * @var bool
  44. */
  45. protected $restoreError = false;
  46. /**
  47. * setUp method
  48. *
  49. * @return void
  50. */
  51. public function setUp(): void
  52. {
  53. parent::setUp();
  54. Configure::write('debug', true);
  55. Log::drop('stderr');
  56. Log::drop('stdout');
  57. Debugger::configInstance('exportFormatter', TextFormatter::class);
  58. }
  59. /**
  60. * tearDown method
  61. *
  62. * @return void
  63. */
  64. public function tearDown(): void
  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. ini_set('docref_root', '');
  79. $this->assertEquals(ini_get('docref_root'), '');
  80. // Force a new instance.
  81. Debugger::getInstance(TestDebugger::class);
  82. Debugger::getInstance(Debugger::class);
  83. $this->assertEquals(ini_get('docref_root'), 'https://secure.php.net/');
  84. }
  85. /**
  86. * test Excerpt writing
  87. *
  88. * @return void
  89. */
  90. public function testExcerpt()
  91. {
  92. $result = Debugger::excerpt(__FILE__, __LINE__ - 1, 2);
  93. $this->assertIsArray($result);
  94. $this->assertCount(5, $result);
  95. $this->assertMatchesRegularExpression('/function(.+)testExcerpt/', $result[1]);
  96. $result = Debugger::excerpt(__FILE__, 2, 2);
  97. $this->assertIsArray($result);
  98. $this->assertCount(4, $result);
  99. $this->skipIf(defined('HHVM_VERSION'), 'HHVM does not highlight php code');
  100. $pattern = '/<code>.*?<span style\="color\: \#\d+">.*?&lt;\?php/';
  101. $this->assertMatchesRegularExpression($pattern, $result[0]);
  102. $result = Debugger::excerpt(__FILE__, 11, 2);
  103. $this->assertCount(5, $result);
  104. $pattern = '/<span style\="color\: \#\d{6}">.*?<\/span>/';
  105. $this->assertMatchesRegularExpression($pattern, $result[0]);
  106. $return = Debugger::excerpt('[internal]', 2, 2);
  107. $this->assertEmpty($return);
  108. $result = Debugger::excerpt(__FILE__, __LINE__, 5);
  109. $this->assertCount(11, $result);
  110. $this->assertStringContainsString('Debugger', $result[5]);
  111. $this->assertStringContainsString('excerpt', $result[5]);
  112. $this->assertStringContainsString('__FILE__', $result[5]);
  113. $result = Debugger::excerpt(__FILE__, 1, 2);
  114. $this->assertCount(3, $result);
  115. $lastLine = count(explode("\n", file_get_contents(__FILE__)));
  116. $result = Debugger::excerpt(__FILE__, $lastLine, 2);
  117. $this->assertCount(3, $result);
  118. }
  119. /**
  120. * Test that setOutputFormat works.
  121. *
  122. * @return void
  123. */
  124. public function testSetOutputFormat()
  125. {
  126. Debugger::setOutputFormat('html');
  127. $this->assertSame('html', Debugger::getOutputFormat());
  128. }
  129. /**
  130. * Test that getOutputFormat/setOutputFormat works.
  131. *
  132. * @return void
  133. */
  134. public function testGetSetOutputFormat()
  135. {
  136. Debugger::setOutputFormat('html');
  137. $this->assertSame('html', Debugger::getOutputFormat());
  138. }
  139. /**
  140. * Test that choosing a nonexistent format causes an exception
  141. *
  142. * @return void
  143. */
  144. public function testSetOutputAsException()
  145. {
  146. $this->expectException(\InvalidArgumentException::class);
  147. Debugger::setOutputFormat('Invalid junk');
  148. }
  149. /**
  150. * Test outputError with description encoding
  151. *
  152. * @return void
  153. */
  154. public function testOutputErrorDescriptionEncoding()
  155. {
  156. Debugger::setOutputFormat('html');
  157. ob_start();
  158. $debugger = Debugger::getInstance();
  159. $debugger->outputError([
  160. 'error' => 'Notice',
  161. 'code' => E_NOTICE,
  162. 'level' => E_NOTICE,
  163. 'description' => 'Undefined index <script>alert(1)</script>',
  164. 'file' => __FILE__,
  165. 'line' => __LINE__,
  166. ]);
  167. $result = ob_get_clean();
  168. $this->assertStringContainsString('&lt;script&gt;', $result);
  169. $this->assertStringNotContainsString('<script>', $result);
  170. }
  171. /**
  172. * Tests that the correct line is being highlighted.
  173. *
  174. * @return void
  175. */
  176. public function testOutputErrorLineHighlight()
  177. {
  178. Debugger::setOutputFormat('js');
  179. ob_start();
  180. $debugger = Debugger::getInstance();
  181. $data = [
  182. 'level' => E_NOTICE,
  183. 'code' => E_NOTICE,
  184. 'file' => __FILE__,
  185. 'line' => __LINE__,
  186. 'description' => 'Error description',
  187. 'start' => 1,
  188. ];
  189. $debugger->outputError($data);
  190. $result = ob_get_clean();
  191. $this->assertMatchesRegularExpression('#^\<span class\="code\-highlight"\>.*outputError.*\</span\>$#m', $result);
  192. }
  193. /**
  194. * Tests that changes in output formats using Debugger::output() change the templates used.
  195. *
  196. * @return void
  197. */
  198. public function testAddFormat()
  199. {
  200. Debugger::addFormat('js', [
  201. 'traceLine' => '{:reference} - <a href="txmt://open?url=file://{:file}' .
  202. '&line={:line}">{:path}</a>, line {:line}',
  203. ]);
  204. Debugger::setOutputFormat('js');
  205. $result = Debugger::trace();
  206. $this->assertMatchesRegularExpression('/' . preg_quote('txmt://open?url=file://', '/') . '(\/|[A-Z]:\\\\)' . '/', $result);
  207. Debugger::addFormat('xml', [
  208. 'error' => '<error><code>{:code}</code><file>{:file}</file><line>{:line}</line>' .
  209. '{:description}</error>',
  210. ]);
  211. Debugger::setOutputFormat('xml');
  212. ob_start();
  213. $debugger = Debugger::getInstance();
  214. $debugger->outputError([
  215. 'level' => E_NOTICE,
  216. 'code' => E_NOTICE,
  217. 'file' => __FILE__,
  218. 'line' => __LINE__,
  219. 'description' => 'Undefined variable: foo',
  220. ]);
  221. $result = ob_get_clean();
  222. $expected = [
  223. '<error',
  224. '<code', '8', '/code',
  225. '<file', 'preg:/[^<]+/', '/file',
  226. '<line', '' . ((int)__LINE__ - 9), '/line',
  227. 'preg:/Undefined variable:\s+foo/',
  228. '/error',
  229. ];
  230. $this->assertHtml($expected, $result, true);
  231. }
  232. /**
  233. * Test adding a format that is handled by a callback.
  234. *
  235. * @return void
  236. */
  237. public function testAddFormatCallback()
  238. {
  239. Debugger::addFormat('callback', ['callback' => [$this, 'customFormat']]);
  240. Debugger::setOutputFormat('callback');
  241. ob_start();
  242. $debugger = Debugger::getInstance();
  243. $debugger->outputError([
  244. 'error' => 'Notice',
  245. 'code' => E_NOTICE,
  246. 'level' => E_NOTICE,
  247. 'description' => 'Undefined variable $foo',
  248. 'file' => __FILE__,
  249. 'line' => __LINE__,
  250. ]);
  251. $result = ob_get_clean();
  252. $this->assertStringContainsString('Notice: I eated an error', $result);
  253. $this->assertStringContainsString('DebuggerTest.php', $result);
  254. Debugger::setOutputFormat('js');
  255. }
  256. /**
  257. * Test method for testing addFormat with callbacks.
  258. *
  259. * @return void
  260. */
  261. public function customFormat($error, $strings)
  262. {
  263. echo $error['error'] . ': I eated an error ' . $error['file'];
  264. }
  265. /**
  266. * testTrimPath method
  267. *
  268. * @return void
  269. */
  270. public function testTrimPath()
  271. {
  272. $this->assertSame('APP/', Debugger::trimPath(APP));
  273. $this->assertSame('CORE' . DS . 'src' . DS, Debugger::trimPath(CAKE));
  274. $this->assertSame('Some/Other/Path', Debugger::trimPath('Some/Other/Path'));
  275. }
  276. /**
  277. * testExportVar method
  278. *
  279. * @return void
  280. */
  281. public function testExportVar()
  282. {
  283. $Controller = new Controller();
  284. $Controller->viewBuilder()->setHelpers(['Html', 'Form']);
  285. $View = $Controller->createView();
  286. $View->int = 2;
  287. $View->float = 1.333;
  288. $View->string = ' ';
  289. $result = Debugger::exportVar($View);
  290. $expected = <<<TEXT
  291. object(Cake\View\View) id:0 {
  292. Html => object(Cake\View\Helper\HtmlHelper) id:1 {}
  293. Form => object(Cake\View\Helper\FormHelper) id:2 {}
  294. int => (int) 2
  295. float => (float) 1.333
  296. string => ' '
  297. [protected] _helpers => object(Cake\View\HelperRegistry) id:3 {}
  298. [protected] Blocks => object(Cake\View\ViewBlock) id:4 {}
  299. [protected] plugin => null
  300. [protected] name => ''
  301. [protected] helpers => [
  302. (int) 0 => 'Html',
  303. (int) 1 => 'Form'
  304. ]
  305. [protected] templatePath => ''
  306. [protected] template => null
  307. [protected] layout => 'default'
  308. [protected] layoutPath => ''
  309. [protected] autoLayout => true
  310. [protected] viewVars => []
  311. [protected] _ext => '.php'
  312. [protected] subDir => ''
  313. [protected] theme => null
  314. [protected] request => object(Cake\Http\ServerRequest) id:5 {}
  315. [protected] response => object(Cake\Http\Response) id:6 {}
  316. [protected] elementCache => 'default'
  317. [protected] _passedVars => [
  318. (int) 0 => 'viewVars',
  319. (int) 1 => 'autoLayout',
  320. (int) 2 => 'helpers',
  321. (int) 3 => 'template',
  322. (int) 4 => 'layout',
  323. (int) 5 => 'name',
  324. (int) 6 => 'theme',
  325. (int) 7 => 'layoutPath',
  326. (int) 8 => 'templatePath',
  327. (int) 9 => 'plugin'
  328. ]
  329. [protected] _defaultConfig => []
  330. [protected] _paths => []
  331. [protected] _pathsForPlugin => []
  332. [protected] _parents => []
  333. [protected] _current => null
  334. [protected] _currentType => ''
  335. [protected] _stack => []
  336. [protected] _viewBlockClass => 'Cake\View\ViewBlock'
  337. [protected] _eventManager => object(Cake\Event\EventManager) id:7 {}
  338. [protected] _eventClass => 'Cake\Event\Event'
  339. [protected] _config => []
  340. [protected] _configInitialized => true
  341. }
  342. TEXT;
  343. $this->assertTextEquals($expected, $result);
  344. $data = [
  345. 1 => 'Index one',
  346. 5 => 'Index five',
  347. ];
  348. $result = Debugger::exportVar($data);
  349. $expected = <<<TEXT
  350. [
  351. (int) 1 => 'Index one',
  352. (int) 5 => 'Index five'
  353. ]
  354. TEXT;
  355. $this->assertTextEquals($expected, $result);
  356. $data = [
  357. 'key' => [
  358. 'value',
  359. ],
  360. ];
  361. $result = Debugger::exportVar($data, 1);
  362. $expected = <<<TEXT
  363. [
  364. 'key' => [
  365. '' => [maximum depth reached]
  366. ]
  367. ]
  368. TEXT;
  369. $this->assertTextEquals($expected, $result);
  370. $data = false;
  371. $result = Debugger::exportVar($data);
  372. $expected = <<<TEXT
  373. false
  374. TEXT;
  375. $this->assertTextEquals($expected, $result);
  376. $file = fopen('php://output', 'w');
  377. fclose($file);
  378. $result = Debugger::exportVar($file);
  379. $this->assertStringContainsString('(resource (closed)) Resource id #', $result);
  380. }
  381. public function testExportVarTypedProperty()
  382. {
  383. $this->skipIf(version_compare(PHP_VERSION, '7.4.0', '<'), 'typed properties require PHP7.4');
  384. // This is gross but was simpler than adding a fixture file.
  385. // phpcs:ignore
  386. eval('class MyClass { private string $field; }');
  387. $obj = new \MyClass();
  388. $out = Debugger::exportVar($obj);
  389. $this->assertTextContains('field => [uninitialized]', $out);
  390. }
  391. /**
  392. * Test exporting various kinds of false.
  393. *
  394. * @return void
  395. */
  396. public function testExportVarZero()
  397. {
  398. $data = [
  399. 'nothing' => '',
  400. 'null' => null,
  401. 'false' => false,
  402. 'szero' => '0',
  403. 'zero' => 0,
  404. ];
  405. $result = Debugger::exportVar($data);
  406. $expected = <<<TEXT
  407. [
  408. 'nothing' => '',
  409. 'null' => null,
  410. 'false' => false,
  411. 'szero' => '0',
  412. 'zero' => (int) 0
  413. ]
  414. TEXT;
  415. $this->assertTextEquals($expected, $result);
  416. }
  417. /**
  418. * test exportVar with cyclic objects.
  419. *
  420. * @return void
  421. */
  422. public function testExportVarCyclicRef()
  423. {
  424. $parent = new stdClass();
  425. $parent->name = 'cake';
  426. $middle = new stdClass();
  427. $parent->child = $middle;
  428. $middle->name = 'php';
  429. $middle->child = $parent;
  430. $result = Debugger::exportVar($parent, 6);
  431. $expected = <<<TEXT
  432. object(stdClass) id:0 {
  433. name => 'cake'
  434. child => object(stdClass) id:1 {
  435. name => 'php'
  436. child => object(stdClass) id:0 {}
  437. }
  438. }
  439. TEXT;
  440. $this->assertTextEquals($expected, $result);
  441. }
  442. /**
  443. * test exportVar with array objects
  444. *
  445. * @return void
  446. */
  447. public function testExportVarSplFixedArray()
  448. {
  449. $subject = new SplFixedArray(2);
  450. $subject[0] = 'red';
  451. $subject[1] = 'blue';
  452. $result = Debugger::exportVar($subject, 6);
  453. $expected = <<<TEXT
  454. object(SplFixedArray) id:0 {
  455. 0 => 'red'
  456. 1 => 'blue'
  457. }
  458. TEXT;
  459. $this->assertTextEquals($expected, $result);
  460. }
  461. /**
  462. * test exportVar with cyclic objects.
  463. *
  464. * @return void
  465. */
  466. public function testExportVarDebugInfo()
  467. {
  468. $form = new Form();
  469. $result = Debugger::exportVar($form, 6);
  470. $this->assertStringContainsString("'_schema' => [", $result, 'Has debuginfo keys');
  471. $this->assertStringContainsString("'_validator' => [", $result);
  472. }
  473. /**
  474. * Test exportVar with an exception during __debugInfo()
  475. *
  476. * @return void
  477. */
  478. public function testExportVarInvalidDebugInfo()
  479. {
  480. $result = Debugger::exportVar(new ThrowsDebugInfo());
  481. $expected = '(unable to export object: from __debugInfo)';
  482. $this->assertTextEquals($expected, $result);
  483. }
  484. /**
  485. * Text exportVarAsNodes()
  486. *
  487. * @return void
  488. */
  489. public function testExportVarAsNodes()
  490. {
  491. $data = [
  492. 1 => 'Index one',
  493. 5 => 'Index five',
  494. ];
  495. $result = Debugger::exportVarAsNodes($data);
  496. $this->assertInstanceOf(NodeInterface::class, $result);
  497. $this->assertCount(2, $result->getChildren());
  498. /** @var \Cake\Error\Debug\ArrayItemNode $item */
  499. $item = $result->getChildren()[0];
  500. $key = new ScalarNode('int', 1);
  501. $this->assertEquals($key, $item->getKey());
  502. $value = new ScalarNode('string', 'Index one');
  503. $this->assertEquals($value, $item->getValue());
  504. $data = [
  505. 'key' => [
  506. 'value',
  507. ],
  508. ];
  509. $result = Debugger::exportVarAsNodes($data, 1);
  510. $item = $result->getChildren()[0];
  511. $nestedItem = $item->getValue()->getChildren()[0];
  512. $expected = new SpecialNode('[maximum depth reached]');
  513. $this->assertEquals($expected, $nestedItem->getValue());
  514. }
  515. /**
  516. * testLog method
  517. *
  518. * @return void
  519. */
  520. public function testLog()
  521. {
  522. Log::setConfig('test', [
  523. 'className' => 'Array',
  524. ]);
  525. Debugger::log('cool');
  526. Debugger::log(['whatever', 'here']);
  527. $messages = Log::engine('test')->read();
  528. $this->assertCount(2, $messages);
  529. $this->assertStringContainsString('DebuggerTest::testLog', $messages[0]);
  530. $this->assertStringContainsString('cool', $messages[0]);
  531. $this->assertStringContainsString('DebuggerTest::testLog', $messages[1]);
  532. $this->assertStringContainsString('[main]', $messages[1]);
  533. $this->assertStringContainsString("'whatever'", $messages[1]);
  534. $this->assertStringContainsString("'here'", $messages[1]);
  535. Log::drop('test');
  536. }
  537. /**
  538. * test log() depth
  539. *
  540. * @return void
  541. */
  542. public function testLogDepth()
  543. {
  544. Log::setConfig('test', [
  545. 'className' => 'Array',
  546. ]);
  547. $val = [
  548. 'test' => ['key' => 'val'],
  549. ];
  550. Debugger::log($val, 'debug', 0);
  551. $messages = Log::engine('test')->read();
  552. $this->assertStringContainsString('DebuggerTest::testLogDepth', $messages[0]);
  553. $this->assertStringContainsString('test', $messages[0]);
  554. $this->assertStringNotContainsString('val', $messages[0]);
  555. }
  556. /**
  557. * testDump method
  558. *
  559. * @return void
  560. */
  561. public function testDump()
  562. {
  563. $var = ['People' => [
  564. [
  565. 'name' => 'joeseph',
  566. 'coat' => 'technicolor',
  567. 'hair_color' => 'brown',
  568. ],
  569. [
  570. 'name' => 'Shaft',
  571. 'coat' => 'black',
  572. 'hair' => 'black',
  573. ],
  574. ]];
  575. ob_start();
  576. Debugger::dump($var);
  577. $result = ob_get_clean();
  578. $open = "\n";
  579. $close = "\n\n";
  580. $expected = <<<TEXT
  581. {$open}[
  582. 'People' => [
  583. (int) 0 => [
  584. 'name' => 'joeseph',
  585. 'coat' => 'technicolor',
  586. 'hair_color' => 'brown'
  587. ],
  588. (int) 1 => [
  589. 'name' => 'Shaft',
  590. 'coat' => 'black',
  591. 'hair' => 'black'
  592. ]
  593. ]
  594. ]{$close}
  595. TEXT;
  596. $this->assertTextEquals($expected, $result);
  597. ob_start();
  598. Debugger::dump($var, 1);
  599. $result = ob_get_clean();
  600. $expected = <<<TEXT
  601. {$open}[
  602. 'People' => [
  603. '' => [maximum depth reached]
  604. ]
  605. ]{$close}
  606. TEXT;
  607. $this->assertTextEquals($expected, $result);
  608. }
  609. /**
  610. * test getInstance.
  611. *
  612. * @return void
  613. */
  614. public function testGetInstance()
  615. {
  616. $result = Debugger::getInstance();
  617. $exporter = $result->getConfig('exportFormatter');
  618. $this->assertInstanceOf(Debugger::class, $result);
  619. $result = Debugger::getInstance(TestDebugger::class);
  620. $this->assertInstanceOf(TestDebugger::class, $result);
  621. $result = Debugger::getInstance();
  622. $this->assertInstanceOf(TestDebugger::class, $result);
  623. $result = Debugger::getInstance(Debugger::class);
  624. $this->assertInstanceOf(Debugger::class, $result);
  625. $result->setConfig('exportFormatter', $exporter);
  626. }
  627. /**
  628. * Test that exportVar() will stop traversing recursive arrays like GLOBALS.
  629. *
  630. * @return void
  631. */
  632. public function testExportVarRecursion()
  633. {
  634. $output = Debugger::exportVar($GLOBALS);
  635. $this->assertMatchesRegularExpression("/'GLOBALS' => \[\s+'' \=\> \[maximum depth reached\]/", $output);
  636. }
  637. /**
  638. * test trace exclude
  639. *
  640. * @return void
  641. */
  642. public function testTraceExclude()
  643. {
  644. $result = Debugger::trace();
  645. $this->assertMatchesRegularExpression('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result);
  646. $result = Debugger::trace([
  647. 'exclude' => ['Cake\Test\TestCase\Error\DebuggerTest::testTraceExclude'],
  648. ]);
  649. $this->assertDoesNotMatchRegularExpression('/^Cake\\\Test\\\TestCase\\\Error\\\DebuggerTest::testTraceExclude/', $result);
  650. }
  651. /**
  652. * Tests that __debugInfo is used when available
  653. *
  654. * @return void
  655. */
  656. public function testDebugInfo()
  657. {
  658. $object = new DebuggableThing();
  659. $result = Debugger::exportVar($object, 2);
  660. $expected = <<<eos
  661. object(TestApp\Error\Thing\DebuggableThing) id:0 {
  662. 'foo' => 'bar'
  663. 'inner' => object(TestApp\Error\Thing\DebuggableThing) id:1 {}
  664. }
  665. eos;
  666. $this->assertSame($expected, $result);
  667. }
  668. /**
  669. * Tests reading the output mask settings.
  670. *
  671. * @return void
  672. */
  673. public function testSetOutputMask()
  674. {
  675. Debugger::setOutputMask(['password' => '[**********]']);
  676. $this->assertEquals(['password' => '[**********]'], Debugger::outputMask());
  677. Debugger::setOutputMask(['serial' => 'XXXXXX']);
  678. $this->assertEquals(['password' => '[**********]', 'serial' => 'XXXXXX'], Debugger::outputMask());
  679. Debugger::setOutputMask([], false);
  680. $this->assertEquals([], Debugger::outputMask());
  681. }
  682. /**
  683. * Test configure based output mask configuration
  684. *
  685. * @return void
  686. */
  687. public function testConfigureOutputMask()
  688. {
  689. Configure::write('Debugger.outputMask', ['wow' => 'xxx']);
  690. Debugger::getInstance(TestDebugger::class);
  691. Debugger::getInstance(Debugger::class);
  692. $result = Debugger::exportVar(['wow' => 'pass1234']);
  693. $this->assertStringContainsString('xxx', $result);
  694. $this->assertStringNotContainsString('pass1234', $result);
  695. }
  696. /**
  697. * Tests the masking of an array key.
  698. *
  699. * @return void
  700. */
  701. public function testMaskArray()
  702. {
  703. Debugger::setOutputMask(['password' => '[**********]']);
  704. $result = Debugger::exportVar(['password' => 'pass1234']);
  705. $expected = "['password'=>'[**********]']";
  706. $this->assertSame($expected, preg_replace('/\s+/', '', $result));
  707. }
  708. /**
  709. * Tests the masking of an array key.
  710. *
  711. * @return void
  712. */
  713. public function testMaskObject()
  714. {
  715. Debugger::setOutputMask(['password' => '[**********]']);
  716. $object = new SecurityThing();
  717. $result = Debugger::exportVar($object);
  718. $expected = "object(TestApp\\Error\\Thing\\SecurityThing)id:0{password=>'[**********]'}";
  719. $this->assertSame($expected, preg_replace('/\s+/', '', $result));
  720. }
  721. /**
  722. * test testPrintVar()
  723. *
  724. * @return void
  725. */
  726. public function testPrintVar()
  727. {
  728. ob_start();
  729. Debugger::printVar('this-is-a-test', ['file' => __FILE__, 'line' => __LINE__], false);
  730. $result = ob_get_clean();
  731. $expectedText = <<<EXPECTED
  732. %s (line %d)
  733. ########## DEBUG ##########
  734. 'this-is-a-test'
  735. ###########################
  736. EXPECTED;
  737. $expected = sprintf($expectedText, Debugger::trimPath(__FILE__), __LINE__ - 9);
  738. $this->assertSame($expected, $result);
  739. ob_start();
  740. $value = '<div>this-is-a-test</div>';
  741. Debugger::printVar($value, ['file' => __FILE__, 'line' => __LINE__], true);
  742. $result = ob_get_clean();
  743. $this->assertStringContainsString('&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039;', $result);
  744. ob_start();
  745. Debugger::printVar('<div>this-is-a-test</div>', ['file' => __FILE__, 'line' => __LINE__], true);
  746. $result = ob_get_clean();
  747. $expected = <<<EXPECTED
  748. <div class="cake-debug-output cake-debug" style="direction:ltr">
  749. <span><strong>%s</strong> (line <strong>%d</strong>)</span>
  750. <div class="cake-dbg"><span class="cake-dbg-string">&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039;</span></div>
  751. </div>
  752. EXPECTED;
  753. $expected = sprintf($expected, Debugger::trimPath(__FILE__), __LINE__ - 8);
  754. $this->assertSame($expected, $result);
  755. ob_start();
  756. Debugger::printVar('<div>this-is-a-test</div>', [], true);
  757. $result = ob_get_clean();
  758. $expected = <<<EXPECTED
  759. <div class="cake-debug-output cake-debug" style="direction:ltr">
  760. <div class="cake-dbg"><span class="cake-dbg-string">&#039;&lt;div&gt;this-is-a-test&lt;/div&gt;&#039;</span></div>
  761. </div>
  762. EXPECTED;
  763. $expected = sprintf($expected, Debugger::trimPath(__FILE__), __LINE__ - 8);
  764. $this->assertSame($expected, $result);
  765. ob_start();
  766. Debugger::printVar('<div>this-is-a-test</div>', ['file' => __FILE__, 'line' => __LINE__], false);
  767. $result = ob_get_clean();
  768. $expected = <<<EXPECTED
  769. %s (line %d)
  770. ########## DEBUG ##########
  771. '<div>this-is-a-test</div>'
  772. ###########################
  773. EXPECTED;
  774. $expected = sprintf($expected, Debugger::trimPath(__FILE__), __LINE__ - 9);
  775. $this->assertSame($expected, $result);
  776. ob_start();
  777. Debugger::printVar('<div>this-is-a-test</div>');
  778. $result = ob_get_clean();
  779. $expected = <<<EXPECTED
  780. ########## DEBUG ##########
  781. '<div>this-is-a-test</div>'
  782. ###########################
  783. EXPECTED;
  784. $expected = sprintf($expected, Debugger::trimPath(__FILE__), __LINE__ - 8);
  785. $this->assertSame($expected, $result);
  786. }
  787. /**
  788. * test formatHtmlMessage
  789. *
  790. * @return void
  791. */
  792. public function testFormatHtmlMessage()
  793. {
  794. $output = Debugger::formatHtmlMessage('Some `code` to `replace`');
  795. $this->assertSame('Some <code>code</code> to <code>replace</code>', $output);
  796. $output = Debugger::formatHtmlMessage("Some `co\nde` to `replace`\nmore");
  797. $this->assertSame("Some <code>co<br />\nde</code> to <code>replace</code><br />\nmore", $output);
  798. $output = Debugger::formatHtmlMessage("Some `code` to <script>alert(\"test\")</script>\nmore");
  799. $this->assertSame(
  800. "Some <code>code</code> to &lt;script&gt;alert(&quot;test&quot;)&lt;/script&gt;<br />\nmore",
  801. $output
  802. );
  803. }
  804. /**
  805. * test adding invalid editor
  806. *
  807. * @return void
  808. */
  809. public function testAddEditorInvalid()
  810. {
  811. $this->expectException(RuntimeException::class);
  812. Debugger::addEditor('nope', ['invalid']);
  813. }
  814. /**
  815. * test choosing an unknown editor
  816. *
  817. * @return void
  818. */
  819. public function testSetEditorInvalid()
  820. {
  821. $this->expectException(RuntimeException::class);
  822. Debugger::setEditor('nope');
  823. }
  824. /**
  825. * test choosing a default editor
  826. *
  827. * @return void
  828. */
  829. public function testSetEditorPredefined()
  830. {
  831. Debugger::setEditor('phpstorm');
  832. Debugger::setEditor('macvim');
  833. Debugger::setEditor('sublime');
  834. Debugger::setEditor('emacs');
  835. // No exceptions raised.
  836. $this->assertTrue(true);
  837. }
  838. /**
  839. * Test configure based editor setup
  840. *
  841. * @return void
  842. */
  843. public function testConfigureEditor()
  844. {
  845. Configure::write('Debugger.editor', 'emacs');
  846. Debugger::getInstance(TestDebugger::class);
  847. Debugger::getInstance(Debugger::class);
  848. $result = Debugger::editorUrl('file.php', 123);
  849. $this->assertStringContainsString('emacs://', $result);
  850. }
  851. /**
  852. * test using a valid editor.
  853. *
  854. * @return void
  855. */
  856. public function testEditorUrlValid()
  857. {
  858. Debugger::addEditor('open', 'open://{file}:{line}');
  859. Debugger::setEditor('open');
  860. $this->assertSame('open://test.php:123', Debugger::editorUrl('test.php', 123));
  861. }
  862. /**
  863. * test using a valid editor.
  864. *
  865. * @return void
  866. */
  867. public function testEditorUrlClosure()
  868. {
  869. Debugger::addEditor('open', function (string $file, int $line) {
  870. return "${file}/${line}";
  871. });
  872. Debugger::setEditor('open');
  873. $this->assertSame('test.php/123', Debugger::editorUrl('test.php', 123));
  874. }
  875. }