Debian Codegraph @

tests/phpunit/MediaWikiTestCaseTrait.php

raw symbols SCIP
1 <?php
2
3 use MediaWiki\Debug\MWDebug;
4 use MediaWiki\HookContainer\HookContainer;
5 use MediaWiki\HookContainer\StaticHookRegistry;
6 use MediaWiki\Message\Message;
7 use MediaWiki\Tests\Unit\FakeQqxMessageLocalizer;
8 use PHPUnit\Framework\Constraint\Constraint;
9 use PHPUnit\Framework\ExpectationFailedException;
10 use PHPUnit\Framework\MockObject\MockObject;
11 use Psr\Container\ContainerInterface;
12 use SebastianBergmann\Comparator\ComparisonFailure;
13 use Wikimedia\ObjectFactory\ObjectFactory;
14 use Wikimedia\Services\NoSuchServiceException;
15 use Wikimedia\Timestamp\ConvertibleTimestamp;
16
17 /**
18 * For code common to both MediaWikiUnitTestCase and MediaWikiIntegrationTestCase.
19 */
20 trait MediaWikiTestCaseTrait {
21 /** @var int|null */
22 private $originalPhpErrorFilter;
23
24 /** @var array */
25 private $expectedDeprecations = [];
26
27 /** @var array */
28 private $actualDeprecations = [];
29
30 /**
31 * Returns a PHPUnit constraint that matches (with `===`) anything other than a fixed set of values.
32 * This can be used to list accepted values, e.g.
33 * $mock->expects( $this->never() )->method( $this->anythingBut( 'foo', 'bar' ) );
34 * which will throw if any unexpected method is called.
35 *
36 * @param mixed ...$values Values that are not matched
37 * @return Constraint
38 */
39 protected function anythingBut( ...$values ) {
40 if ( !in_array( '__destruct', $values, true ) ) {
41 // Ensure that __destruct is always included. PHPUnit will fail very hard with no
42 // useful output if __destruct ends up being called (T280780).
43 $values[] = '__destruct';
44 }
45 return $this->logicalNot( $this->logicalOr(
46 ...array_map( [ $this, 'identicalTo' ], $values )
47 ) );
48 }
49
50 /**
51 * Return a PHPUnit mock that is expected to never have any methods called on it.
52 *
53 * @psalm-template RealInstanceType of object
54 *
55 * @psalm-param class-string<RealInstanceType> $type
56 * @psalm-param list<string> $allow Methods to allow
57 *
58 * @param string $type
59 * @param string[] $allow Methods to allow
60 *
61 * @return MockObject&RealInstanceType
62 */
63 protected function createNoOpMock( $type, $allow = [] ) {
64 $mock = $this->createMock( $type );
65 $mock->expects( $this->never() )->method( $this->anythingBut( '__debugInfo', '__destruct', ...$allow ) );
66 return $mock;
67 }
68
69 /**
70 * Return a PHPUnit mock that is expected to never have any methods called on it.
71 *
72 * @psalm-template RealInstanceType of object
73 *
74 * @psalm-param class-string<RealInstanceType> $type
75 * @psalm-param list<string> $allow Methods to allow
76 *
77 * @param string $type
78 * @param string[] $allow methods to allow
79 *
80 * @return MockObject&RealInstanceType
81 */
82 protected function createNoOpAbstractMock( $type, $allow = [] ) {
83 $mock = $this->getMockBuilder( $type )
84 ->disableOriginalConstructor()
85 ->disableOriginalClone()
86 ->disableArgumentCloning()
87 ->disallowMockingUnknownTypes()
88 ->getMockForAbstractClass();
89 $mock->expects( $this->never() )->method( $this->anythingBut( '__destruct', ...$allow ) );
90 return $mock;
91 }
92
93 /**
94 * Create an ObjectFactory with no dependencies and no services
95 *
96 * @return ObjectFactory
97 */
98 protected function createSimpleObjectFactory() {
99 $serviceContainer = $this->createMock( ContainerInterface::class );
100 $serviceContainer->method( 'has' )->willReturn( false );
101 $serviceContainer->method( 'get' )->willReturnCallback(
102 static function ( $serviceName ) {
103 throw new NoSuchServiceException( $serviceName );
104 }
105 );
106 return new ObjectFactory( $serviceContainer );
107 }
108
109 /**
110 * Create an initially empty HookContainer with an empty service container
111 * attached. Register only the hooks specified in the parameter.
112 *
113 * @param callable[] $hooks
114 * @return HookContainer
115 */
116 protected function createHookContainer( $hooks = [] ) {
117 $hookContainer = new HookContainer(
118 new StaticHookRegistry(),
119 $this->createSimpleObjectFactory()
120 );
121 foreach ( $hooks as $name => $callback ) {
122 $hookContainer->register( $name, $callback );
123 }
124 return $hookContainer;
125 }
126
127 /**
128 * Skip the test if not running the necessary php version
129 *
130 * @since 1.42 (also backported to 1.39.8, 1.40.4 and 1.41.2)
131 *
132 * @param string $op
133 * @param string $version
134 */
135 protected function markTestSkippedIfPhp( $op, $version ) {
136 if ( version_compare( PHP_VERSION, $version, $op ) ) {
137 $this->markTestSkipped( "PHP $version isn't supported for this test" );
138 }
139 }
140
141 /**
142 * Don't throw a warning if $function is deprecated and called later
143 *
144 * @since 1.19
145 *
146 * @param string $function
147 */
148 public function hideDeprecated( $function ) {
149 // Construct a regex that will match the message generated by
150 // wfDeprecated() if it is called for the specified function.
151 $this->filterDeprecated( '/Use of ' . preg_quote( $function, '/' ) . ' /' );
152 }
153
154 /**
155 * Don't throw a warning for deprecation messages matching a regex.
156 *
157 * @since 1.35
158 *
159 * @param string $regex
160 */
161 public function filterDeprecated( $regex ) {
162 MWDebug::filterDeprecationForTest( $regex );
163 }
164
165 /**
166 * Expect a deprecation notice, but suppress it and continue operation so we can test that the
167 * deprecated functionality works as intended for compatibility.
168 *
169 * @since 1.39
170 *
171 * @param string $regex Deprecation message that must be triggered.
172 */
173 public function expectDeprecationAndContinue( string $regex ): void {
174 $this->expectedDeprecations[] = $regex;
175 MWDebug::filterDeprecationForTest( $regex, function () use ( $regex ): void {
176 $this->actualDeprecations[] = $regex;
177 } );
178 }
179
180 /**
181 * @after
182 */
183 public function checkExpectedDeprecationsOnTearDown(): void {
184 if ( $this->expectedDeprecations ) {
185 $this->assertSame( [],
186 array_diff( $this->expectedDeprecations, $this->actualDeprecations ),
187 'Expected deprecation warning(s) were not emitted' );
188 }
189 }
190
191 /**
192 * Check whether file contains given data.
193 * @param string $fileName
194 * @param string $actualData
195 * @param bool $createIfMissing If true, and file does not exist, create it with given data
196 * and skip the test.
197 * @param string $msg
198 * @since 1.30
199 */
200 protected function assertFileContains(
201 $fileName,
202 $actualData,
203 $createIfMissing = false,
204 $msg = ''
205 ) {
206 if ( $createIfMissing ) {
207 if ( !is_file( $fileName ) ) {
208 file_put_contents( $fileName, $actualData );
209 $this->markTestSkipped( "Data file $fileName does not exist" );
210 }
211 } else {
212 $this->assertFileExists( $fileName );
213 }
214 $this->assertEquals( file_get_contents( $fileName ), $actualData, $msg );
215 }
216
217 /**
218 * Assert that an associative array contains the subset of an expected array.
219 *
220 * The internal key order does not matter.
221 * Values are compared with strict equality.
222 *
223 * @since 1.41
224 * @param array $expected
225 * @param array $actual
226 * @param string $message
227 */
228 protected function assertArrayContains(
229 array $expected,
230 array $actual,
231 $message = ''
232 ) {
233 $patched = array_replace_recursive( $actual, $expected );
234
235 ksort( $patched );
236 ksort( $actual );
237 $result = ( $actual === $patched );
238
239 if ( !$result ) {
240 $comparisonFailure = new ComparisonFailure(
241 $patched,
242 $actual,
243 var_export( $patched, true ),
244 var_export( $actual, true )
245 );
246
247 $failureDescription = 'Failed asserting that array contains the expected submap.';
248 if ( $message != '' ) {
249 $failureDescription = $message . "\n" . $failureDescription;
250 }
251
252 throw new ExpectationFailedException(
253 $failureDescription,
254 $comparisonFailure
255 );
256 } else {
257 $this->assertTrue( true, $message );
258 }
259 }
260
261 /**
262 * Assert that two arrays are equal. By default, this means that both arrays need to hold
263 * the same set of values. Using additional arguments, order and associated key can also
264 * be set as relevant.
265 *
266 * @since 1.20
267 *
268 * @param array $expected
269 * @param array $actual
270 * @param bool $ordered If the order of the values should match
271 * @param bool $named If the keys should match
272 * @param string $message
273 */
274 public function assertArrayEquals(
275 array $expected, array $actual, $ordered = false, $named = false, string $message = ''
276 ) {
277 if ( !$ordered ) {
278 $this->objectAssociativeSort( $expected );
279 $this->objectAssociativeSort( $actual );
280 }
281
282 if ( !$named ) {
283 $expected = array_values( $expected );
284 $actual = array_values( $actual );
285 }
286
287 $this->assertEquals( $expected, $actual, $message );
288 }
289
290 /**
291 * Does an associative sort that works for objects.
292 *
293 * @since 1.20
294 *
295 * @param array &$array
296 */
297 protected function objectAssociativeSort( array &$array ) {
298 uasort(
299 $array,
300 static function ( $a, $b ) {
301 return serialize( $a ) <=> serialize( $b );
302 }
303 );
304 }
305
306 /**
307 * @before
308 */
309 protected function phpErrorFilterSetUp() {
310 $this->originalPhpErrorFilter = error_reporting();
311 }
312
313 /**
314 * @after
315 */
316 protected function phpErrorFilterTearDown() {
317 $phpErrorFilter = error_reporting();
318
319 if ( $phpErrorFilter !== $this->originalPhpErrorFilter ) {
320 error_reporting( $this->originalPhpErrorFilter );
321 $message = "PHP error_reporting setting found dirty."
322 . " Did you forget AtEase::restoreWarnings?";
323 $this->fail( $message );
324 }
325 }
326
327 /**
328 * Re-enable any disabled deprecation warnings and allow same deprecations to be thrown
329 * multiple times in different tests, so the PHPUnit expectDeprecation() works.
330 *
331 * @after
332 */
333 protected function mwDebugTearDown() {
334 MWDebug::clearLog();
335 MWDebug::clearDeprecationFilters();
336 }
337
338 /**
339 * Reset any fake timestamps so that they don't mess with any other tests.
340 *
341 * @since 1.37 before that, integration tests had it reset in
342 * MediaWikiIntegrationTestCase::mediaWikiTearDown, and unit tests didn't at all
343 *
344 * @after
345 */
346 protected function fakeTimestampTearDown() {
347 ConvertibleTimestamp::setFakeTime( null );
348 }
349
350 /**
351 * Check that no fake timestamp is set before the tests (e.g. in a test provider).
352 * They should be only set in the tests and cleared by fakeTimestampTearDown().
353 *
354 * @since 1.43
355 * @before
356 */
357 protected function fakeTimestampSetUp() {
358 $realTime = time();
359 $maybeFakeTime = ConvertibleTimestamp::time();
360 if ( abs( $maybeFakeTime - $realTime ) > 1 ) {
361 $this->assertTrue( false, "Someone set a fake timestamp ($maybeFakeTime) " .
362 "and did not clean it up. This will cause confusing test failures." );
363 }
364 }
365
366 /**
367 * @param string $text
368 * @param array $params
369 * @return Message|MockObject
370 * @since 1.35
371 */
372 protected function getMockMessage( string $text = '', array $params = [] ) {
373 // Warning, don't use PHPUnit's logicalOr with strings as that's extremely slow!
374 $oneOf = fn ( string ...$methods ) => $this->logicalOr(
375 ...array_map( [ $this, 'identicalTo' ], $methods )
376 );
377
378 $msg = $this->createMock( Message::class );
379 $msg->method( $oneOf( '__toString', 'escaped', 'getKey', 'parse', 'parseAsBlock',
380 'plain', 'text', 'toString' ) )->willReturn( $text );
381 $msg->method( 'getParams' )->willReturn( $params );
382 $msg->method( $oneOf( 'inContentLanguage', 'inLanguage', 'numParams', 'params',
383 'rawParams', 'setContext', 'title', 'useDatabase' ) )->willReturnSelf();
384 $msg->method( 'exists' )->willReturn( true );
385 return $msg;
386 }
387
388 private function failStatus( StatusValue $status, $reason, $message = '' ) {
389 $reason = $message === '' ? $reason : "$message\n$reason";
390 $this->fail( "$reason\n$status" );
391 }
392
393 protected function assertStatusOK( StatusValue $status, $message = '' ) {
394 if ( !$status->isOK() ) {
395 $errors = $status->splitByErrorType()[0];
396 $this->failStatus( $errors, 'Status should be OK', $message );
397 } else {
398 $this->addToAssertionCount( 1 );
399 }
400 }
401
402 protected function assertStatusGood( StatusValue $status, $message = '' ) {
403 if ( !$status->isGood() ) {
404 $this->failStatus( $status, 'Status should be Good', $message );
405 } else {
406 $this->addToAssertionCount( 1 );
407 }
408 }
409
410 protected function assertStatusNotOK( StatusValue $status, $message = '' ) {
411 if ( $status->isOK() ) {
412 $this->failStatus( $status, 'Status should not be OK', $message );
413 } else {
414 $this->addToAssertionCount( 1 );
415 }
416 }
417
418 protected function assertStatusNotGood( StatusValue $status, $message = '' ) {
419 if ( $status->isGood() ) {
420 $this->failStatus( $status, 'Status should not be Good', $message );
421 } else {
422 $this->addToAssertionCount( 1 );
423 }
424 }
425
426 protected function assertStatusMessage( string $messageKey, StatusValue $status, $message = '' ) {
427 if ( !$status->hasMessage( $messageKey ) ) {
428 $this->failStatus( $status, "Status should have message $messageKey", $message );
429 } else {
430 $this->addToAssertionCount( 1 );
431 }
432 }
433
434 /**
435 * Check if the status contains exactly the same messages as the expected status.
436 *
437 * Prefer using assertStatusError / assertStatusWarning unless you really need to check the
438 * parameters, count and order of the messages too.
439 *
440 * This method does not compare isGood() vs isOK() or the values of the statuses, use dedicated
441 * assertion methods for that.
442 *
443 * Note that some differences between the internals of the objects are allowed (such as their own
444 * class, use of MessageSpecifier vs string keys, use of strings vs other scalars for parameters).
445 *
446 * @param StatusValue $expected
447 * @param StatusValue $actual
448 * @param string $message
449 */
450 protected function assertStatusMessagesExactly( StatusValue $expected, StatusValue $actual, $message = '' ) {
451 $localizer = new FakeQqxMessageLocalizer();
452
453 foreach ( [ 'error', 'warning' ] as $type ) {
454 foreach (
455 array_map( null, $expected->getMessages( $type ), $actual->getMessages( $type ) )
456 as [ $expectedMsg, $actualMsg ]
457 ) {
458 if (
459 $expectedMsg === null || $actualMsg === null ||
460 $localizer->msg( $expectedMsg )->text() !== $localizer->msg( $actualMsg )->text()
461 ) {
462 $this->failStatus( $actual, "Status messages should be exactly like: $expected\nActual:", $message );
463 }
464 }
465 }
466
467 $this->addToAssertionCount( 1 );
468 }
469
470 protected function assertStatusValue( $expected, StatusValue $status, $message = 'Status value' ) {
471 $this->assertEquals( $expected, $status->getValue(), $message );
472 }
473
474 protected function assertStatusError( string $messageKey, StatusValue $status, $message = '' ) {
475 $this->assertStatusNotOK( $status, $message );
476 $this->assertStatusMessage( $messageKey, $status, $message );
477 }
478
479 protected function assertStatusWarning( string $messageKey, StatusValue $status, $message = '' ) {
480 $this->assertStatusNotGood( $status, $message );
481 $this->assertStatusOK( $status, $message );
482 $this->assertStatusMessage( $messageKey, $status, $message );
483 }
484
485 /**
486 * Put each HTML element on its own line and then equals() the results
487 *
488 * Use for nicely formatting of PHPUnit diff output when comparing very
489 * simple HTML
490 *
491 * @since 1.20
492 * @since 1.39 available in MediaWikiUnitTestCase
493 *
494 * @param string $expected HTML on oneline
495 * @param string $actual HTML on oneline
496 * @param string $msg Optional message
497 */
498 protected function assertHTMLEquals( $expected, $actual, $msg = '' ) {
499 $expected = str_replace( '>', ">\n", $expected );
500 $actual = str_replace( '>', ">\n", $actual );
501
502 $this->assertEquals( $expected, $actual, $msg );
503 }
504
505 /**
506 * This method allows you to assert that the given callback emits a PHP error. It is a PHPUnit 10 compatible
507 * replacement for expectNotice(), expectWarning(), expectError(), and the other methods deprecated in
508 * https://github.com/sebastianbergmann/phpunit/issues/5062.
509 *
510 * @param int $errorLevel
511 * @param callable $callback
512 * @param string|null $msg String that must be contained in the error message
513 */
514 protected function expectPHPError(
515 int $errorLevel,
516 callable $callback,
517 ?string $msg = null
518 ): void {
519 try {
520 $errorEmitted = false;
521 set_error_handler( function ( $_, $actualMsg ) use ( $msg, &$errorEmitted ) {
522 if ( $msg !== null ) {
523 $this->assertStringContainsString( $msg, $actualMsg );
524 }
525 $errorEmitted = true;
526 }, $errorLevel );
527 $callback();
528 $this->assertTrue( $errorEmitted, "No PHP error was emitted." );
529 } finally {
530 restore_error_handler();
531 }
532 }
533 }