aboutsummaryrefslogtreecommitdiffstats
path: root/tests/phpunit/unit/includes/exception/MWExceptionHandlerTest.php
blob: 39ff45d7f2dff017e0d9f79420896bdc0140ffbe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
<?php

use Wikimedia\NormalizedException\NormalizedException;
use Wikimedia\TestingAccessWrapper;

/**
 * @covers MWExceptionHandler
 * @author Antoine Musso
 */
class MWExceptionHandlerTest extends \MediaWikiUnitTestCase {

	private $oldSettingValue;

	protected function setUp(): void {
		parent::setUp();
		// We need to make sure the traces have function arguments as we're testing
		// their handling.
		$this->oldSettingValue = ini_set( 'zend.exception_ignore_args', 0 );
	}

	protected function tearDown(): void {
		TestingAccessWrapper::newFromClass( MWExceptionHandler::class )
			->logExceptionBacktrace = true;
		ini_set( 'zend.exception_ignore_args', $this->oldSettingValue );
		parent::tearDown();
	}

	/**
	 * Test end-to-end formatting of an exception, such as used by LogstashFormatter.
	 *
	 * @see MWExceptionHandler::prettyPrintTrace
	 */
	public function testTraceFormatting() {
		try {
			$dummy = new TestThrowerDummy();
			$startLine = __LINE__ + 1;
			$dummy->main();
		} catch ( Exception $e ) {
		}

		$startFile = __FILE__;
		$dummyFile = TestThrowerDummy::getFile();
		$dummyClass = TestThrowerDummy::class;
		$expected = <<<TEXT
from {$dummyFile}(17)
#0 {$dummyFile}(13): {$dummyClass}->getQuux()
#1 {$dummyFile}(9): {$dummyClass}->getBar()
#2 {$dummyFile}(5): {$dummyClass}->doFoo()
#3 {$startFile}($startLine): {$dummyClass}->main()
TEXT;

		// Trim up until our call()
		$trace = MWExceptionHandler::getRedactedTraceAsString( $e );
		$actual = implode( "\n", array_slice( explode( "\n", trim( $trace ) ), 0, 5 ) );

		$this->assertEquals( $expected, $actual );
	}

	public function testGetRedactedTrace() {
		$refvar = 'value';
		try {
			$array = [ 'a', 'b' ];
			$object = (object)[];
			self::helperThrowForArgs( $array, $object, $refvar );
		} catch ( Exception $e ) {
		}

		// Make sure our stack trace contains an array and an object passed to
		// some function in the stacktrace. Else, we cannot assert the trace
		// redaction achieved its job.
		$trace = $e->getTrace();
		$hasObject = false;
		$hasArray = false;
		foreach ( $trace as $frame ) {
			if ( !isset( $frame['args'] ) ) {
				continue;
			}
			foreach ( $frame['args'] as $arg ) {
				$hasObject = $hasObject || is_object( $arg );
				$hasArray = $hasArray || is_array( $arg );
			}

			if ( $hasObject && $hasArray ) {
				break;
			}
		}
		$this->assertTrue( $hasObject, "The stacktrace has a frame with an object parameter" );
		$this->assertTrue( $hasArray, "The stacktrace has a frame with an array parameter" );

		// Now we redact the trace.. and verify there are no longer any arrays or objects
		$redacted = MWExceptionHandler::getRedactedTrace( $e );

		foreach ( $redacted as $frame ) {
			if ( !isset( $frame['args'] ) ) {
				continue;
			}
			foreach ( $frame['args'] as $arg ) {
				$this->assertIsNotArray( $arg );
				$this->assertIsNotObject( $arg );
			}
		}

		$this->assertEquals( 'value', $refvar, 'Reference variable' );
	}

	public function testGetLogNormalMessage() {
		$this->assertSame(
			'[{reqId}] {exception_url}   Exception: message',
			MWExceptionHandler::getLogNormalMessage( new Exception( 'message' ) )
		);
		$this->assertSame(
			'[{reqId}] {exception_url}   message',
			MWExceptionHandler::getLogNormalMessage( new ErrorException( 'message' ) )
		);
		$this->assertSame(
			'[{reqId}] {exception_url}   ' . NormalizedException::class . ': {placeholder}',
			MWExceptionHandler::getLogNormalMessage(
				new NormalizedException( '{placeholder}', [ 'placeholder' => 'message' ] )
			)
		);
	}

	public function testGetLogContext() {
		$e = new Exception( 'message' );
		$context = MWExceptionHandler::getLogContext( $e );
		$this->assertSame( $e, $context['exception'] );

		$e = new NormalizedException( 'message', [ 'param' => 'value' ] );
		$context = MWExceptionHandler::getLogContext( $e );
		$this->assertSame( $e, $context['exception'] );
		$this->assertSame( 'value', $context['param'] );
	}

	/**
	 * @dataProvider provideJsonSerializedKeys
	 * @param string $expectedKeyType Type expected as returned by gettype()
	 * @param string $exClass An exception class (ie: Exception, MWException)
	 * @param string $key Name of the key to validate in the serialized JSON
	 */
	public function testJsonserializeexceptionKeys( $expectedKeyType, $exClass, $key ) {
		$json = json_decode(
			MWExceptionHandler::jsonSerializeException( new $exClass() )
		);
		$this->assertObjectHasProperty( $key, $json );
		$this->assertSame( $expectedKeyType, gettype( $json->$key ), "Type of the '$key' key" );
	}

	/**
	 * Each case provides: [ type, exception class, key name ]
	 */
	public static function provideJsonSerializedKeys() {
		foreach ( [ Exception::class, MWException::class ] as $exClass ) {
			yield [ 'string', $exClass, 'id' ];
			yield [ 'string', $exClass, 'file' ];
			yield [ 'integer', $exClass, 'line' ];
			yield [ 'string', $exClass, 'message' ];
			yield [ 'NULL', $exClass, 'url' ];
			// Backtrace only enabled with wgLogExceptionBacktrace = true
			yield [ 'array', $exClass, 'backtrace' ];
		}
	}

	/**
	 * Given wgLogExceptionBacktrace is true
	 * then serialized exception must have a backtrace
	 */
	public function testJsonserializeexceptionBacktracingEnabled() {
		TestingAccessWrapper::newFromClass( MWExceptionHandler::class )
			->logExceptionBacktrace = true;
		$json = json_decode(
			MWExceptionHandler::jsonSerializeException( new Exception() )
		);
		$this->assertObjectHasProperty( 'backtrace', $json );
	}

	/**
	 * Given wgLogExceptionBacktrace is false
	 * then serialized exception must not have a backtrace
	 */
	public function testJsonserializeexceptionBacktracingDisabled() {
		TestingAccessWrapper::newFromClass( MWExceptionHandler::class )
			->logExceptionBacktrace = false;
		$json = json_decode(
			MWExceptionHandler::jsonSerializeException( new Exception() )
		);
		$this->assertObjectNotHasProperty( 'backtrace', $json );
	}

	/**
	 * Helper function for testGetRedactedTrace
	 *
	 * @param array $a
	 * phpcs:disable MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
	 * @param object $b
	 * @param mixed &$c
	 * @throws Exception
	 */
	protected static function helperThrowForArgs( array $a, object $b, &$c ) {
		throw new Exception();
	}
}