Debian Codegraph @

tests/phpunit/unit/includes/exception/MWExceptionHandlerTest.php

raw symbols SCIP
1 <?php
2
3 use Wikimedia\NormalizedException\NormalizedException;
4 use Wikimedia\TestingAccessWrapper;
5
6 /**
7 * @covers \MWExceptionHandler
8 * @author Antoine Musso
9 */
10 class MWExceptionHandlerTest extends \MediaWikiUnitTestCase {
11
12 /** @var int */
13 private $oldSettingValue;
14
15 protected function setUp(): void {
16 parent::setUp();
17 // We need to make sure the traces have function arguments as we're testing
18 // their handling.
19 $this->oldSettingValue = ini_set( 'zend.exception_ignore_args', 0 );
20 }
21
22 protected function tearDown(): void {
23 TestingAccessWrapper::newFromClass( MWExceptionHandler::class )
24 ->logExceptionBacktrace = true;
25 ini_set( 'zend.exception_ignore_args', $this->oldSettingValue );
26 parent::tearDown();
27 }
28
29 /**
30 * Test end-to-end formatting of an exception, such as used by LogstashFormatter.
31 *
32 * @see MWExceptionHandler::prettyPrintTrace
33 */
34 public function testTraceFormatting() {
35 try {
36 $dummy = new TestThrowerDummy();
37 $startLine = __LINE__ + 1;
38 $dummy->main();
39 } catch ( Exception $e ) {
40 }
41
42 $startFile = __FILE__;
43 $dummyFile = TestThrowerDummy::getFile();
44 $dummyClass = TestThrowerDummy::class;
45 $expected = <<<TEXT
46 from {$dummyFile}(17)
47 #0 {$dummyFile}(13): {$dummyClass}->getQuux()
48 #1 {$dummyFile}(9): {$dummyClass}->getBar()
49 #2 {$dummyFile}(5): {$dummyClass}->doFoo()
50 #3 {$startFile}($startLine): {$dummyClass}->main()
51 TEXT;
52
53 // Trim up until our call()
54 $trace = MWExceptionHandler::getRedactedTraceAsString( $e );
55 $actual = implode( "\n", array_slice( explode( "\n", trim( $trace ) ), 0, 5 ) );
56
57 $this->assertEquals( $expected, $actual );
58 }
59
60 public function testGetRedactedTrace() {
61 $refvar = 'value';
62 try {
63 $array = [ 'a', 'b' ];
64 $object = (object)[];
65 self::helperThrowForArgs( $array, $object, $refvar );
66 } catch ( Exception $e ) {
67 }
68
69 // Make sure our stack trace contains an array and an object passed to
70 // some function in the stacktrace. Else, we cannot assert the trace
71 // redaction achieved its job.
72 $trace = $e->getTrace();
73 $hasObject = false;
74 $hasArray = false;
75 foreach ( $trace as $frame ) {
76 if ( !isset( $frame['args'] ) ) {
77 continue;
78 }
79 foreach ( $frame['args'] as $arg ) {
80 $hasObject = $hasObject || is_object( $arg );
81 $hasArray = $hasArray || is_array( $arg );
82 }
83
84 if ( $hasObject && $hasArray ) {
85 break;
86 }
87 }
88 $this->assertTrue( $hasObject, "The stacktrace has a frame with an object parameter" );
89 $this->assertTrue( $hasArray, "The stacktrace has a frame with an array parameter" );
90
91 // Now we redact the trace.. and verify there are no longer any arrays or objects
92 $redacted = MWExceptionHandler::getRedactedTrace( $e );
93
94 foreach ( $redacted as $frame ) {
95 if ( !isset( $frame['args'] ) ) {
96 continue;
97 }
98 foreach ( $frame['args'] as $arg ) {
99 $this->assertIsNotArray( $arg );
100 $this->assertIsNotObject( $arg );
101 }
102 }
103
104 $this->assertEquals( 'value', $refvar, 'Reference variable' );
105 }
106
107 public function testGetLogNormalMessage() {
108 $this->assertSame(
109 '[{reqId}] {exception_url} Exception: message',
110 MWExceptionHandler::getLogNormalMessage( new Exception( 'message' ) )
111 );
112 $this->assertSame(
113 '[{reqId}] {exception_url} message',
114 MWExceptionHandler::getLogNormalMessage( new ErrorException( 'message' ) )
115 );
116 $this->assertSame(
117 '[{reqId}] {exception_url} ' . NormalizedException::class . ': {placeholder}',
118 MWExceptionHandler::getLogNormalMessage(
119 new NormalizedException( '{placeholder}', [ 'placeholder' => 'message' ] )
120 )
121 );
122 }
123
124 public function testGetLogContext() {
125 $e = new Exception( 'message' );
126 $context = MWExceptionHandler::getLogContext( $e );
127 $this->assertSame( $e, $context['exception'] );
128
129 $e = new NormalizedException( 'message', [ 'param' => 'value' ] );
130 $context = MWExceptionHandler::getLogContext( $e );
131 $this->assertSame( $e, $context['exception'] );
132 $this->assertSame( 'value', $context['param'] );
133 }
134
135 /**
136 * @dataProvider provideJsonSerializedKeys
137 * @param string $expectedKeyType Type expected as returned by get_debug_type()
138 * @param string $exClass An exception class (ie: Exception, MWException)
139 * @param string $key Name of the key to validate in the serialized JSON
140 */
141 public function testJsonserializeexceptionKeys( $expectedKeyType, $exClass, $key ) {
142 $json = json_decode(
143 MWExceptionHandler::jsonSerializeException( new $exClass() )
144 );
145 $this->assertObjectHasProperty( $key, $json );
146 $this->assertSame( $expectedKeyType, get_debug_type( $json->$key ), "Type of the '$key' key" );
147 }
148
149 /**
150 * Each case provides: [ type, exception class, key name ]
151 */
152 public static function provideJsonSerializedKeys() {
153 foreach ( [ Exception::class, MWException::class ] as $exClass ) {
154 yield [ 'string', $exClass, 'id' ];
155 yield [ 'string', $exClass, 'file' ];
156 yield [ 'int', $exClass, 'line' ];
157 yield [ 'string', $exClass, 'message' ];
158 yield [ 'null', $exClass, 'url' ];
159 // Backtrace only enabled with wgLogExceptionBacktrace = true
160 yield [ 'array', $exClass, 'backtrace' ];
161 }
162 }
163
164 /**
165 * Given wgLogExceptionBacktrace is true
166 * then serialized exception must have a backtrace
167 */
168 public function testJsonserializeexceptionBacktracingEnabled() {
169 TestingAccessWrapper::newFromClass( MWExceptionHandler::class )
170 ->logExceptionBacktrace = true;
171 $json = json_decode(
172 MWExceptionHandler::jsonSerializeException( new Exception() )
173 );
174 $this->assertObjectHasProperty( 'backtrace', $json );
175 }
176
177 /**
178 * Given wgLogExceptionBacktrace is false
179 * then serialized exception must not have a backtrace
180 */
181 public function testJsonserializeexceptionBacktracingDisabled() {
182 TestingAccessWrapper::newFromClass( MWExceptionHandler::class )
183 ->logExceptionBacktrace = false;
184 $json = json_decode(
185 MWExceptionHandler::jsonSerializeException( new Exception() )
186 );
187 $this->assertObjectNotHasProperty( 'backtrace', $json );
188 }
189
190 /**
191 * Helper function for testGetRedactedTrace
192 *
193 * @param array $a
194 * phpcs:disable MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
195 * @param object $b
196 * @param mixed &$c
197 * @throws Exception
198 */
199 protected static function helperThrowForArgs( array $a, object $b, &$c ) {
200 throw new Exception();
201 }
202 }