DebuggerTest.php 24 KB

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