Debian Codegraph @

tests/phpunit/includes/Status/StatusFormatterTest.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Context\RequestContext;
4 use MediaWiki\Language\RawMessage;
5 use MediaWiki\Message\Message;
6 use MediaWiki\Status\StatusFormatter;
7 use MediaWiki\User\User;
8 use Psr\Log\Test\TestLogger;
9 use Wikimedia\Message\MessageValue;
10 use Wikimedia\TestingAccessWrapper;
11
12 /**
13 * @covers \MediaWiki\Status\StatusFormatter
14 */
15 class StatusFormatterTest extends MediaWikiLangTestCase {
16
17 private ?TestLogger $logger;
18
19 protected function setUp(): void {
20 parent::setUp();
21
22 $this->logger = new TestLogger();
23 }
24
25 protected function tearDown(): void {
26 parent::tearDown();
27 $this->logger = null;
28 }
29
30 private function getFormatter( $lang = 'en' ) {
31 $localizer = new class() implements MessageLocalizer {
32 public $lang;
33
34 public function msg( $key, ...$params ) {
35 return wfMessage( $key, ...$params )->inLanguage( $this->lang );
36 }
37 };
38
39 $cache = $this->createNoOpMock( MessageCache::class, [ 'parse' ] );
40 $cache->method( 'parse' )->willReturnCallback(
41 static function ( $text ) {
42 $text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5 );
43 return "<p>" . trim( $text ) . "\n</p>";
44 }
45 );
46
47 $localizer->lang = $lang;
48
49 return new StatusFormatter( $localizer, $cache, $this->logger );
50 }
51
52 /**
53 * @dataProvider provideCleanParams
54 */
55 public function testCleanParams( $cleanCallback, $params, $expected, $unexpected ) {
56 $status = new StatusValue();
57 $status->warning( 'ok', ...$params );
58
59 $formatter = $this->getFormatter( 'qqx' );
60 $options = [ 'cleanCallback' => $cleanCallback ];
61
62 $wikitext = $formatter->getWikiText( $status, $options );
63 $this->assertStringContainsString( $expected, $wikitext );
64 $this->assertStringNotContainsString( $unexpected, $wikitext );
65
66 $html = $formatter->getHTML( $status, $options );
67 $this->assertStringContainsString( $expected, $html );
68 $this->assertStringNotContainsString( $unexpected, $html );
69 }
70
71 public static function provideCleanParams() {
72 $cleanCallback = static function ( $value ) {
73 return 'xxx';
74 };
75
76 return [
77 [ false, [ 'secret' ], 'secret', 'xxx' ],
78 [ $cleanCallback, [ 'secret' ], 'xxx', 'secret' ],
79 ];
80 }
81
82 /**
83 * @dataProvider provideGetWikiTextAndHtml
84 */
85 public function testGetWikiText(
86 StatusValue $status, $wikitext, $wrappedWikitext, $html, $wrappedHtml
87 ) {
88 $formatter = $this->getFormatter();
89 $this->assertEquals( $wikitext, $formatter->getWikiText( $status ) );
90
91 $this->assertEquals(
92 $wrappedWikitext,
93 $formatter->getWikiText(
94 $status,
95 [
96 'shortContext' => 'wrap-short',
97 'longContext' => 'wrap-long',
98 'lang' => 'qqx',
99 ]
100 )
101 );
102 }
103
104 /**
105 * @dataProvider provideGetWikiTextAndHtml
106 */
107 public function testGetHtml(
108 StatusValue $status,
109 $wikitext,
110 $wrappedWikitext,
111 $html,
112 $wrappedHtml,
113 ?string $expectedWarning = null
114 ) {
115 $formatter = $this->getFormatter();
116 $this->assertEquals( $html, $formatter->getHTML( $status ) );
117
118 $this->assertEquals(
119 $wrappedHtml,
120 $formatter->getHTML(
121 $status,
122 [
123 'shortContext' => 'wrap-short',
124 'longContext' => 'wrap-long',
125 'lang' => 'qqx',
126 ]
127 )
128 );
129
130 if ( $expectedWarning !== null ) {
131 $this->assertTrue( $this->logger->hasWarningThatContains( $expectedWarning ) );
132 } else {
133 $this->assertFalse( $this->logger->hasWarningRecords() );
134 }
135 }
136
137 /**
138 * @return array Array of arrays with values;
139 * 0 => status object
140 * 1 => expected string (with no context)
141 */
142 public static function provideGetWikiTextAndHtml() {
143 $testCases = [];
144
145 $testCases['GoodStatus'] = [
146 new StatusValue(),
147 "Internal error: MediaWiki\Status\StatusFormatter::getWikiText called for a good result, this is incorrect&#10;",
148 "(wrap-short: (internalerror_info: MediaWiki\Status\StatusFormatter::getWikiText called for a good result, " .
149 "this is incorrect&#10;))",
150 "<p>Internal error: MediaWiki\Status\StatusFormatter::getWikiText called for a good result, this is incorrect\n</p>",
151 "<p>(wrap-short: (internalerror_info: MediaWiki\Status\StatusFormatter::getWikiText called for a good result, " .
152 "this is incorrect\n))\n</p>",
153 'MediaWiki\Status\StatusFormatter::getWikiText called for a good result, this is incorrect'
154 ];
155
156 $status = new StatusValue();
157 $status->setOK( false );
158 $testCases['GoodButNoError'] = [
159 $status,
160 "Internal error: MediaWiki\Status\StatusFormatter::getWikiText: Invalid result object: no error text but not OK&#10;",
161 "(wrap-short: (internalerror_info: MediaWiki\Status\StatusFormatter::getWikiText: Invalid result object: " .
162 "no error text but not OK&#10;))",
163 "<p>Internal error: MediaWiki\Status\StatusFormatter::getWikiText: Invalid result object: no error text but not OK\n</p>",
164 "<p>(wrap-short: (internalerror_info: MediaWiki\Status\StatusFormatter::getWikiText: Invalid result object: " .
165 "no error text but not OK\n))\n</p>",
166 'MediaWiki\Status\StatusFormatter::getWikiText: Invalid result object: no error text but not OK'
167 ];
168
169 $status = new StatusValue();
170 $status->warning( 'fooBar!' );
171 $testCases['1StringWarning'] = [
172 $status,
173 "⧼fooBar!⧽",
174 "(wrap-short: (fooBar!))",
175 "<p>⧼fooBar!⧽\n</p>",
176 "<p>(wrap-short: (fooBar!))\n</p>",
177 ];
178
179 $status = new StatusValue();
180 $status->warning( 'fooBar!' );
181 $status->warning( 'fooBar2!' );
182 $testCases['2StringWarnings'] = [
183 $status,
184 "<ul>\n<li>\n⧼fooBar!⧽\n</li>\n<li>\n⧼fooBar2!⧽\n</li>\n</ul>\n",
185 "(wrap-long: <ul>\n<li>\n(fooBar!)\n</li>\n<li>\n(fooBar2!)\n</li>\n</ul>\n)",
186 "<p><ul>\n<li>\n⧼fooBar!⧽\n</li>\n<li>\n⧼fooBar2!⧽\n</li>\n</ul>\n</p>",
187 "<p>(wrap-long: <ul>\n<li>\n(fooBar!)\n</li>\n<li>\n(fooBar2!)\n</li>\n</ul>\n)\n</p>",
188 ];
189
190 $status = new StatusValue();
191 $status->warning( new Message( 'fooBar!', [ 'foo', 'bar' ] ) );
192 $testCases['1MessageWarning'] = [
193 $status,
194 "⧼fooBar!⧽",
195 "(wrap-short: (fooBar!: foo, bar))",
196 "<p>⧼fooBar!⧽\n</p>",
197 "<p>(wrap-short: (fooBar!: foo, bar))\n</p>",
198 ];
199
200 $status = new StatusValue();
201 $status->warning( new Message( 'fooBar!', [ 'foo', 'bar' ] ) );
202 $status->warning( new Message( 'fooBar2!' ) );
203 $testCases['2MessageWarnings'] = [
204 $status,
205 "<ul>\n<li>\n⧼fooBar!⧽\n</li>\n<li>\n⧼fooBar2!⧽\n</li>\n</ul>\n",
206 "(wrap-long: <ul>\n<li>\n(fooBar!: foo, bar)\n</li>\n<li>\n(fooBar2!)\n</li>\n</ul>\n)",
207 "<p><ul>\n<li>\n⧼fooBar!⧽\n</li>\n<li>\n⧼fooBar2!⧽\n</li>\n</ul>\n</p>",
208 "<p>(wrap-long: <ul>\n<li>\n(fooBar!: foo, bar)\n</li>\n<li>\n(fooBar2!)\n</li>\n</ul>\n)\n</p>",
209 ];
210
211 return $testCases;
212 }
213
214 private static function sanitizedMessageParams( Message $message ) {
215 return array_map( static function ( $p ) {
216 return $p instanceof Message
217 ? [
218 'key' => $p->getKey(),
219 'params' => self::sanitizedMessageParams( $p ),
220 'lang' => $p->getLanguage()->getCode(),
221 ]
222 : $p;
223 }, $message instanceof RawMessage ? $message->getParamsOfRawMessage() : $message->getParams() );
224 }
225
226 private static function sanitizedMessageKey( Message $message ) {
227 return $message instanceof RawMessage ? $message->getTextOfRawMessage() : $message->getKey();
228 }
229
230 /**
231 * @dataProvider provideGetMessage
232 */
233 public function testGetMessage(
234 StatusValue $status,
235 $expectedParams,
236 $expectedKey,
237 $expectedWrapper,
238 ?string $expectedWarning = null
239 ) {
240 $formatter = $this->getFormatter();
241 $message = $formatter->getMessage( $status, [ 'lang' => 'qqx' ] );
242 $this->assertInstanceOf( Message::class, $message );
243 $this->assertEquals( $expectedParams, self::sanitizedMessageParams( $message ),
244 'Message::getParams' );
245 $this->assertEquals( $expectedKey, self::sanitizedMessageKey( $message ), 'Message::getKey' );
246
247 $message = $formatter->getMessage(
248 $status,
249 [
250 'shortContext' => 'wrapper-short',
251 'longContext' => 'wrapper-long',
252 ]
253 );
254 $this->assertInstanceOf( Message::class, $message );
255 $this->assertEquals( $expectedWrapper, $message->getKey(), 'Message::getKey with wrappers' );
256 $this->assertCount( 1, $message->getParams(), 'Message::getParams with wrappers' );
257
258 $message = $formatter->getMessage( $status, [ 'shortContext' => 'wrapper' ] );
259 $this->assertInstanceOf( Message::class, $message );
260 $this->assertEquals( 'wrapper', $message->getKey(), 'Message::getKey with wrappers' );
261 $this->assertCount( 1, $message->getParams(), 'Message::getParams with wrappers' );
262
263 $message = $formatter->getMessage( $status, [ 'longContext' => 'wrapper' ] );
264 $this->assertInstanceOf( Message::class, $message );
265 $this->assertEquals( 'wrapper', $message->getKey(), 'Message::getKey with wrappers' );
266 $this->assertCount( 1, $message->getParams(), 'Message::getParams with wrappers' );
267
268 if ( $expectedWarning !== null ) {
269 $this->assertTrue( $this->logger->hasWarningThatContains( $expectedWarning ) );
270 } else {
271 $this->assertFalse( $this->logger->hasWarningRecords() );
272 }
273 }
274
275 /**
276 * @return array Array of arrays with values;
277 * 0 => status object
278 * 1 => expected Message parameters (with no context)
279 * 2 => expected Message key
280 */
281 public static function provideGetMessage() {
282 $testCases = [];
283
284 $testCases['GoodStatus'] = [
285 new StatusValue(),
286 [ "MediaWiki\Status\StatusFormatter::getMessage called for a good result, this is incorrect&#10;" ],
287 'internalerror_info',
288 'wrapper-short',
289 'MediaWiki\Status\StatusFormatter::getMessage called for a good result, this is incorrect'
290 ];
291
292 $status = new StatusValue();
293 $status->setOK( false );
294 $testCases['GoodButNoError'] = [
295 $status,
296 [ "MediaWiki\Status\StatusFormatter::getMessage: Invalid result object: no error text but not OK&#10;" ],
297 'internalerror_info',
298 'wrapper-short',
299 'MediaWiki\Status\StatusFormatter::getMessage: Invalid result object: no error text but not OK'
300 ];
301
302 $status = new StatusValue();
303 $status->warning( 'fooBar!' );
304 $testCases['1StringWarning'] = [
305 $status,
306 [],
307 'fooBar!',
308 'wrapper-short'
309 ];
310
311 $status = new StatusValue();
312 $status->warning( 'fooBar!' );
313 $status->warning( 'fooBar2!' );
314 $testCases[ '2StringWarnings' ] = [
315 $status,
316 [
317 [ 'key' => 'fooBar!', 'params' => [], 'lang' => 'qqx' ],
318 [ 'key' => 'fooBar2!', 'params' => [], 'lang' => 'qqx' ]
319 ],
320 "* \$1\n* \$2",
321 'wrapper-long'
322 ];
323
324 $status = new StatusValue();
325 $status->warning( new Message( 'fooBar!', [ 'foo', 'bar' ] ) );
326 $testCases['1MessageWarning'] = [
327 $status,
328 [ 'foo', 'bar' ],
329 'fooBar!',
330 'wrapper-short'
331 ];
332
333 $status = new StatusValue();
334 $status->warning( new MessageValue( 'fooBar!', [ 'foo', 'bar' ] ) );
335 $status->warning( new MessageValue( 'fooBar2!' ) );
336 $testCases['2MessageWarnings'] = [
337 $status,
338 [
339 [ 'key' => 'fooBar!', 'params' => [ 'foo', 'bar' ], 'lang' => 'qqx' ],
340 [ 'key' => 'fooBar2!', 'params' => [], 'lang' => 'qqx' ]
341 ],
342 "* \$1\n* \$2",
343 'wrapper-long'
344 ];
345
346 return $testCases;
347 }
348
349 /**
350 * @dataProvider provideGetPsr3MessageAndContext
351 */
352 public function testGetPsr3MessageAndContext(
353 array $errors,
354 string $expectedMessage,
355 array $expectedContext
356 ) {
357 // set up a rawmessage_2 message, which is just like rawmessage but doesn't trigger
358 // the special-casing in StatusFormatter::getPsr3MessageAndContext
359 $this->setTemporaryHook( 'MessageCacheFetchOverrides', static function ( &$overrides ) {
360 $overrides['rawmessage_2'] = 'rawmessage';
361 }, false );
362
363 $status = new StatusValue();
364 foreach ( $errors as $error ) {
365 $status->error( ...$error );
366 }
367
368 $formatter = $this->getFormatter();
369
370 [ $actualMessage, $actualContext ] = $formatter->getPsr3MessageAndContext( $status );
371 $this->assertSame( $expectedMessage, $actualMessage );
372 $this->assertSame( $expectedContext, $actualContext );
373 }
374
375 public static function provideGetPsr3MessageAndContext() {
376 return [
377 // parameters to StatusValue::error() calls as array of arrays; expected message; expected context
378 'no errors' => [
379 [],
380 "Internal error: MediaWiki\Status\StatusFormatter::getWikiText called for a good result, this is incorrect&#10;",
381 [],
382 ],
383 // make sure that the rawmessage_2 hack works as the following tests rely on it
384 'rawmessage_2' => [
385 [ [ 'rawmessage_2', 'foo' ] ],
386 '{parameter1}',
387 [ 'parameter1' => 'foo' ],
388 ],
389 'two errors' => [
390 [ [ 'rawmessage_2', 'foo' ], [ 'rawmessage_2', 'bar' ] ],
391 "<ul>\n<li>\nfoo\n</li>\n<li>\nbar\n</li>\n</ul>\n",
392 [],
393 ],
394 'unknown subclass' => [
395 // phpcs:ignore Squiz.WhiteSpace.ScopeClosingBrace.ContentBefore
396 [ [ new class( 'rawmessage_2', [ 'foo' ] ) extends Message {} ] ],
397 'foo',
398 [],
399 ],
400 'non-scalar parameter' => [
401 [ [ new Message( 'rawmessage_2', [ new Message( 'rawmessage_2', [ 'foo' ] ) ] ) ] ],
402 'foo',
403 [],
404 ],
405 'one parameter' => [
406 [ [ 'apiwarn-invalidtitle', 'foo' ] ],
407 '"{parameter1}" is not a valid title.',
408 [ 'parameter1' => 'foo' ],
409 ],
410 'multiple parameters' => [
411 [ [ 'api-exception-trace', 'foo', 'bar', 'baz', 'boom' ] ],
412 "{parameter1} at {parameter2}({parameter3})\n{parameter4}",
413 [ 'parameter1' => 'foo', 'parameter2' => 'bar', 'parameter3' => 'baz', 'parameter4' => 'boom' ],
414 ],
415 'formatted parameter' => [
416 [ [ 'apiwarn-invalidtitle', Message::numParam( 1000000 ) ] ],
417 '"{parameter1}" is not a valid title.',
418 [ 'parameter1' => 1000000 ],
419 ],
420 'rawmessage' => [
421 [ [ 'rawmessage', 'foo' ] ],
422 'foo',
423 [],
424 ],
425 'RawMessage' => [
426 [ [ new RawMessage( 'foo $1 baz', [ 'bar' ] ) ] ],
427 'foo {parameter1} baz',
428 [ 'parameter1' => 'bar' ],
429 ],
430 ];
431 }
432
433 public function testGetErrorMessage() {
434 $formatter = $this->getFormatter();
435 /** @var StatusFormatter $formatter */
436 $formatter = TestingAccessWrapper::newFromObject( $formatter );
437 $key = 'foo';
438 $params = [ 'bar' ];
439
440 $message = $formatter->getErrorMessage( [ $key, ...$params ] );
441 $this->assertInstanceOf( Message::class, $message );
442 $this->assertEquals( $key, $message->getKey() );
443 $this->assertEquals( $params, $message->getParams() );
444 }
445
446 public function testGetErrorMessageComplexParam() {
447 $formatter = $this->getFormatter();
448 /** @var StatusFormatter $formatter */
449 $formatter = TestingAccessWrapper::newFromObject( $formatter );
450 $key = 'foo';
451 $params = [ 'bar', Message::numParam( 5 ) ];
452
453 $message = $formatter->getErrorMessage( [ $key, ...$params ] );
454 $this->assertInstanceOf( Message::class, $message );
455 $this->assertEquals( $key, $message->getKey() );
456 $this->assertEquals( $params, $message->getParams() );
457 }
458
459 public function testGetErrorMessageArray() {
460 $formatter = $this->getFormatter();
461 $formatter = TestingAccessWrapper::newFromObject( $formatter );
462 $key = 'foo';
463 $params = [ 'bar' ];
464
465 /** @var Message[] $messageArray */
466 $messageArray = $formatter->getErrorMessageArray(
467 [
468 [ $key, ...$params ],
469 [ $key, ...$params ],
470 ]
471 );
472
473 $this->assertIsArray( $messageArray );
474 $this->assertCount( 2, $messageArray );
475 foreach ( $messageArray as $message ) {
476 $this->assertInstanceOf( Message::class, $message );
477 $this->assertEquals( $key, $message->getKey() );
478 $this->assertEquals( $params, $message->getParams() );
479 }
480 }
481
482 public function testUserLanguageNotLoaded() {
483 // Confirm that the user language is not loaded from the database when
484 // formatting an error in a specific language
485 $this->getServiceContainer()->disableService( 'UserOptionsLookup' );
486 $context = RequestContext::getMain();
487 $user = new User;
488 $user->setName( 'Test' );
489 $context->setUser( $user );
490 $this->getServiceContainer()
491 ->getFormatterFactory()
492 ->getStatusFormatter( RequestContext::getMain() )
493 ->getWikiText(
494 StatusValue::newFatal( 'apierror-badquery' ),
495 [ 'lang' => 'en' ]
496 );
497 $this->assertTrue( true );
498 }
499 }