DebuggerTest.php 28 KB

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