Page MenuHomePhorge

No OneTemporary

Size
92 KB
Referenced Files
None
Subscribers
None
diff --git a/tests/phpunit/includes/Output/OutputPageTest.php b/tests/phpunit/includes/Output/OutputPageTest.php
index fe5e1dbaddc..df1fb8eecc9 100644
--- a/tests/phpunit/includes/Output/OutputPageTest.php
+++ b/tests/phpunit/includes/Output/OutputPageTest.php
@@ -948,6 +948,9 @@ class OutputPageTest extends MediaWikiIntegrationTestCase {
}
$title = $titles[0];
+ if ( is_array( $title ) ) {
+ $title = $this->makeMockTitle( ...$title );
+ }
$query = $queries[0];
$str = OutputPage::buildBacklinkSubtitle( $title, $query )->text();
@@ -966,8 +969,11 @@ class OutputPageTest extends MediaWikiIntegrationTestCase {
*/
public function testAddBacklinkSubtitle( $titles, $queries, $contains, $notContains ) {
$op = $this->newInstance();
- foreach ( $titles as $i => $unused ) {
- $op->addBacklinkSubtitle( $titles[$i], $queries[$i] );
+ foreach ( $titles as $i => $title ) {
+ if ( is_array( $title ) ) {
+ $title = $this->makeMockTitle( ...$title );
+ }
+ $op->addBacklinkSubtitle( $title, $queries[$i] );
}
$str = $op->getSubtitle();
@@ -981,8 +987,8 @@ class OutputPageTest extends MediaWikiIntegrationTestCase {
}
}
- public function provideBacklinkSubtitle() {
- $page1title = $this->makeMockTitle( 'Page 1', [ 'redirect' => true ] );
+ public static function provideBacklinkSubtitle() {
+ $page1title = [ 'Page 1', [ 'redirect' => true ] ];
$page1ref = new PageReferenceValue( NS_MAIN, 'Page 1', PageReference::LOCAL );
$row = [
diff --git a/tests/phpunit/includes/ResourceLoader/StartUpModuleTest.php b/tests/phpunit/includes/ResourceLoader/StartUpModuleTest.php
index d212eb47413..4d087a5231a 100644
--- a/tests/phpunit/includes/ResourceLoader/StartUpModuleTest.php
+++ b/tests/phpunit/includes/ResourceLoader/StartUpModuleTest.php
@@ -687,16 +687,11 @@ mw.loader.register([
*
* @see provideGetModuleRegistrations
*/
- public function provideGetModuleRegistrationsProduction() {
+ public static function provideGetModuleRegistrationsProduction() {
yield 'Version falls back gracefully if getModuleContent throws' => [ [
'modules' => [
'test.fail' => [
- 'factory' => function () {
- $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
- ->onlyMethods( [ 'getModuleContent' ] )->getMock();
- $mock->method( 'getModuleContent' )->willThrowException( new Exception );
- return $mock;
- }
+ 'moduleContent' => 'throw',
]
],
'out' => 'mw.loader.addSource({"local":"/w/load.php"});' . "\n"
@@ -706,17 +701,7 @@ mw.loader.register([
yield 'Version falls back gracefully if getDefinitionSummary throws' => [ [
'modules' => [
'test.fail' => [
- 'factory' => function () {
- $mock = $this->getMockBuilder( ResourceLoaderTestModule::class )
- ->onlyMethods( [
- 'enableModuleContentVersion',
- 'getDefinitionSummary'
- ] )
- ->getMock();
- $mock->method( 'enableModuleContentVersion' )->willReturn( false );
- $mock->method( 'getDefinitionSummary' )->willThrowException( new Exception );
- return $mock;
- }
+ 'definitionSummary' => 'throw',
]
],
'out' => 'mw.loader.addSource({"local":"/w/load.php"});' . "\n"
@@ -731,6 +716,27 @@ mw.loader.register([
public function testGetModuleRegistrationsProduction( array $case ) {
$this->clearHook( 'ResourceLoaderModifyEmbeddedSourceUrls' );
+ foreach ( $case['modules'] as $module => &$definition ) {
+ $mockBuilder = $this->getMockBuilder( ResourceLoaderTestModule::class );
+ if ( isset( $definition['moduleContent'] ) ) {
+ $mock = $mockBuilder->onlyMethods( [ 'getModuleContent' ] )->getMock();
+ $mock->method( 'getModuleContent' )->willThrowException( new Exception );
+ } elseif ( isset( $definition['definitionSummary'] ) ) {
+ $mock = $mockBuilder->onlyMethods( [
+ 'enableModuleContentVersion',
+ 'getDefinitionSummary'
+ ] )
+ ->getMock();
+ $mock->method( 'enableModuleContentVersion' )->willReturn( false );
+ $mock->method( 'getDefinitionSummary' )->willThrowException( new Exception );
+ }
+ $definition = [
+ 'factory' => static function () use ( $mock ) {
+ return $mock;
+ },
+ ];
+ }
+
$context = $this->getResourceLoaderContext( [ 'debug' => 'false' ] );
$rl = $context->getResourceLoader();
$rl->register( $case['modules'] );
diff --git a/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php b/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php
index 4ddd3d7f3a5..658e33d89b1 100644
--- a/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php
+++ b/tests/phpunit/includes/Storage/DerivedPageDataUpdaterTest.php
@@ -876,7 +876,7 @@ class DerivedPageDataUpdaterTest extends MediaWikiIntegrationTestCase {
return $rev;
}
- public function provideIsReusableFor() {
+ public static function provideIsReusableFor() {
$title = PageIdentityValue::localIdentity( 1234, NS_MAIN, __CLASS__ );
$user1 = new UserIdentityValue( 111, 'Alice' );
@@ -894,12 +894,12 @@ class DerivedPageDataUpdaterTest extends MediaWikiIntegrationTestCase {
$update2 = new RevisionSlotsUpdate();
$update2->modifyContent( SlotRecord::MAIN, $content2 );
- $rev1 = $this->makeRevision( $title, $update1, $user1, 'rev1', 11 );
- $rev1b = $this->makeRevision( $title, $update1b, $user1, 'rev1', 11 );
+ $rev1 = [ $title, $update1, $user1, 'rev1', 11 ];
+ $rev1b = [ $title, $update1b, $user1, 'rev1', 11 ];
- $rev2 = $this->makeRevision( $title, $update2, $user1, 'rev2', 12 );
- $rev2x = $this->makeRevision( $title, $update2, $user2, 'rev2', 12 );
- $rev2y = $this->makeRevision( $title, $update2, $user1, 'rev2', 122 );
+ $rev2 = [ $title, $update2, $user1, 'rev2', 12 ];
+ $rev2x = [ $title, $update2, $user2, 'rev2', 12 ];
+ $rev2y = [ $title, $update2, $user1, 'rev2', 122 ];
yield 'any' => [
'$prepUser' => null,
@@ -1019,10 +1019,10 @@ class DerivedPageDataUpdaterTest extends MediaWikiIntegrationTestCase {
*/
public function testIsReusableFor(
?UserIdentity $prepUser,
- ?MutableRevisionRecord $prepRevision,
+ ?array $prepRevision,
?RevisionSlotsUpdate $prepUpdate,
?UserIdentity $forUser,
- ?RevisionRecord $forRevision,
+ ?array $forRevision,
?RevisionSlotsUpdate $forUpdate,
$forParent,
$isReusable
@@ -1034,7 +1034,10 @@ class DerivedPageDataUpdaterTest extends MediaWikiIntegrationTestCase {
}
if ( $prepRevision ) {
- $updater->prepareUpdate( $prepRevision );
+ $updater->prepareUpdate( $this->makeRevision( ...$prepRevision ) );
+ }
+ if ( $forRevision ) {
+ $forRevision = $this->makeRevision( ...$forRevision );
}
$this->assertSame(
diff --git a/tests/phpunit/includes/block/BlockManagerTest.php b/tests/phpunit/includes/block/BlockManagerTest.php
index 7b4239a3f1d..a99af804e09 100644
--- a/tests/phpunit/includes/block/BlockManagerTest.php
+++ b/tests/phpunit/includes/block/BlockManagerTest.php
@@ -401,6 +401,22 @@ class BlockManagerTest extends MediaWikiIntegrationTestCase {
public function testTrackBlockWithCookie( $options, $expected ) {
$this->overrideConfigValue( MainConfigNames::CookiePrefix, '' );
+ if ( is_int( $options['block'] ) ) {
+ $options['block'] = $this->getTrackableBlock( $options['block'] );
+ } elseif ( is_array( $options['block'] ) ) {
+ $blocks = [];
+ foreach ( $options['block'] as $block ) {
+ if ( is_int( $block ) ) {
+ $blocks[] = $this->getTrackableBlock( $block );
+ } elseif ( $block === 'system' ) {
+ $blocks[] = new SystemBlock();
+ }
+ }
+ $options['block'] = new CompositeBlock( [
+ 'originalBlocks' => $blocks
+ ] );
+ }
+
$request = new FauxRequest();
if ( $options['cookieSet'] ) {
$request->setCookie( 'BlockID', 'the value does not matter' );
@@ -428,13 +444,13 @@ class BlockManagerTest extends MediaWikiIntegrationTestCase {
$this->assertEquals( $expected['value'], $response->getCookie( 'BlockID' ) );
}
- public function provideTrackBlockWithCookie() {
+ public static function provideTrackBlockWithCookie() {
$blockId = 123;
return [
'Block cookie is already set; there is a trackable block' => [
[
'cookieSet' => true,
- 'block' => $this->getTrackableBlock( $blockId ),
+ 'block' => $blockId,
],
[
'count' => 1,
@@ -465,7 +481,7 @@ class BlockManagerTest extends MediaWikiIntegrationTestCase {
'Block cookie is not yet set; there is a trackable block' => [
[
'cookieSet' => false,
- 'block' => $this->getTrackableBlock( $blockId ),
+ 'block' => $blockId,
],
[
'count' => 1,
@@ -475,12 +491,10 @@ class BlockManagerTest extends MediaWikiIntegrationTestCase {
'Block cookie is not yet set; there is a composite block with a trackable block' => [
[
'cookieSet' => false,
- 'block' => new CompositeBlock( [
- 'originalBlocks' => [
- new SystemBlock(),
- $this->getTrackableBlock( $blockId ),
- ]
- ] ),
+ 'block' => [
+ 'system',
+ $blockId,
+ ],
],
[
'count' => 1,
@@ -490,12 +504,10 @@ class BlockManagerTest extends MediaWikiIntegrationTestCase {
'Block cookie is not yet set; there is a composite block but no trackable block' => [
[
'cookieSet' => false,
- 'block' => new CompositeBlock( [
- 'originalBlocks' => [
- new SystemBlock(),
- new SystemBlock(),
- ]
- ] ),
+ 'block' => [
+ 'system',
+ 'system',
+ ],
],
[
'count' => 0,
diff --git a/tests/phpunit/includes/filerepo/FileBackendDBRepoWrapperTest.php b/tests/phpunit/includes/filerepo/FileBackendDBRepoWrapperTest.php
index ac53f5f44e8..a45c3f20d5f 100644
--- a/tests/phpunit/includes/filerepo/FileBackendDBRepoWrapperTest.php
+++ b/tests/phpunit/includes/filerepo/FileBackendDBRepoWrapperTest.php
@@ -15,77 +15,61 @@ class FileBackendDBRepoWrapperTest extends MediaWikiIntegrationTestCase {
* @covers \MediaWiki\FileRepo\FileBackendDBRepoWrapper::getBackendPaths
*/
public function testGetBackendPaths(
- $mocks,
$latest,
- $dbReadsExpected,
+ $dbReadsExpectedArray,
$dbReturnValue,
$originalPath,
- $expectedBackendPath,
- $message ) {
- [ $dbMock, $backendMock, $wrapperMock ] = $mocks;
+ $expectedBackendPath
+ ) {
+ [ $dbMock, $backendMock, $wrapperMock ] = $this->getMocks();
- $dbMock->expects( $dbReadsExpected )
- ->method( 'selectField' )
- ->willReturn( $dbReturnValue );
- $dbMock->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $dbMock ) );
+ foreach ( $dbReadsExpectedArray as $message => $dbReadsExpected ) {
+ $dbMock->expects( $dbReadsExpected )
+ ->method( 'selectField' )
+ ->willReturn( $dbReturnValue );
+ $dbMock->method( 'newSelectQueryBuilder' )->willReturnCallback( static fn () => new SelectQueryBuilder( $dbMock ) );
- $newPaths = $wrapperMock->getBackendPaths( [ $originalPath ], $latest );
+ $newPaths = $wrapperMock->getBackendPaths( [ $originalPath ], $latest );
- $this->assertEquals(
- $expectedBackendPath,
- $newPaths[0],
- $message );
+ $this->assertEquals(
+ $expectedBackendPath,
+ $newPaths[0],
+ $message
+ );
+ }
}
- public function getBackendPathsProvider() {
+ public static function getBackendPathsProvider() {
$prefix = 'mwstore://' . self::BACKEND_NAME . '/' . self::REPO_NAME;
- $mocksForCaching = $this->getMocks();
return [
[
- $mocksForCaching,
- false,
- $this->once(),
- '96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- $prefix . '-public/f/o/foobar.jpg',
- $prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- 'Public path translated correctly',
- ],
- [
- $mocksForCaching,
false,
- $this->never(),
+ [ 'Public path translated correctly' => self::once(), 'LRU cache leveraged' => self::never() ],
'96246614d75ba1703bdfd5d7660bb57407aaf5d9',
$prefix . '-public/f/o/foobar.jpg',
$prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- 'LRU cache leveraged',
],
[
- $this->getMocks(),
true,
- $this->once(),
+ [ 'Latest obtained' => self::once() ],
'96246614d75ba1703bdfd5d7660bb57407aaf5d9',
$prefix . '-public/f/o/foobar.jpg',
$prefix . '-original/9/6/2/96246614d75ba1703bdfd5d7660bb57407aaf5d9',
- 'Latest obtained',
],
[
- $this->getMocks(),
true,
- $this->never(),
+ [ 'Deleted path translated correctly' => self::never() ],
'96246614d75ba1703bdfd5d7660bb57407aaf5d9',
$prefix . '-deleted/f/o/foobar.jpg',
$prefix . '-original/f/o/o/foobar',
- 'Deleted path translated correctly',
],
[
- $this->getMocks(),
true,
- $this->once(),
+ [ 'Path left untouched if no sha1 can be found' => self::once() ],
null,
$prefix . '-public/b/a/baz.jpg',
$prefix . '-public/b/a/baz.jpg',
- 'Path left untouched if no sha1 can be found',
],
];
}
diff --git a/tests/phpunit/includes/jobqueue/JobTest.php b/tests/phpunit/includes/jobqueue/JobTest.php
index 51885288c2e..8070cf73ff0 100644
--- a/tests/phpunit/includes/jobqueue/JobTest.php
+++ b/tests/phpunit/includes/jobqueue/JobTest.php
@@ -18,50 +18,52 @@ class JobTest extends MediaWikiIntegrationTestCase {
/**
* @dataProvider provideTestToString
- *
- * @param Job $job
- * @param string $expected
*/
- public function testToString( $job, $expected ) {
+ public function testToString( $jobSpec, $expected ) {
$this->overrideConfigValue( MainConfigNames::LanguageCode, 'en' );
+
+ if ( $jobSpec === 'stdClass' ) {
+ $mockToStringObj = $this->getMockBuilder( stdClass::class )
+ ->addMethods( [ '__toString' ] )->getMock();
+ $mockToStringObj->method( '__toString' )
+ ->willReturn( '{STRING_OBJ_VAL}' );
+ $jobSpec = [ $mockToStringObj ];
+ }
+ $job = $this->getMockJob( $jobSpec );
+
$this->assertEquals( $expected, $job->toString() );
}
- public function provideTestToString() {
- $mockToStringObj = $this->getMockBuilder( stdClass::class )
- ->addMethods( [ '__toString' ] )->getMock();
- $mockToStringObj->method( '__toString' )
- ->willReturn( '{STRING_OBJ_VAL}' );
-
+ public static function provideTestToString() {
$requestId = 'requestId=' . WebRequest::getRequestId();
return [
[
- $this->getMockJob( [ 'key' => 'val' ] ),
+ [ 'key' => 'val' ],
'someCommand Special: key=val ' . $requestId
],
[
- $this->getMockJob( [ 'key' => [ 'inkey' => 'inval' ] ] ),
+ [ 'key' => [ 'inkey' => 'inval' ] ],
'someCommand Special: key={"inkey":"inval"} ' . $requestId
],
[
- $this->getMockJob( [ 'val1' ] ),
+ [ 'val1' ],
'someCommand Special: 0=val1 ' . $requestId
],
[
- $this->getMockJob( [ 'val1', 'val2' ] ),
+ [ 'val1', 'val2' ],
'someCommand Special: 0=val1 1=val2 ' . $requestId
],
[
- $this->getMockJob( [ (object)[] ] ),
+ [ (object)[] ],
'someCommand Special: 0=stdClass ' . $requestId
],
[
- $this->getMockJob( [ $mockToStringObj ] ),
+ 'stdClass',
'someCommand Special: 0={STRING_OBJ_VAL} ' . $requestId
],
[
- $this->getMockJob( [
+ [
"pages" => [
"932737" => [
0,
@@ -76,7 +78,7 @@ class JobTest extends MediaWikiIntegrationTestCase {
"asOfTime" => 1457521464.3814
],
"triggeredRecursive" => true
- ] ),
+ ],
'someCommand Special: pages={"932737":[0,"Robert_James_Waller"]} ' .
'rootJobSignature=45868e99bba89064e4483743ebb9b682ef95c1a7 ' .
'rootJobTimestamp=20160309110158 masterPos=' .
diff --git a/tests/phpunit/includes/page/PageStoreTest.php b/tests/phpunit/includes/page/PageStoreTest.php
index 0b02448ae4e..0d2be3448de 100644
--- a/tests/phpunit/includes/page/PageStoreTest.php
+++ b/tests/phpunit/includes/page/PageStoreTest.php
@@ -620,17 +620,17 @@ class PageStoreTest extends MediaWikiIntegrationTestCase {
$this->assertSamePage( $existingPage, $page );
}
- public function provideGetPageByIdentity_invalid() {
+ public static function provideGetPageByIdentity_invalid() {
yield 'section' => [
- $this->makeMockTitle( '', [ 'fragment' => 'See also' ] ),
+ [ '', [ 'fragment' => 'See also' ] ],
InvalidArgumentException::class
];
yield 'special' => [
- $this->makeMockTitle( 'Blankpage', [ 'namespace' => NS_SPECIAL ] ),
+ [ 'Blankpage', [ 'namespace' => NS_SPECIAL ] ],
InvalidArgumentException::class
];
yield 'interwiki' => [
- $this->makeMockTitle( 'Foo', [ 'interwiki' => 'acme' ] ),
+ [ 'Foo', [ 'interwiki' => 'acme' ] ],
InvalidArgumentException::class
];
@@ -645,6 +645,9 @@ class PageStoreTest extends MediaWikiIntegrationTestCase {
* @covers \MediaWiki\Page\PageStore::getPageByReference
*/
public function testGetPageByIdentity_invalid( $identity, $exception ) {
+ if ( is_array( $identity ) ) {
+ $identity = $this->makeMockTitle( ...$identity );
+ }
$pageStore = $this->getPageStore();
$this->expectException( $exception );
diff --git a/tests/phpunit/includes/parser/ParserMethodsTest.php b/tests/phpunit/includes/parser/ParserMethodsTest.php
index 98d3436a7cf..96000b5de14 100644
--- a/tests/phpunit/includes/parser/ParserMethodsTest.php
+++ b/tests/phpunit/includes/parser/ParserMethodsTest.php
@@ -6,7 +6,6 @@ use LogicException;
use MediaWiki\Content\WikitextContent;
use MediaWiki\Language\RawMessage;
use MediaWiki\MainConfigNames;
-use MediaWiki\MediaWikiServices;
use MediaWiki\Parser\Parser;
use MediaWiki\Parser\ParserOptions;
use MediaWiki\Revision\MutableRevisionRecord;
@@ -265,46 +264,31 @@ class ParserMethodsTest extends MediaWikiLangTestCase {
];
}
- public function provideRevisionAccess() {
- $title = $this->makeMockTitle( 'ParserRevisionAccessTest', [
- 'language' => MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'en' )
- ] );
-
- $frank = new UserIdentityValue( 5, 'Frank' );
-
+ public static function provideRevisionAccess() {
$text = '* user:{{REVISIONUSER}};id:{{REVISIONID}};time:{{REVISIONTIMESTAMP}};';
- $po = new ParserOptions( $frank );
- yield 'current' => [ $text, $po, 0, 'user:CurrentAuthor;id:200;time:20160606000000;' ];
- yield 'anonymous' => [ $text, $po, null, 'user:;id:;time:' ];
- yield 'current with ID' => [ $text, $po, 200, 'user:CurrentAuthor;id:200;time:20160606000000;' ];
+ yield 'current' => [ $text, [], 0, 'user:CurrentAuthor;id:200;time:20160606000000;' ];
+ yield 'anonymous' => [ $text, [], null, 'user:;id:;time:' ];
+ yield 'current with ID' => [ $text, [], 200, 'user:CurrentAuthor;id:200;time:20160606000000;' ];
$text = '* user:{{REVISIONUSER}};id:{{REVISIONID}};time:{{REVISIONTIMESTAMP}};';
- $po = new ParserOptions( $frank );
- yield 'old' => [ $text, $po, 100, 'user:OldAuthor;id:100;time:20140404000000;' ];
+ yield 'old' => [ $text, [], 100, 'user:OldAuthor;id:100;time:20140404000000;' ];
- $oldRevision = new MutableRevisionRecord( $title );
- $oldRevision->setId( 100 );
- $oldRevision->setUser( new UserIdentityValue( 7, 'FauxAuthor' ) );
- $oldRevision->setTimestamp( '20141111111111' );
- $oldRevision->setContent( SlotRecord::MAIN, new WikitextContent( 'FAUX' ) );
-
- $po = new ParserOptions( $frank );
- $po->setCurrentRevisionRecordCallback( static function () use ( $oldRevision ) {
- return $oldRevision;
- } );
+ $oldRevisionSpec = [
+ 'id' => 100,
+ 'user' => [ 7, 'FauxAuthor' ],
+ 'timestamp' => '20141111111111',
+ 'content' => 'FAUX',
+ ];
- yield 'old with override' => [ $text, $po, 100, 'user:FauxAuthor;id:100;time:20141111111111;' ];
+ yield 'old with override' => [ $text, [ 'revisionCallback' => $oldRevisionSpec ], 100, 'user:FauxAuthor;id:100;time:20141111111111;' ];
$text = '* user:{{REVISIONUSER}};user-subst:{{subst:REVISIONUSER}};';
- $po = new ParserOptions( $frank );
- $po->setIsPreview( true );
-
yield 'preview without override, using context' => [
$text,
- $po,
+ [ 'preview' => true ],
null,
'user:Frank;',
'user-subst:Frank;',
@@ -313,33 +297,22 @@ class ParserMethodsTest extends MediaWikiLangTestCase {
$text = '* user:{{REVISIONUSER}};time:{{REVISIONTIMESTAMP}};'
. 'user-subst:{{subst:REVISIONUSER}};time-subst:{{subst:REVISIONTIMESTAMP}};';
- $newRevision = new MutableRevisionRecord( $title );
- $newRevision->setUser( new UserIdentityValue( 9, 'NewAuthor' ) );
- $newRevision->setTimestamp( '20180808000000' );
- $newRevision->setContent( SlotRecord::MAIN, new WikitextContent( 'NEW' ) );
-
- $po = new ParserOptions( $frank );
- $po->setIsPreview( true );
- $po->setCurrentRevisionRecordCallback( static function () use ( $newRevision ) {
- return $newRevision;
- } );
-
+ $newRevisionSpec = [
+ 'user' => [ 9, 'NewAuthor' ],
+ 'timestamp' => '20180808000000',
+ 'content' => 'NEW',
+ ];
yield 'preview' => [
$text,
- $po,
+ [ 'preview' => true, 'revisionCallback' => $newRevisionSpec ],
null,
'user:NewAuthor;time:20180808000000;',
'user-subst:NewAuthor;time-subst:20180808000000;',
];
- $po = new ParserOptions( $frank );
- $po->setCurrentRevisionRecordCallback( static function () use ( $newRevision ) {
- return $newRevision;
- } );
-
yield 'pre-save' => [
$text,
- $po,
+ [ 'revisionCallback' => $newRevisionSpec ],
null,
'user:NewAuthor;time:20180808000000;',
'user-subst:NewAuthor;time-subst:20180808000000;',
@@ -348,18 +321,12 @@ class ParserMethodsTest extends MediaWikiLangTestCase {
$text = "(ONE)<includeonly>(TWO)</includeonly>"
. "<noinclude>#{{:ParserRevisionAccessTest}}#</noinclude>";
- $newRevision = new MutableRevisionRecord( $title );
- $newRevision->setUser( new UserIdentityValue( 9, 'NewAuthor' ) );
- $newRevision->setTimestamp( '20180808000000' );
- $newRevision->setContent( SlotRecord::MAIN, new WikitextContent( $text ) );
-
- $po = new ParserOptions( $frank );
- $po->setIsPreview( true );
- $po->setCurrentRevisionRecordCallback( static function () use ( $newRevision ) {
- return $newRevision;
- } );
-
- yield 'preview with self-transclude' => [ $text, $po, null, '(ONE)#(ONE)(TWO)#' ];
+ $newRevisionSpec = [
+ 'user' => [ 9, 'NewAuthor' ],
+ 'timestamp' => '20180808000000',
+ 'content' => $text,
+ ];
+ yield 'preview with self-transclude' => [ $text, [ 'preview' => true, 'revisionCallback' => $newRevisionSpec ], null, '(ONE)#(ONE)(TWO)#' ];
}
/**
@@ -367,7 +334,7 @@ class ParserMethodsTest extends MediaWikiLangTestCase {
*/
public function testRevisionAccess(
$text,
- ParserOptions $po,
+ $poSpec,
$revId,
$expectedInHtml,
$expectedInPst = null
@@ -376,6 +343,25 @@ class ParserMethodsTest extends MediaWikiLangTestCase {
'language' => $this->getServiceContainer()->getLanguageFactory()->getLanguage( 'en' )
] );
+ $frank = new UserIdentityValue( 5, 'Frank' );
+ $po = new ParserOptions( $frank );
+ if ( isset( $poSpec['revisionCallback'] ) ) {
+ $revisionSpec = $poSpec['revisionCallback'];
+ $revision = new MutableRevisionRecord( $title );
+ if ( isset( $revisionSpec['id'] ) ) {
+ $revision->setId( $revisionSpec['id'] );
+ }
+ $revision->setUser( new UserIdentityValue( ...$revisionSpec['user'] ) );
+ $revision->setTimestamp( $revisionSpec['timestamp'] );
+ $revision->setContent( SlotRecord::MAIN, new WikitextContent( $revisionSpec['content'] ) );
+ $po->setCurrentRevisionRecordCallback( static function () use ( $revision ) {
+ return $revision;
+ } );
+ }
+ if ( isset( $poSpec['preview'] ) ) {
+ $po->setIsPreview( $poSpec['preview'] );
+ }
+
$oldRevision = new MutableRevisionRecord( $title );
$oldRevision->setId( 100 );
$oldRevision->setUser( new UserIdentityValue( 7, 'OldAuthor' ) );
diff --git a/tests/phpunit/includes/parser/ParserOutputTest.php b/tests/phpunit/includes/parser/ParserOutputTest.php
index 2b488ffc0a1..542c1c55d0e 100644
--- a/tests/phpunit/includes/parser/ParserOutputTest.php
+++ b/tests/phpunit/includes/parser/ParserOutputTest.php
@@ -1104,31 +1104,25 @@ EOF
$this->assertFieldValues( $a, $expected );
}
- public function provideMergeInternalMetaDataFrom() {
- $this->filterDeprecated( '/^.*CacheTime::setCacheTime called with -1 as an argument/' );
-
+ public static function provideMergeInternalMetaDataFrom() {
// flags & co
- $a = new ParserOutput();
-
- $a->addWarningMsg( 'duplicate-args-warning', 'A', 'B', 'C' );
- $a->addWarningMsg( 'template-loop-warning', 'D' );
-
- $a->setOutputFlag( 'foo' );
- $a->setOutputFlag( 'bar' );
-
- $a->recordOption( 'Foo' );
- $a->recordOption( 'Bar' );
-
- $b = new ParserOutput();
-
- $b->addWarningMsg( 'template-equals-warning' );
- $b->addWarningMsg( 'template-loop-warning', 'D' );
-
- $b->setOutputFlag( 'zoo' );
- $b->setOutputFlag( 'bar' );
+ $a = [
+ 'warning' => [
+ [ 'duplicate-args-warning', 'A', 'B', 'C' ],
+ [ 'template-loop-warning', 'D' ],
+ ],
+ 'outputFlag' => [ 'foo', 'bar' ],
+ 'recordOption' => [ 'Foo', 'Bar' ],
+ ];
- $b->recordOption( 'Zoo' );
- $b->recordOption( 'Bar' );
+ $b = [
+ 'warning' => [
+ [ 'template-equals-warning' ],
+ [ 'template-loop-warning', 'D' ],
+ ],
+ 'outputFlag' => [ 'zoo', 'bar' ],
+ 'recordOption' => [ 'Zoo', 'Bar' ],
+ ];
yield 'flags' => [ $a, $b, [
'getWarnings' => [
@@ -1143,112 +1137,136 @@ EOF
// cache time
$someTime = "20240207202040";
$someLaterTime = "20240207202112";
- $a = new ParserOutput();
- $a->setCacheTime( $someTime );
- $b = new ParserOutput();
+ $a = [
+ 'cacheTime' => $someTime,
+ ];
+ $b = [];
yield 'only left cache time' => [ $a, $b, [ 'getCacheTime' => $someTime ] ];
- $a = new ParserOutput();
- $b = new ParserOutput();
- $b->setCacheTime( $someTime );
+ $a = [];
+ $b = [
+ 'cacheTime' => $someTime,
+ ];
yield 'only right cache time' => [ $a, $b, [ 'getCacheTime' => $someTime ] ];
- $a = new ParserOutput();
- $b = new ParserOutput();
- $a->setCacheTime( $someLaterTime );
- $b->setCacheTime( $someTime );
+ $a = [
+ 'cacheTime' => $someLaterTime,
+ ];
+ $b = [
+ 'cacheTime' => $someTime,
+ ];
yield 'left has later cache time' => [ $a, $b, [ 'getCacheTime' => $someLaterTime ] ];
- $a = new ParserOutput();
- $b = new ParserOutput();
- $a->setCacheTime( $someTime );
- $b->setCacheTime( $someLaterTime );
+ $a = [
+ 'cacheTime' => $someTime,
+ ];
+ $b = [
+ 'cacheTime' => $someLaterTime,
+ ];
yield 'right has later cache time' => [ $a, $b, [ 'getCacheTime' => $someLaterTime ] ];
- $a = new ParserOutput();
- $b = new ParserOutput();
- $a->setCacheTime( -1 );
- $b->setCacheTime( $someTime );
+ $a = [
+ 'cacheTime' => -1,
+ ];
+ $b = [
+ 'cacheTime' => $someTime,
+ ];
yield 'left is uncacheable' => [ $a, $b, [ 'getCacheTime' => "-1" ] ];
- $a = new ParserOutput();
- $b = new ParserOutput();
- $a->setCacheTime( $someTime );
- $b->setCacheTime( -1 );
+ $a = [
+ 'cacheTime' => $someTime,
+ ];
+ $b = [
+ 'cacheTime' => -1,
+ ];
yield 'right is uncacheable' => [ $a, $b, [ 'getCacheTime' => "-1" ] ];
// timestamp ------------
- $a = new ParserOutput();
- $a->setRevisionTimestamp( '20180101000011' );
- $b = new ParserOutput();
+ $a = [
+ 'revisionTimestamp' => '20180101000011',
+ ];
+ $b = [];
yield 'only left timestamp' => [ $a, $b, [ 'getTimestamp' => '20180101000011' ] ];
- $a = new ParserOutput();
- $b = new ParserOutput();
- $b->setRevisionTimestamp( '20180101000011' );
+ $a = [];
+ $b = [
+ 'revisionTimestamp' => '20180101000011',
+ ];
yield 'only right timestamp' => [ $a, $b, [ 'getTimestamp' => '20180101000011' ] ];
- $a = new ParserOutput();
- $a->setRevisionTimestamp( '20180101000011' );
- $b = new ParserOutput();
- $b->setRevisionTimestamp( '20180101000001' );
+ $a = [
+ 'revisionTimestamp' => '20180101000011',
+ ];
+ $b = [
+ 'revisionTimestamp' => '20180101000001',
+ ];
yield 'left timestamp wins' => [ $a, $b, [ 'getTimestamp' => '20180101000011' ] ];
- $a = new ParserOutput();
- $a->setRevisionTimestamp( '20180101000001' );
- $b = new ParserOutput();
- $b->setRevisionTimestamp( '20180101000011' );
+ $a = [
+ 'revisionTimestamp' => '20180101000001',
+ ];
+ $b = [
+ 'revisionTimestamp' => '20180101000011',
+ ];
yield 'right timestamp wins' => [ $a, $b, [ 'getTimestamp' => '20180101000011' ] ];
// speculative rev id ------------
- $a = new ParserOutput();
- $a->setSpeculativeRevIdUsed( 9 );
- $b = new ParserOutput();
+ $a = [
+ 'speculativeRevIdUsed' => 9,
+ ];
+ $b = [];
yield 'only left speculative rev id' => [ $a, $b, [ 'getSpeculativeRevIdUsed' => 9 ] ];
- $a = new ParserOutput();
- $b = new ParserOutput();
- $b->setSpeculativeRevIdUsed( 9 );
+ $a = [];
+ $b = [
+ 'speculativeRevIdUsed' => 9,
+ ];
yield 'only right speculative rev id' => [ $a, $b, [ 'getSpeculativeRevIdUsed' => 9 ] ];
- $a = new ParserOutput();
- $a->setSpeculativeRevIdUsed( 9 );
- $b = new ParserOutput();
- $b->setSpeculativeRevIdUsed( 9 );
+ $a = [
+ 'speculativeRevIdUsed' => 9,
+ ];
+ $b = [
+ 'speculativeRevIdUsed' => 9,
+ ];
yield 'same speculative rev id' => [ $a, $b, [ 'getSpeculativeRevIdUsed' => 9 ] ];
// limit report (recursive max) ------------
- $a = new ParserOutput();
-
- $a->setLimitReportData( 'naive1', 7 );
- $a->setLimitReportData( 'naive2', 27 );
-
- $a->setLimitReportData( 'limitreport-simple1', 7 );
- $a->setLimitReportData( 'limitreport-simple2', 27 );
+ $a = [
+ 'limitReportData' => [
+ [ 'naive1', 7 ],
+ [ 'naive2', 27 ],
- $a->setLimitReportData( 'limitreport-pair1', [ 7, 9 ] );
- $a->setLimitReportData( 'limitreport-pair2', [ 27, 29 ] );
+ [ 'limitreport-simple1', 7 ],
+ [ 'limitreport-simple2', 27 ],
- $a->setLimitReportData( 'limitreport-more1', [ 7, 9, 1 ] );
- $a->setLimitReportData( 'limitreport-more2', [ 27, 29, 21 ] );
+ [ 'limitreport-pair1', [ 7, 9 ] ],
+ [ 'limitreport-pair2', [ 27, 29 ] ],
- $a->setLimitReportData( 'limitreport-only-a', 13 );
+ [ 'limitreport-more1', [ 7, 9, 1 ] ],
+ [ 'limitreport-more2', [ 27, 29, 21 ] ],
- $b = new ParserOutput();
+ [ 'limitreport-only-a', 13 ],
+ ],
+ ];
- $b->setLimitReportData( 'naive1', 17 );
- $b->setLimitReportData( 'naive2', 17 );
+ $b = [
+ 'limitReportData' => [
+ [ 'naive1', 17 ],
+ [ 'naive2', 17 ],
- $b->setLimitReportData( 'limitreport-simple1', 17 );
- $b->setLimitReportData( 'limitreport-simple2', 17 );
+ [ 'limitreport-simple1', 17 ],
+ [ 'limitreport-simple2', 17 ],
- $b->setLimitReportData( 'limitreport-pair1', [ 17, 19 ] );
- $b->setLimitReportData( 'limitreport-pair2', [ 17, 19 ] );
+ [ 'limitreport-pair1', [ 17, 19 ] ],
+ [ 'limitreport-pair2', [ 17, 19 ] ],
- $b->setLimitReportData( 'limitreport-more1', [ 17, 19, 11 ] );
- $b->setLimitReportData( 'limitreport-more2', [ 17, 19, 11 ] );
+ [ 'limitreport-more1', [ 17, 19, 11 ] ],
+ [ 'limitreport-more2', [ 17, 19, 11 ] ],
- $b->setLimitReportData( 'limitreport-only-b', 23 );
+ [ 'limitreport-only-b', 23 ],
+ ],
+ ];
// first write wins
yield 'limit report' => [ $a, $b, [
@@ -1277,20 +1295,16 @@ EOF
],
],
] ];
-
- MWDebug::clearDeprecationFilters();
}
/**
* @dataProvider provideMergeInternalMetaDataFrom
* @covers \MediaWiki\Parser\ParserOutput::mergeInternalMetaDataFrom
- *
- * @param ParserOutput $a
- * @param ParserOutput $b
- * @param array $expected
*/
- public function testMergeInternalMetaDataFrom( ParserOutput $a, ParserOutput $b, $expected ) {
+ public function testMergeInternalMetaDataFrom( array $aSpec, array $bSpec, $expected ) {
$this->filterDeprecated( '/^.*CacheTime::setCacheTime called with -1 as an argument/' );
+ $a = $this->createParserOutput( $aSpec );
+ $b = $this->createParserOutput( $bSpec );
$a->mergeInternalMetaDataFrom( $b );
$this->assertFieldValues( $a, $expected );
@@ -1301,6 +1315,32 @@ EOF
$this->assertFieldValues( $a, $expected );
}
+ private function createParserOutput( array $spec ): ParserOutput {
+ $po = new ParserOutput();
+ foreach ( $spec['warning'] ?? [] as $warning ) {
+ $po->addWarningMsg( ...$warning );
+ }
+ foreach ( $spec['outputFlag'] ?? [] as $outputFlag ) {
+ $po->setOutputFlag( $outputFlag );
+ }
+ foreach ( $spec['recordOption'] ?? [] as $recordOption ) {
+ $po->recordOption( $recordOption );
+ }
+ foreach ( $spec['limitReportData'] ?? [] as $limitReportData ) {
+ $po->setLimitReportData( ...$limitReportData );
+ }
+ if ( isset( $spec['cacheTime'] ) ) {
+ $po->setCacheTime( $spec['cacheTime'] );
+ }
+ if ( isset( $spec['revisionTimestamp'] ) ) {
+ $po->setRevisionTimestamp( $spec['revisionTimestamp'] );
+ }
+ if ( isset( $spec['speculativeRevIdUsed'] ) ) {
+ $po->setSpeculativeRevIdUsed( $spec['speculativeRevIdUsed'] );
+ }
+ return $po;
+ }
+
/**
* @covers \MediaWiki\Parser\ParserOutput::mergeInternalMetaDataFrom
* @covers \MediaWiki\Parser\ParserOutput::getTimes
diff --git a/tests/phpunit/includes/user/PasswordResetTest.php b/tests/phpunit/includes/user/PasswordResetTest.php
index 1bdbdcf6d1c..427affcd773 100644
--- a/tests/phpunit/includes/user/PasswordResetTest.php
+++ b/tests/phpunit/includes/user/PasswordResetTest.php
@@ -204,25 +204,21 @@ class PasswordResetTest extends MediaWikiIntegrationTestCase {
/**
* @dataProvider provideExecute
- * @param string|bool $expectedError
- * @param ServiceOptions $config
- * @param User $performingUser
- * @param AuthManager $authManager
- * @param string|null $username
- * @param string|null $email
- * @param User[] $usersWithEmail
* @covers \MediaWiki\Deferred\SendPasswordResetEmailUpdate
*/
public function testExecute(
$expectedError,
- ServiceOptions $config,
- User $performingUser,
- AuthManager $authManager,
+ array $configSpec,
+ array $performingUserSpec,
+ array $authManagerSpec,
$username = '',
$email = '',
array $usersWithEmail = []
) {
$users = $this->makeUsers();
+ $config = $this->makeConfig( ...$configSpec );
+ $performingUser = $this->makePerformingUser( ...$performingUserSpec );
+ $authManager = $this->makeAuthManager( ...$authManagerSpec );
// Only User1 has `requireemail` true, everything else false (so that is the default)
$userOptionsLookup = new StaticUserOptionsLookup(
@@ -277,198 +273,198 @@ class PasswordResetTest extends MediaWikiIntegrationTestCase {
}
}
- public function provideExecute() {
+ public static function provideExecute() {
// 'User1' has the 'requireemail' preference set (see testExecute()). Other users do not.
- $defaultConfig = $this->makeConfig( true, [ 'username' => true, 'email' => true ] );
- $performingUser = $this->makePerformingUser( self::VALID_IP, false );
- $throttledUser = $this->makePerformingUser( self::VALID_IP, true );
+ $defaultConfig = [ true, [ 'username' => true, 'email' => true ] ];
+ $performingUser = [ self::VALID_IP, false ];
+ $throttledUser = [ self::VALID_IP, true ];
return [
'Throttled, pretend everything is ok' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $throttledUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $throttledUser,
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => '',
'usersWithEmail' => [],
],
'Throttled, email required for resets, is invalid, pretend everything is ok' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $throttledUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $throttledUser,
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => '[invalid email]',
'usersWithEmail' => [],
],
'Invalid email' => [
'expectedError' => 'passwordreset-invalidemail',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => '',
'email' => '[invalid email]',
'usersWithEmail' => [],
],
'No username, no email' => [
'expectedError' => 'passwordreset-nodata',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => '',
'email' => '',
'usersWithEmail' => [],
],
'Email route not enabled' => [
'expectedError' => 'passwordreset-nodata',
- 'config' => $this->makeConfig( true, [ 'username' => true ] ),
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => [ true, [ 'username' => true ] ],
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => '',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [],
],
'Username route not enabled' => [
'expectedError' => 'passwordreset-nodata',
- 'config' => $this->makeConfig( true, [ 'email' => true ] ),
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => [ true, [ 'email' => true ] ],
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => '',
'usersWithEmail' => [],
],
'No routes enabled' => [
'expectedError' => 'passwordreset-nodata',
- 'config' => $this->makeConfig( true, [] ),
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => [ true, [] ],
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [],
],
'Email required for resets but is empty, pretend everything is OK' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => '',
'usersWithEmail' => [],
],
'Email required for resets but is invalid' => [
'expectedError' => 'passwordreset-invalidemail',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => '[invalid email]',
'usersWithEmail' => [],
],
'Password email already sent within 24 hours, pretend everything is ok' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User1' ], 0, [], [ 'User1' ] ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User1' ], 0, [], [ 'User1' ] ],
'username' => 'User1',
'email' => '',
'usersWithEmail' => [ 'User1' ],
],
'No user by this username, pretend everything is OK' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'Nonexistent user',
'email' => '',
'usersWithEmail' => [],
],
'Username is not valid' => [
'expectedError' => 'noname',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'Invalid|username',
'email' => '',
'usersWithEmail' => [],
],
'If no users with this email found, pretend everything is OK' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => '',
'email' => 'some@not.found.email',
'usersWithEmail' => [],
],
'No email for the user, pretend everything is OK' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'BadUser',
'email' => '',
'usersWithEmail' => [],
],
'Email required for resets, no match' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => 'some@other.email',
'usersWithEmail' => [],
],
"Couldn't determine the performing user's IP" => [
'expectedError' => 'badipaddress',
- 'config' => $defaultConfig,
- 'performingUser' => $this->makePerformingUser( '', false ),
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => [ '', false ],
+ 'authManagerSpec' => [],
'username' => 'User1',
'email' => '',
'usersWithEmail' => [],
],
'User is allowed, but ignored' => [
'expectedError' => 'passwordreset-ignored',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User2' ], 0, [ 'User2' ] ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User2' ], 0, [ 'User2' ] ],
'username' => 'User2',
'email' => '',
'usersWithEmail' => [],
],
'One of users is ignored' => [
'expectedError' => 'passwordreset-ignored',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User1', 'User2' ], 0, [ 'User2' ] ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User1', 'User2' ], 0, [ 'User2' ] ],
'username' => '',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [ 'User1', 'User2' ],
],
'User is rejected' => [
'expectedError' => 'rejected by test mock',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager(),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [],
'username' => 'User2',
'email' => '',
'usersWithEmail' => [],
],
'One of users is rejected' => [
'expectedError' => 'rejected by test mock',
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User1' ] ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User1' ] ],
'username' => '',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [ 'User1', 'User2' ],
],
'Reset one user via password' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User1' ], 1 ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User1' ], 1 ],
'username' => 'User1',
'email' => self::VALID_EMAIL,
// Make sure that only the user specified by username is reset
@@ -476,36 +472,36 @@ class PasswordResetTest extends MediaWikiIntegrationTestCase {
],
'Reset one user via email' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User2' ], 1 ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User2' ], 1 ],
'username' => '',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [ 'User2' ],
],
'Reset multiple users via email' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User2', 'User3' ], 2 ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User2', 'User3' ], 2 ],
'username' => '',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [ 'User2', 'User3' ],
],
"Email is not required for resets, this user didn't opt in" => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User2' ], 1 ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User2' ], 1 ],
'username' => 'User2',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [ 'User2' ],
],
'Reset three users via email that did not opt in, multiple users with same email' => [
'expectedError' => false,
- 'config' => $defaultConfig,
- 'performingUser' => $performingUser,
- 'authManager' => $this->makeAuthManager( [ 'User2', 'User3', 'User4' ], 3, [ 'User1' ] ),
+ 'configSpec' => $defaultConfig,
+ 'performingUserSpec' => $performingUser,
+ 'authManagerSpec' => [ [ 'User2', 'User3', 'User4' ], 3, [ 'User1' ] ],
'username' => '',
'email' => self::VALID_EMAIL,
'usersWithEmail' => [ 'User1', 'User2', 'User3', 'User4' ],
diff --git a/tests/phpunit/includes/user/UserGroupManagerTest.php b/tests/phpunit/includes/user/UserGroupManagerTest.php
index 61ca2d7479d..041c6db0fb9 100644
--- a/tests/phpunit/includes/user/UserGroupManagerTest.php
+++ b/tests/phpunit/includes/user/UserGroupManagerTest.php
@@ -583,49 +583,18 @@ class UserGroupManagerTest extends MediaWikiIntegrationTestCase {
$this->assertSame( 'test', $memberships['test']->getGroup() );
}
- public function provideGetUserAutopromoteEmailConfirmed() {
- $successUserMock = $this->createNoOpMock(
- User::class, [ 'getEmail', 'getEmailAuthenticationTimestamp', 'isTemp', 'assertWiki' ]
- );
- $successUserMock->method( 'assertWiki' )->willReturn( true );
- $successUserMock->expects( $this->once() )
- ->method( 'getEmail' )
- ->willReturn( 'test@test.com' );
- $successUserMock->expects( $this->once() )
- ->method( 'getEmailAuthenticationTimestamp' )
- ->willReturn( wfTimestampNow() );
+ public static function provideGetUserAutopromoteEmailConfirmed() {
yield 'Successful autopromote' => [
- true, $successUserMock, [ 'test_autoconfirmed' ]
+ true, [ 'email' => 'test@test.com', 'timestamp' => wfTimestampNow() ], [ 'test_autoconfirmed' ]
];
- $emailAuthMock = $this->createNoOpMock( User::class, [ 'getEmail', 'isTemp', 'assertWiki' ] );
- $emailAuthMock->method( 'assertWiki' )->willReturn( true );
- $emailAuthMock->expects( $this->once() )
- ->method( 'getEmail' )
- ->willReturn( 'test@test.com' );
yield 'wgEmailAuthentication is false' => [
- false, $emailAuthMock, [ 'test_autoconfirmed' ]
+ false, [ 'email' => 'test@test.com' ], [ 'test_autoconfirmed' ]
];
- $invalidEmailMock = $this->createNoOpMock( User::class, [ 'getEmail', 'isTemp', 'assertWiki' ] );
- $invalidEmailMock->method( 'assertWiki' )->willReturn( true );
- $invalidEmailMock
- ->expects( $this->once() )
- ->method( 'getEmail' )
- ->willReturn( 'INVALID!' );
yield 'Invalid email' => [
- true, $invalidEmailMock, []
+ true, [ 'email' => 'INVALID!' ], []
];
- $nullTimestampMock = $this->createNoOpMock(
- User::class, [ 'getEmail', 'getEmailAuthenticationTimestamp', 'isTemp', 'assertWiki' ]
- );
- $nullTimestampMock->method( 'assertWiki' )->willReturn( true );
- $nullTimestampMock->expects( $this->once() )
- ->method( 'getEmail' )
- ->willReturn( 'test@test.com' );
- $nullTimestampMock->expects( $this->once() )
- ->method( 'getEmailAuthenticationTimestamp' )
- ->willReturn( null );
yield 'Invalid email auth timestamp' => [
- true, $nullTimestampMock, []
+ true, [ 'email' => 'test@test.com', 'timestamp' => null ], []
];
}
@@ -633,15 +602,25 @@ class UserGroupManagerTest extends MediaWikiIntegrationTestCase {
* @dataProvider provideGetUserAutopromoteEmailConfirmed
* @covers \MediaWiki\User\UserGroupManager::getUserAutopromoteGroups
* @covers \MediaWiki\User\UserGroupManager::checkCondition
- * @param bool $emailAuthentication
- * @param User $user
- * @param array $expected
*/
public function testGetUserAutopromoteEmailConfirmed(
bool $emailAuthentication,
- User $user,
+ array $userSpec,
array $expected
) {
+ $user = $this->createNoOpMock(
+ User::class, array_merge( [ 'getEmail', 'isTemp', 'assertWiki' ],
+ ( array_key_exists( 'timestamp', $userSpec ) ? [ 'getEmailAuthenticationTimestamp' ] : [] ) )
+ );
+ $user->method( 'assertWiki' )->willReturn( true );
+ $user->expects( $this->once() )
+ ->method( 'getEmail' )
+ ->willReturn( $userSpec['email'] );
+ if ( array_key_exists( 'timestamp', $userSpec ) ) {
+ $user->expects( $this->once() )
+ ->method( 'getEmailAuthenticationTimestamp' )
+ ->willReturn( $userSpec['timestamp'] );
+ }
$manager = $this->getManager( [
MainConfigNames::Autopromote => [ 'test_autoconfirmed' => [ APCOND_EMAILCONFIRMED ] ],
MainConfigNames::EmailAuthentication => $emailAuthentication
diff --git a/tests/phpunit/integration/includes/Rest/Handler/Helper/HtmlOutputRendererHelperTest.php b/tests/phpunit/integration/includes/Rest/Handler/Helper/HtmlOutputRendererHelperTest.php
index f19a6e83c5f..487337645ed 100644
--- a/tests/phpunit/integration/includes/Rest/Handler/Helper/HtmlOutputRendererHelperTest.php
+++ b/tests/phpunit/integration/includes/Rest/Handler/Helper/HtmlOutputRendererHelperTest.php
@@ -1080,41 +1080,29 @@ class HtmlOutputRendererHelperTest extends MediaWikiIntegrationTestCase {
$helper->getHtml();
}
- public function provideInit() {
- $page = PageIdentityValue::localIdentity( 7, NS_MAIN, 'Köfte' );
- $authority = $this->createNoOpMock( Authority::class );
-
+ public static function provideInit() {
yield 'Minimal' => [
- $page,
[],
- $authority,
null,
[
- 'page' => $page,
- 'authority' => $authority,
+ 'page' => 'mock',
+ 'authority' => 'mock',
'revisionOrId' => null,
'stash' => false,
'flavor' => 'view',
]
];
- $rev = $this->createNoOpMock( RevisionRecord::class, [ 'getId' ] );
- $rev->method( 'getId' )->willReturn( 7 );
-
yield 'Revision and Language' => [
- $page,
[],
- $authority,
- $rev,
+ 'mock',
[
- 'revisionOrId' => $rev,
+ 'revisionOrId' => 'mock',
]
];
yield 'revid and stash' => [
- $page,
[ 'stash' => true ],
- $authority,
8,
[
'stash' => true,
@@ -1124,9 +1112,7 @@ class HtmlOutputRendererHelperTest extends MediaWikiIntegrationTestCase {
];
yield 'flavor' => [
- $page,
[ 'flavor' => 'fragment' ],
- $authority,
8,
[
'flavor' => 'fragment',
@@ -1134,9 +1120,7 @@ class HtmlOutputRendererHelperTest extends MediaWikiIntegrationTestCase {
];
yield 'stash winds over flavor' => [
- $page,
[ 'flavor' => 'fragment', 'stash' => true ],
- $authority,
8,
[
'flavor' => 'stash',
@@ -1148,25 +1132,33 @@ class HtmlOutputRendererHelperTest extends MediaWikiIntegrationTestCase {
* Whitebox test for ensuring that init() sets the correct members.
* Testing init() against behavior would mean duplicating all tests that use setters.
*
- * @param PageIdentity $page
- * @param array $parameters
- * @param Authority $authority
- * @param RevisionRecord|int|null $revision
- * @param array $expected
- *
* @dataProvider provideInit
*/
public function testInit(
- PageIdentity $page,
array $parameters,
- Authority $authority,
$revision,
array $expected
) {
+ $page = PageIdentityValue::localIdentity( 7, NS_MAIN, 'Köfte' );
+ $authority = $this->createNoOpMock( Authority::class );
+ if ( $revision === 'mock' ) {
+ $revision = $this->createNoOpMock( RevisionRecord::class, [ 'getId' ] );
+ $revision->method( 'getId' )->willReturn( 7 );
+ }
+
$helper = $this->newHelper( [], $page, $parameters, $authority, $revision );
$wrapper = TestingAccessWrapper::newFromObject( $helper );
foreach ( $expected as $name => $value ) {
+ if ( $value === 'mock' ) {
+ if ( $name === 'page' ) {
+ $value = $page;
+ } elseif ( $name === 'authority' ) {
+ $value = $authority;
+ } else {
+ $value = $revision;
+ }
+ }
$this->assertSame( $value, $wrapper->$name );
}
}
diff --git a/tests/phpunit/tests/MockHttpTraitTest.php b/tests/phpunit/tests/MockHttpTraitTest.php
index 7fe9887dedc..81ff6541d88 100644
--- a/tests/phpunit/tests/MockHttpTraitTest.php
+++ b/tests/phpunit/tests/MockHttpTraitTest.php
@@ -35,31 +35,54 @@ class MockHttpTraitTest extends MediaWikiIntegrationTestCase {
$this->assertTrue( $pass, 'HTTP request prevented' );
}
- public function provideFactoryRequestData() {
- yield 'a request object' => [ $this->makeFakeHttpRequest( 'Hello World' ), 'Hello World' ];
+ public static function provideFactoryRequestData() {
+ yield 'a request object' => [ [ 'request-string' => 'Hello World' ], 'Hello World' ];
yield 'just a string' => [ 'Hello World', 'Hello World' ];
yield 'a closure returning a request' => [
- function () {
- return $this->makeFakeHttpRequest( 'Hello World' );
- },
+ [
+ 'request-closure' => 'Hello World',
+ ],
'Hello World'
];
yield 'a list of requests' => [
[
- $this->makeFakeHttpRequest( 'Hello World' ),
- $this->makeFakeHttpRequest( 'Yadda Yadda' ),
+ 'request-array' => [
+ 'Hello World',
+ 'Yadda Yadda',
+ ]
],
'Hello World'
];
}
+ private function prepareFactoryRequest( $requestSpec ) {
+ if ( isset( $requestSpec['request-string'] ) ) {
+ return $this->makeFakeHttpRequest( $requestSpec['request-string'] );
+ }
+ if ( isset( $requestSpec['request-array'] ) ) {
+ $request = [];
+ foreach ( $requestSpec['request-array'] as $v ) {
+ $request[] = $this->makeFakeHttpRequest( $v );
+ }
+ return $request;
+ }
+ if ( isset( $requestSpec['request-closure'] ) ) {
+ $value = $requestSpec['request-closure'];
+ return function () use ( $value ) {
+ return $this->makeFakeHttpRequest( $value );
+ };
+ }
+ return $requestSpec;
+ }
+
/**
* @dataProvider provideFactoryRequestData
*/
- public function testInstallMockHttpEmulatesRequests( $request, $expected ) {
+ public function testInstallMockHttpEmulatesRequests( $requestSpec, $expected ) {
+ $request = $this->prepareFactoryRequest( $requestSpec );
$this->installMockHttp( $request );
$data = $this->getServiceContainer()->getHttpRequestFactory()
@@ -71,7 +94,8 @@ class MockHttpTraitTest extends MediaWikiIntegrationTestCase {
/**
* @dataProvider provideFactoryRequestData
*/
- public function testMakeMockHttpRequestFactoryEmulatesRequests( $request, $expected ) {
+ public function testMakeMockHttpRequestFactoryEmulatesRequests( $requestSpec, $expected ) {
+ $request = $this->prepareFactoryRequest( $requestSpec );
$data = $this->makeMockHttpRequestFactory( $request )
->get( 'http://example.com' );
diff --git a/tests/phpunit/unit/includes/Revision/MutableRevisionRecordTest.php b/tests/phpunit/unit/includes/Revision/MutableRevisionRecordTest.php
index 3bea090bd7b..18f8e426e24 100644
--- a/tests/phpunit/unit/includes/Revision/MutableRevisionRecordTest.php
+++ b/tests/phpunit/unit/includes/Revision/MutableRevisionRecordTest.php
@@ -365,47 +365,32 @@ class MutableRevisionRecordTest extends MediaWikiUnitTestCase {
$this->assertFalse( $record->hasSlot( 'c' ) );
}
- public function provideNotReadyForInsertion() {
- $title = $this->makeMockTitle( 'Dummy' );
- $user = new UserIdentityValue( 42, 'Test' );
-
- /** @var CommentStoreComment $comment */
- $comment = $this->createMock( CommentStoreComment::class );
-
- $content = new DummyContentForTesting( 'Test' );
-
- $rev = new MutableRevisionRecord( $title );
- yield 'empty' => [ $rev ];
-
- $rev = new MutableRevisionRecord( $title );
- $rev->setContent( SlotRecord::MAIN, $content );
- $rev->setUser( $user );
- $rev->setComment( $comment );
- yield 'no timestamp' => [ $rev ];
-
- $rev = new MutableRevisionRecord( $title );
- $rev->setUser( $user );
- $rev->setComment( $comment );
- $rev->setTimestamp( '20101010000000' );
- yield 'no content' => [ $rev ];
-
- $rev = new MutableRevisionRecord( $title );
- $rev->setContent( SlotRecord::MAIN, $content );
- $rev->setComment( $comment );
- $rev->setTimestamp( '20101010000000' );
- yield 'no user' => [ $rev ];
-
- $rev = new MutableRevisionRecord( $title );
- $rev->setUser( $user );
- $rev->setContent( SlotRecord::MAIN, $content );
- $rev->setTimestamp( '20101010000000' );
- yield 'no comment' => [ $rev ];
+ public static function provideNotReadyForInsertion() {
+ yield 'empty' => [ [ 'content' => false, 'user' => false, 'comment' => false, 'timestamp' => false ] ];
+ yield 'no timestamp' => [ [ 'content' => true, 'user' => true, 'comment' => true, 'timestamp' => false ] ];
+ yield 'no content' => [ [ 'content' => false, 'user' => true, 'comment' => true, 'timestamp' => true ] ];
+ yield 'no user' => [ [ 'content' => true, 'user' => false, 'comment' => true, 'timestamp' => true ] ];
+ yield 'no comment' => [ [ 'content' => true, 'user' => true, 'comment' => false, 'timestamp' => true ] ];
}
/**
* @dataProvider provideNotReadyForInsertion
*/
- public function testNotReadyForInsertion( $rev ) {
+ public function testNotReadyForInsertion( $revSpec ) {
+ $rev = new MutableRevisionRecord( $this->makeMockTitle( 'Dummy' ) );
+ if ( $revSpec['content'] ) {
+ $rev->setContent( SlotRecord::MAIN, new DummyContentForTesting( 'Test' ) );
+ }
+ if ( $revSpec['user'] ) {
+ $rev->setUser( new UserIdentityValue( 42, 'Test' ) );
+ }
+ if ( $revSpec['comment'] ) {
+ $rev->setComment( $this->createMock( CommentStoreComment::class ) );
+ }
+ if ( $revSpec['timestamp'] ) {
+ $rev->setTimestamp( '20101010000000' );
+ }
+
$this->assertFalse( $rev->isReadyForInsertion() );
}
diff --git a/tests/phpunit/unit/includes/auth/AuthenticationResponseTest.php b/tests/phpunit/unit/includes/auth/AuthenticationResponseTest.php
index c9b3faec1b4..c3b5539024a 100644
--- a/tests/phpunit/unit/includes/auth/AuthenticationResponseTest.php
+++ b/tests/phpunit/unit/includes/auth/AuthenticationResponseTest.php
@@ -22,6 +22,21 @@ class AuthenticationResponseTest extends MediaWikiUnitTestCase {
* @param array|Exception $expect
*/
public function testConstructors( $constructor, $args, $expect ) {
+ if ( $args && is_array( $args[0] ) ) {
+ foreach ( $args[0] as &$arg ) {
+ if ( $arg === 'authrequest' ) {
+ $arg = $this->getMockForAbstractClass( AuthenticationRequest::class );
+ }
+ }
+ }
+ if ( is_array( $expect ) && isset( $expect['neededRequests'] ) ) {
+ foreach ( $expect['neededRequests'] as &$neededRequests ) {
+ if ( $neededRequests === 'authrequest' ) {
+ $neededRequests = $this->getMockForAbstractClass( AuthenticationRequest::class );
+ }
+ }
+ }
+
if ( is_array( $expect ) ) {
$res = new AuthenticationResponse();
$res->messageType = 'warning';
@@ -40,8 +55,7 @@ class AuthenticationResponseTest extends MediaWikiUnitTestCase {
}
}
- public function provideConstructors() {
- $req = $this->getMockForAbstractClass( AuthenticationRequest::class );
+ public static function provideConstructors() {
$msg = new Message( 'mainpage' );
return [
@@ -73,23 +87,23 @@ class AuthenticationResponseTest extends MediaWikiUnitTestCase {
'status' => AuthenticationResponse::ABSTAIN,
] ],
- [ 'newUI', [ [ $req ], $msg ], [
+ [ 'newUI', [ [ 'authrequest' ], $msg ], [
'status' => AuthenticationResponse::UI,
- 'neededRequests' => [ $req ],
+ 'neededRequests' => [ 'authrequest' ],
'message' => $msg,
'messageType' => 'warning',
] ],
- [ 'newUI', [ [ $req ], $msg, 'warning' ], [
+ [ 'newUI', [ [ 'authrequest' ], $msg, 'warning' ], [
'status' => AuthenticationResponse::UI,
- 'neededRequests' => [ $req ],
+ 'neededRequests' => [ 'authrequest' ],
'message' => $msg,
'messageType' => 'warning',
] ],
- [ 'newUI', [ [ $req ], $msg, 'error' ], [
+ [ 'newUI', [ [ 'authrequest' ], $msg, 'error' ], [
'status' => AuthenticationResponse::UI,
- 'neededRequests' => [ $req ],
+ 'neededRequests' => [ 'authrequest' ],
'message' => $msg,
'messageType' => 'error',
] ],
@@ -97,17 +111,17 @@ class AuthenticationResponseTest extends MediaWikiUnitTestCase {
new InvalidArgumentException( '$reqs may not be empty' )
],
- [ 'newRedirect', [ [ $req ], 'http://example.org/redir' ], [
+ [ 'newRedirect', [ [ 'authrequest' ], 'http://example.org/redir' ], [
'status' => AuthenticationResponse::REDIRECT,
- 'neededRequests' => [ $req ],
+ 'neededRequests' => [ 'authrequest' ],
'redirectTarget' => 'http://example.org/redir',
] ],
[
'newRedirect',
- [ [ $req ], 'http://example.org/redir', [ 'foo' => 'bar' ] ],
+ [ [ 'authrequest' ], 'http://example.org/redir', [ 'foo' => 'bar' ] ],
[
'status' => AuthenticationResponse::REDIRECT,
- 'neededRequests' => [ $req ],
+ 'neededRequests' => [ 'authrequest' ],
'redirectTarget' => 'http://example.org/redir',
'redirectApiData' => [ 'foo' => 'bar' ],
]
diff --git a/tests/phpunit/unit/includes/diff/UnsupportedSlotDiffRendererTest.php b/tests/phpunit/unit/includes/diff/UnsupportedSlotDiffRendererTest.php
index bcbc4def6cb..25bf70f4cc6 100644
--- a/tests/phpunit/unit/includes/diff/UnsupportedSlotDiffRendererTest.php
+++ b/tests/phpunit/unit/includes/diff/UnsupportedSlotDiffRendererTest.php
@@ -11,22 +11,14 @@ use MediaWiki\Message\Message;
*/
class UnsupportedSlotDiffRendererTest extends MediaWikiUnitTestCase {
- public function provideDiff() {
+ public static function provideDiff() {
// AbstactContent::getContentHandler uses the ContentHandlerFactory
// from MediaWikiServices, which we need to avoid. Instead, mock
// to return the relevant ContentHandlers. The actual "content" of the
// Content objects isn't used, just getModel() and getContentHandler()
- $oldContent = $this->createMock( TextContent::class );
- $oldContent->method( 'getModel' )->willReturn( CONTENT_MODEL_TEXT );
- $oldContent->method( 'getContentHandler' )->willReturn( new TextContentHandler() );
-
- $newContent = $this->createMock( TextContent::class );
- $newContent->method( 'getModel' )->willReturn( CONTENT_MODEL_TEXT );
- $newContent->method( 'getContentHandler' )->willReturn( new TextContentHandler() );
-
- $badContent = $this->createMock( FallbackContent::class );
- $badContent->method( 'getModel' )->willReturn( 'xyzzy' );
- $badContent->method( 'getContentHandler' )->willReturn( new FallbackContentHandler( 'xyzzy' ) );
+ $oldContent = [ TextContent::class, CONTENT_MODEL_TEXT, new TextContentHandler() ];
+ $newContent = [ TextContent::class, CONTENT_MODEL_TEXT, new TextContentHandler() ];
+ $badContent = [ FallbackContent::class, 'xyzzy', new FallbackContentHandler( 'xyzzy' ) ];
yield [ '(unsupported-content-diff)', $oldContent, null ];
yield [ '(unsupported-content-diff)', null, $newContent ];
@@ -40,7 +32,22 @@ class UnsupportedSlotDiffRendererTest extends MediaWikiUnitTestCase {
/**
* @dataProvider provideDiff
*/
- public function testDiff( $expected, $oldContent, $newContent ) {
+ public function testDiff( $expected, $oldContentSpec, $newContentSpec ) {
+ if ( $oldContentSpec !== null ) {
+ $oldContent = $this->createMock( $oldContentSpec[0] );
+ $oldContent->method( 'getModel' )->willReturn( $oldContentSpec[1] );
+ $oldContent->method( 'getContentHandler' )->willReturn( $oldContentSpec[2] );
+ } else {
+ $oldContent = null;
+ }
+ if ( $newContentSpec !== null ) {
+ $newContent = $this->createMock( $newContentSpec[0] );
+ $newContent->method( 'getModel' )->willReturn( $newContentSpec[1] );
+ $newContent->method( 'getContentHandler' )->willReturn( $newContentSpec[2] );
+ } else {
+ $newContent = null;
+ }
+
$localizer = $this->createMock( MessageLocalizer::class );
$localizer->method( 'msg' )
diff --git a/tests/phpunit/unit/includes/exception/HttpErrorTest.php b/tests/phpunit/unit/includes/exception/HttpErrorTest.php
index dac0fe9e32c..1d65dfa14a4 100644
--- a/tests/phpunit/unit/includes/exception/HttpErrorTest.php
+++ b/tests/phpunit/unit/includes/exception/HttpErrorTest.php
@@ -23,7 +23,22 @@ class HttpErrorTest extends MediaWikiUnitTestCase {
/**
* @dataProvider getHtmlProvider
*/
- public function testGetHtml( array $expected, $content, $header ) {
+ public function testGetHtml( array $expected, $contentSpec, $headerSpec ) {
+ // Avoid parsing logic in real Message class which includes text transformations
+ // that require MediaWikiServices
+ if ( is_array( $contentSpec ) ) {
+ $content = $this->createMock( Message::class );
+ $content->method( 'escaped' )->willReturn( ...$contentSpec );
+ } else {
+ $content = $contentSpec;
+ }
+ if ( is_array( $headerSpec ) ) {
+ $header = $this->createMock( Message::class );
+ $header->method( 'escaped' )->willReturn( ...$headerSpec );
+ } else {
+ $header = $headerSpec;
+ }
+
$httpError = new HttpError( 500, $content, $header );
$errorHtml = $httpError->getHTML();
@@ -32,14 +47,7 @@ class HttpErrorTest extends MediaWikiUnitTestCase {
}
}
- public function getHtmlProvider() {
- // Avoid parsing logic in real Message class which includes text transformations
- // that require MediaWikiServices
- $content = $this->createMock( Message::class );
- $content->method( 'escaped' )->willReturn( 'blahblah' );
- $header = $this->createMock( Message::class );
- $header->method( 'escaped' )->willReturn( 'loginerror' );
-
+ public static function getHtmlProvider() {
return [
[
[
@@ -56,8 +64,8 @@ class HttpErrorTest extends MediaWikiUnitTestCase {
'body html' => '<body><h1>loginerror</h1>'
. '<p>blahblah</p></body>'
],
- $content,
- $header
+ [ 'blahblah' ],
+ [ 'loginerror' ]
],
[
[
diff --git a/tests/phpunit/unit/includes/http/MwHttpRequestToResponseInterfaceAdapterTest.php b/tests/phpunit/unit/includes/http/MwHttpRequestToResponseInterfaceAdapterTest.php
index 754acbf29b5..561fdffebbb 100644
--- a/tests/phpunit/unit/includes/http/MwHttpRequestToResponseInterfaceAdapterTest.php
+++ b/tests/phpunit/unit/includes/http/MwHttpRequestToResponseInterfaceAdapterTest.php
@@ -108,15 +108,18 @@ class MwHttpRequestToResponseInterfaceAdapterTest extends MediaWikiUnitTestCase
* @dataProvider unsupportedMethodsProvider
*/
public function testBuilderMethodsThrowLogicException( string $method, $args ) {
+ if ( $args === 'streaminterface' ) {
+ $args = [ $this->createMock( StreamInterface::class ) ];
+ }
$this->expectException( \LogicException::class );
( new MwHttpRequestToResponseInterfaceAdapter( $this->createMock( MWHttpRequest::class ) ) )
->{$method}( ...$args );
}
- public function unsupportedMethodsProvider() {
+ public static function unsupportedMethodsProvider() {
return [
[ 'withAddedHeader', [ 'foo', 'bar' ] ],
- [ 'withBody', [ $this->createMock( StreamInterface::class ) ] ],
+ [ 'withBody', 'streaminterface' ],
[ 'withHeader', [ 'foo', 'bar' ] ],
[ 'withoutHeader', [ 'foo', 'bar' ] ],
[ 'withProtocolVersion', [ '1.1' ] ],
diff --git a/tests/phpunit/unit/includes/libs/Diff/ArrayDiffFormatterTest.php b/tests/phpunit/unit/includes/libs/Diff/ArrayDiffFormatterTest.php
index 1a7c476eb2a..13c5e2c286f 100644
--- a/tests/phpunit/unit/includes/libs/Diff/ArrayDiffFormatterTest.php
+++ b/tests/phpunit/unit/includes/libs/Diff/ArrayDiffFormatterTest.php
@@ -15,18 +15,22 @@ use Wikimedia\Diff\DiffOp;
class ArrayDiffFormatterTest extends MediaWikiUnitTestCase {
/**
- * @param Diff $input
- * @param array $expectedOutput
* @dataProvider provideTestFormat
* @covers \Wikimedia\Diff\ArrayDiffFormatter::format
*/
- public function testFormat( Diff $input, array $expectedOutput ) {
+ public function testFormat( $inputSpec, array $expectedOutput ) {
+ $input = $this->getMockDiff( $inputSpec );
+
$instance = new ArrayDiffFormatter();
$output = $instance->format( $input );
$this->assertSame( $expectedOutput, $output );
}
- private function getMockDiff( array $edits ) {
+ private function getMockDiff( array $editsSpec ) {
+ $edits = [];
+ foreach ( $editsSpec as $edit ) {
+ $edits[] = $this->getMockDiffOp( ...$edit );
+ }
$diff = $this->createMock( Diff::class );
$diff->method( 'getEdits' )
->willReturn( $edits );
@@ -50,46 +54,46 @@ class ArrayDiffFormatterTest extends MediaWikiUnitTestCase {
return $diffOp;
}
- public function provideTestFormat() {
+ public static function provideTestFormat() {
$emptyArrayTestCases = [
- $this->getMockDiff( [] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'add' ) ] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'delete' ) ] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'change' ) ] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'copy' ) ] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'FOOBARBAZ' ) ] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'add', 'line' ) ] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'delete', [], [ 'line' ] ) ] ),
- $this->getMockDiff( [ $this->getMockDiffOp( 'copy', [], [ 'line' ] ) ] ),
+ [],
+ [ [ 'add' ] ],
+ [ [ 'delete' ] ],
+ [ [ 'change' ] ],
+ [ [ 'copy' ] ],
+ [ [ 'FOOBARBAZ' ] ],
+ [ [ 'add', 'line' ] ],
+ [ [ 'delete', [], [ 'line' ] ] ],
+ [ [ 'copy', [], [ 'line' ] ] ],
];
foreach ( $emptyArrayTestCases as $testCase ) {
yield [ $testCase, [] ];
}
yield [
- $this->getMockDiff( [ $this->getMockDiffOp( 'add', [], [ 'a1' ] ) ] ),
+ [ [ 'add', [], [ 'a1' ] ] ],
[ [ 'action' => 'add', 'new' => 'a1', 'newline' => 1 ] ],
];
yield [
- $this->getMockDiff( [ $this->getMockDiffOp( 'add', [], [ 'a1', 'a2' ] ) ] ),
+ [ [ 'add', [], [ 'a1', 'a2' ] ] ],
[
[ 'action' => 'add', 'new' => 'a1', 'newline' => 1 ],
[ 'action' => 'add', 'new' => 'a2', 'newline' => 2 ],
],
];
yield [
- $this->getMockDiff( [ $this->getMockDiffOp( 'delete', [ 'd1' ] ) ] ),
+ [ [ 'delete', [ 'd1' ] ] ],
[ [ 'action' => 'delete', 'old' => 'd1', 'oldline' => 1 ] ],
];
yield [
- $this->getMockDiff( [ $this->getMockDiffOp( 'delete', [ 'd1', 'd2' ] ) ] ),
+ [ [ 'delete', [ 'd1', 'd2' ] ] ],
[
[ 'action' => 'delete', 'old' => 'd1', 'oldline' => 1 ],
[ 'action' => 'delete', 'old' => 'd2', 'oldline' => 2 ],
],
];
yield [
- $this->getMockDiff( [ $this->getMockDiffOp( 'change', [ 'd1' ], [ 'a1' ] ) ] ),
+ [ [ 'change', [ 'd1' ], [ 'a1' ] ] ],
[ [
'action' => 'change',
'old' => 'd1',
@@ -99,11 +103,11 @@ class ArrayDiffFormatterTest extends MediaWikiUnitTestCase {
] ],
];
yield [
- $this->getMockDiff( [ $this->getMockDiffOp(
+ [ [
'change',
[ 'd1', 'd2' ],
[ 'a1', 'a2' ]
- ) ] ),
+ ] ],
[
[
'action' => 'change',
diff --git a/tests/phpunit/unit/includes/page/DeletePageTest.php b/tests/phpunit/unit/includes/page/DeletePageTest.php
index 163c556696c..1e9d15c6697 100644
--- a/tests/phpunit/unit/includes/page/DeletePageTest.php
+++ b/tests/phpunit/unit/includes/page/DeletePageTest.php
@@ -20,14 +20,12 @@ use MediaWiki\Page\WikiPage;
use MediaWiki\Page\WikiPageFactory;
use MediaWiki\Permissions\Authority;
use MediaWiki\Permissions\PermissionStatus;
-use MediaWiki\Permissions\UltimateAuthority;
use MediaWiki\Revision\RevisionRecord;
use MediaWiki\Revision\RevisionStore;
use MediaWiki\Tests\Unit\Permissions\MockAuthorityTrait;
use MediaWiki\Title\NamespaceInfo;
use MediaWiki\Title\Title;
use MediaWiki\User\UserFactory;
-use MediaWiki\User\UserIdentityValue;
use MediaWikiUnitTestCase;
use PHPUnit\Framework\MockObject\MockObject;
use Wikimedia\Message\ITextFormatter;
@@ -145,12 +143,24 @@ class DeletePageTest extends MediaWikiUnitTestCase {
* @dataProvider providePermissions
*/
public function testPermissions(
- Authority $authority,
+ $authoritySpec,
bool $expectedGood,
?string $expectedMessage = null,
- ?ServiceOptions $options = null,
- ?RevisionStore $revStore = null
+ ?int $revDeleteLimit = null
) {
+ $authority = $authoritySpec === 'ultimate'
+ ? $this->mockRegisteredUltimateAuthority()
+ : $this->mockAnonAuthority( $authoritySpec );
+ if ( $revDeleteLimit !== null ) {
+ $options = $this->getServiceOptions( $revDeleteLimit );
+ $revStore = $this->getMockRevisionStore();
+ $revStore->expects( $this->atLeastOnce() )
+ ->method( 'countRevisionsByPageId' )
+ ->willReturn( $revDeleteLimit + 42 );
+ } else {
+ $options = null;
+ $revStore = null;
+ }
$dp = $this->getDeletePage(
$this->getMockPage(),
$authority,
@@ -164,57 +174,46 @@ class DeletePageTest extends MediaWikiUnitTestCase {
}
}
- public function providePermissions(): iterable {
+ public static function providePermissions(): iterable {
$cannotDeleteMsg = "You shall not delete!";
- $cannotDeleteAuthority = $this->mockAnonAuthority(
- static function (
- string $permission,
- ?PageIdentity $page = null,
- ?PermissionStatus $status = null
- ) use ( $cannotDeleteMsg ): bool {
- if ( $permission === 'delete' ) {
- if ( $status ) {
- $status->fatal( $cannotDeleteMsg );
- }
- return false;
+ $cannotDeleteAuthoritySpec = static function (
+ string $permission,
+ ?PageIdentity $page = null,
+ ?PermissionStatus $status = null
+ ) use ( $cannotDeleteMsg ): bool {
+ if ( $permission === 'delete' ) {
+ if ( $status ) {
+ $status->fatal( $cannotDeleteMsg );
}
- return true;
+ return false;
}
- );
- yield 'Cannot delete' => [ $cannotDeleteAuthority, false, $cannotDeleteMsg ];
+ return true;
+ };
+ yield 'Cannot delete' => [ $cannotDeleteAuthoritySpec, false, $cannotDeleteMsg ];
$cannotBigDeleteMsg = 'delete-toomanyrevisions';
- $cannotBigDeleteAuthority = $this->mockAnonAuthority(
- static function (
- string $permission,
- ?PageIdentity $page = null,
- ?PermissionStatus $status = null
- ) use ( $cannotBigDeleteMsg ): bool {
- if ( $permission === 'bigdelete' ) {
- if ( $status ) {
- $status->fatal( $cannotBigDeleteMsg );
- }
- return false;
+ $cannotBigDeleteAuthoritySpec = static function (
+ string $permission,
+ ?PageIdentity $page = null,
+ ?PermissionStatus $status = null
+ ) use ( $cannotBigDeleteMsg ): bool {
+ if ( $permission === 'bigdelete' ) {
+ if ( $status ) {
+ $status->fatal( $cannotBigDeleteMsg );
}
- return true;
+ return false;
}
- );
+ return true;
+ };
$revDeleteLimit = -1;
- $cannotBigDeleteOptions = $this->getServiceOptions( $revDeleteLimit );
- $revStore = $this->getMockRevisionStore();
- $revStore->expects( $this->atLeastOnce() )
- ->method( 'countRevisionsByPageId' )
- ->willReturn( $revDeleteLimit + 42 );
yield 'Cannot bigdelete' => [
- $cannotBigDeleteAuthority,
+ $cannotBigDeleteAuthoritySpec,
false,
$cannotBigDeleteMsg,
- $cannotBigDeleteOptions,
- $revStore
+ $revDeleteLimit
];
- $successAuthority = new UltimateAuthority( new UserIdentityValue( 42, 'Deleter' ) );
- yield 'Successful' => [ $successAuthority, true ];
+ yield 'Successful' => [ 'ultimate', true ];
}
/**
@@ -266,19 +265,31 @@ class DeletePageTest extends MediaWikiUnitTestCase {
}
/**
- * @param ProperPageIdentity $page
- * @param WikiPageFactory $wpFactory
- * @param NamespaceInfo|null $nsInfo
- * @param string|null $expectedMsg
* @covers ::canProbablyDeleteAssociatedTalk
* @dataProvider provideAssociatedTalk
*/
public function testCanProbablyDeleteAssociatedTalk(
ProperPageIdentity $page,
- WikiPageFactory $wpFactory,
- ?NamespaceInfo $nsInfo,
+ $talkExists,
?string $expectedMsg
): void {
+ $wpFactory = $this->createMock( WikiPageFactory::class );
+ $wpFactory->method( 'newFromTitle' )->willReturnCallback( function ( $t ) {
+ $title = Title::castFromPageReference( $t );
+ $wikiPage = $this->createMock( WikiPage::class );
+ $wikiPage->method( 'getTitle' )->willReturn( $title );
+ $wikiPage->method( 'getNamespace' )->willReturn( $title->getNamespace() );
+ return $wikiPage;
+ } );
+ $wpFactory->method( 'newFromLinkTarget' )->willReturnCallback(
+ function ( LinkTarget $t ) use ( $talkExists ) {
+ $existingTalk = $this->createMock( WikiPage::class );
+ $existingTalk->expects( $this->atLeastOnce() )->method( 'exists' )->willReturn( $talkExists );
+ return $existingTalk;
+ }
+ );
+
+ $nsInfo = new NamespaceInfo( $this->createMock( ServiceOptions::class ), $this->createHookContainer(), [], [] );
$delPage = $this->getDeletePage( $page, null, null, null, $wpFactory, $nsInfo );
$res = $delPage->canProbablyDeleteAssociatedTalk();
@@ -289,34 +300,13 @@ class DeletePageTest extends MediaWikiUnitTestCase {
}
}
- public function provideAssociatedTalk(): Generator {
- $getWpFactory = function ( bool $talkExists ): WikiPageFactory {
- $wpFactory = $this->createMock( WikiPageFactory::class );
- $wpFactory->method( 'newFromTitle' )->willReturnCallback( function ( $t ) {
- $title = Title::castFromPageReference( $t );
- $wikiPage = $this->createMock( WikiPage::class );
- $wikiPage->method( 'getTitle' )->willReturn( $title );
- $wikiPage->method( 'getNamespace' )->willReturn( $title->getNamespace() );
- return $wikiPage;
- } );
- $wpFactory->method( 'newFromLinkTarget' )->willReturnCallback(
- function ( LinkTarget $t ) use ( $talkExists ) {
- $existingTalk = $this->createMock( WikiPage::class );
- $existingTalk->expects( $this->atLeastOnce() )->method( 'exists' )->willReturn( $talkExists );
- return $existingTalk;
- }
- );
- return $wpFactory;
- };
- $nsInfo = new NamespaceInfo( $this->createMock( ServiceOptions::class ), $this->createHookContainer(), [], [] );
-
+ public static function provideAssociatedTalk(): Generator {
$talkPage = new PageIdentityValue( 42, NS_TALK, 'Test talk page', PageIdentity::LOCAL );
- yield 'Talk page' => [ $talkPage, $getWpFactory( false ), $nsInfo, 'delete-error-associated-alreadytalk' ];
+ yield 'Talk page' => [ $talkPage, false, 'delete-error-associated-alreadytalk' ];
$nonTalkPage = new PageIdentityValue( 44, NS_MAIN, 'Test article', PageIdentity::LOCAL );
- yield 'Article without talk page' =>
- [ $nonTalkPage, $getWpFactory( false ), $nsInfo, 'delete-error-associated-doesnotexist' ];
+ yield 'Article without talk page' => [ $nonTalkPage, false, 'delete-error-associated-doesnotexist' ];
- yield 'Article with talk page' => [ $nonTalkPage, $getWpFactory( true ), $nsInfo, null ];
+ yield 'Article with talk page' => [ $nonTalkPage, true, null ];
}
}
diff --git a/tests/phpunit/unit/includes/page/UndeletePageTest.php b/tests/phpunit/unit/includes/page/UndeletePageTest.php
index 89bbba22482..807a9d3d95f 100644
--- a/tests/phpunit/unit/includes/page/UndeletePageTest.php
+++ b/tests/phpunit/unit/includes/page/UndeletePageTest.php
@@ -63,21 +63,33 @@ class UndeletePageTest extends MediaWikiUnitTestCase {
}
/**
- * @param ProperPageIdentity $page
- * @param WikiPageFactory $wpFactory
- * @param NamespaceInfo|null $nsInfo
- * @param ArchivedRevisionLookup $archivedRevisionLookup
- * @param string|null $expectedMsg
* @covers ::canProbablyUndeleteAssociatedTalk
* @dataProvider provideAssociatedTalk
*/
public function testCanProbablyUndeleteAssociatedTalk(
ProperPageIdentity $page,
- WikiPageFactory $wpFactory,
- ?NamespaceInfo $nsInfo,
- ArchivedRevisionLookup $archivedRevisionLookup,
+ bool $talkExists,
+ bool $hasDeletedRevs,
?string $expectedMsg
): void {
+ $wpFactory = $this->createMock( WikiPageFactory::class );
+ $wpFactory->method( 'newFromTitle' )->willReturnCallback( function ( $t ) {
+ $title = Title::castFromPageReference( $t );
+ $wikiPage = $this->createMock( WikiPage::class );
+ $wikiPage->method( 'getTitle' )->willReturn( $title );
+ return $wikiPage;
+ } );
+ $wpFactory->method( 'newFromLinkTarget' )->willReturnCallback(
+ function ( LinkTarget $t ) use ( $talkExists ) {
+ $existingTalk = $this->createMock( WikiPage::class );
+ $existingTalk->method( 'exists' )->willReturn( $talkExists );
+ return $existingTalk;
+ }
+ );
+ $nsInfo = new NamespaceInfo( $this->createMock( ServiceOptions::class ), $this->createHookContainer(), [], [] );
+ $archivedRevisionLookup = $this->createMock( ArchivedRevisionLookup::class );
+ $archivedRevisionLookup->method( 'hasArchivedRevisions' )->willReturn( $hasDeletedRevs );
+
$res = $this->getUndeletePage( $page, $wpFactory, $nsInfo, $archivedRevisionLookup )
->canProbablyUndeleteAssociatedTalk();
if ( $expectedMsg === null ) {
@@ -87,37 +99,12 @@ class UndeletePageTest extends MediaWikiUnitTestCase {
}
}
- public function provideAssociatedTalk(): Generator {
- $getWpFactory = function ( bool $talkExists ): WikiPageFactory {
- $wpFactory = $this->createMock( WikiPageFactory::class );
- $wpFactory->method( 'newFromTitle' )->willReturnCallback( function ( $t ) {
- $title = Title::castFromPageReference( $t );
- $wikiPage = $this->createMock( WikiPage::class );
- $wikiPage->method( 'getTitle' )->willReturn( $title );
- return $wikiPage;
- } );
- $wpFactory->method( 'newFromLinkTarget' )->willReturnCallback(
- function ( LinkTarget $t ) use ( $talkExists ) {
- $existingTalk = $this->createMock( WikiPage::class );
- $existingTalk->method( 'exists' )->willReturn( $talkExists );
- return $existingTalk;
- }
- );
- return $wpFactory;
- };
- $getArchiveLookup = function ( bool $hasDeletedRevs ): ArchivedRevisionLookup {
- $ret = $this->createMock( ArchivedRevisionLookup::class );
- $ret->method( 'hasArchivedRevisions' )->willReturn( $hasDeletedRevs );
- return $ret;
- };
- $nsInfo = new NamespaceInfo( $this->createMock( ServiceOptions::class ), $this->createHookContainer(), [], [] );
-
+ public static function provideAssociatedTalk(): Generator {
$talkPage = new PageIdentityValue( 42, NS_TALK, 'Test talk page', PageIdentity::LOCAL );
yield 'Talk page' => [
$talkPage,
- $getWpFactory( false ),
- $nsInfo,
- $getArchiveLookup( false ),
+ false,
+ false,
'undelete-error-associated-alreadytalk'
];
@@ -125,24 +112,22 @@ class UndeletePageTest extends MediaWikiUnitTestCase {
yield 'Article whose talk page exists and does not have deleted revisions' => [
$nonTalkPage,
- $getWpFactory( true ),
- $nsInfo,
- $getArchiveLookup( false ),
+ true,
+ false,
'undelete-error-associated-notdeleted'
];
yield 'Article whose talk page does not exist and does not have deleted revisions' => [
$nonTalkPage,
- $getWpFactory( false ),
- $nsInfo,
- $getArchiveLookup( false ),
+ false,
+ false,
'undelete-error-associated-notdeleted'
];
yield 'Article whose talk page exists and has deleted revisions' =>
- [ $nonTalkPage, $getWpFactory( true ), $nsInfo, $getArchiveLookup( true ), null ];
+ [ $nonTalkPage, true, true, null ];
yield 'Article whose talk page does not exist and has deleted revisions' =>
- [ $nonTalkPage, $getWpFactory( false ), $nsInfo, $getArchiveLookup( true ), null ];
+ [ $nonTalkPage, false, true, null ];
}
}
diff --git a/tests/phpunit/unit/includes/preferences/MultiTitleFilterTest.php b/tests/phpunit/unit/includes/preferences/MultiTitleFilterTest.php
index d885fff4f6e..3977f81949e 100644
--- a/tests/phpunit/unit/includes/preferences/MultiTitleFilterTest.php
+++ b/tests/phpunit/unit/includes/preferences/MultiTitleFilterTest.php
@@ -54,6 +54,10 @@ class MultiTitleFilterTest extends MediaWikiUnitTestCase {
* @dataProvider filterForFormDataProvider
*/
public function testFilterForForm( $expected, $inputValue, $newFromIDsReturnValue ) {
+ $newFromIDsReturnValuePages = [];
+ foreach ( $newFromIDsReturnValue as $s ) {
+ $newFromIDsReturnValuePages[] = $this->getMockTitle( $s );
+ }
$titleFormatter = $this->createMock( TitleFormatter::class );
$titleFormatter->method( 'getPrefixedText' )
->willReturnOnConsecutiveCalls(
@@ -61,10 +65,10 @@ class MultiTitleFilterTest extends MediaWikiUnitTestCase {
static function ( $t ) {
return $t->getPrefixedText();
},
- $newFromIDsReturnValue
+ $newFromIDsReturnValuePages
)
);
- $pageStore = $this->getPageStore( $newFromIDsReturnValue );
+ $pageStore = $this->getPageStore( $newFromIDsReturnValuePages );
$multiTitleFilter = new MultiTitleFilter( null, $pageStore, $titleFormatter );
$this->assertSame( $expected, $multiTitleFilter->filterForForm( $inputValue ) );
}
@@ -84,7 +88,7 @@ class MultiTitleFilterTest extends MediaWikiUnitTestCase {
return $pageStore;
}
- public function filterForFormDataProvider(): array {
+ public static function filterForFormDataProvider(): array {
return [
[
'',
@@ -100,8 +104,8 @@ class MultiTitleFilterTest extends MediaWikiUnitTestCase {
"Foo\nBar",
"2\n\3\n\42",
[
- $this->getMockTitle( 'Foo' ),
- $this->getMockTitle( 'Bar' )
+ 'Foo',
+ 'Bar'
]
]
];
@@ -114,27 +118,27 @@ class MultiTitleFilterTest extends MediaWikiUnitTestCase {
public function testFilterFromForm( $expected, $titles, $newFromTextValue ) {
$pageStore = $this->createMock( PageStore::class );
$pageStore->method( 'getPageByText' )
- ->willReturnOnConsecutiveCalls( $newFromTextValue );
+ ->willReturnOnConsecutiveCalls( $this->getMockPageIdentityValue( ...$newFromTextValue ) );
$multiTitleFilter = new MultiTitleFilter( null, $pageStore );
$this->assertSame( $expected, $multiTitleFilter->filterFromForm( $titles ) );
}
- public function filterFromFormDataProvider(): array {
+ public static function filterFromFormDataProvider(): array {
return [
[
null,
'',
- $this->getMockPageIdentityValue( 0, 'Foo' ),
+ [ 0, 'Foo' ],
],
[
"42",
"Foo",
- $this->getMockPageIdentityValue( 42, 'Foo' )
+ [ 42, 'Foo' ]
],
[
"",
"Bar",
- $this->getMockPageIdentityValue( 0, 'Bar' )
+ [ 0, 'Bar' ]
]
];
diff --git a/tests/phpunit/unit/includes/title/TitleTest.php b/tests/phpunit/unit/includes/title/TitleTest.php
index ddf5e8a7eae..b9ce0258436 100644
--- a/tests/phpunit/unit/includes/title/TitleTest.php
+++ b/tests/phpunit/unit/includes/title/TitleTest.php
@@ -310,29 +310,24 @@ class TitleTest extends MediaWikiUnitTestCase {
}
}
- public function provideCastFromPageIdentity() {
+ public static function provideCastFromPageIdentity() {
yield [ null ];
-
- $fake = $this->createMock( PageIdentity::class );
- $fake->method( 'getId' )->willReturn( 7 );
- $fake->method( 'getNamespace' )->willReturn( NS_MAIN );
- $fake->method( 'getDBkey' )->willReturn( 'Test' );
-
- yield [ $fake ];
-
- $fake = $this->createMock( Title::class );
- $fake->method( 'getId' )->willReturn( 7 );
- $fake->method( 'getNamespace' )->willReturn( NS_MAIN );
- $fake->method( 'getDBkey' )->willReturn( 'Test' );
-
- yield [ $fake ];
+ yield [ PageIdentity::class ];
+ yield [ Title::class ];
}
/**
* @covers \MediaWiki\Title\Title::castFromPageIdentity
* @dataProvider provideCastFromPageIdentity
*/
- public function testCastFromPageIdentity( ?PageIdentity $value ) {
+ public function testCastFromPageIdentity( $value ) {
+ if ( $value !== null ) {
+ $value = $this->createMock( $value );
+ $value->method( 'getId' )->willReturn( 7 );
+ $value->method( 'getNamespace' )->willReturn( NS_MAIN );
+ $value->method( 'getDBkey' )->willReturn( 'Test' );
+ }
+
$title = Title::castFromPageIdentity( $value );
if ( $value === null ) {
@@ -355,7 +350,14 @@ class TitleTest extends MediaWikiUnitTestCase {
* @dataProvider provideCastFromPageIdentity
* @dataProvider provideCastFromPageReference
*/
- public function testCastFromPageReference( ?PageReference $value ) {
+ public function testCastFromPageReference( $value ) {
+ if ( is_string( $value ) ) {
+ $value = $this->createMock( $value );
+ $value->method( 'getId' )->willReturn( 7 );
+ $value->method( 'getNamespace' )->willReturn( NS_MAIN );
+ $value->method( 'getDBkey' )->willReturn( 'Test' );
+ }
+
$title = Title::castFromPageReference( $value );
if ( $value === null ) {
diff --git a/tests/phpunit/unit/includes/utils/MWRestrictionsTest.php b/tests/phpunit/unit/includes/utils/MWRestrictionsTest.php
index ba98299133f..7dd118733b9 100644
--- a/tests/phpunit/unit/includes/utils/MWRestrictionsTest.php
+++ b/tests/phpunit/unit/includes/utils/MWRestrictionsTest.php
@@ -2,7 +2,6 @@
use MediaWiki\Json\FormatJson;
use MediaWiki\Request\FauxRequest;
-use MediaWiki\Request\WebRequest;
use MediaWiki\Status\Status;
class MWRestrictionsTest extends MediaWikiUnitTestCase {
@@ -186,47 +185,34 @@ class MWRestrictionsTest extends MediaWikiUnitTestCase {
/**
* @covers \MWRestrictions::check
- * @dataProvider provideCheck
- * @param WebRequest $request
- * @param Status $expect
+ * @dataProvider provideCheckIP
*/
- public function testCheck( $request, $expect ) {
- $this->assertEquals( $expect, self::$restrictionsForChecks->check( $request ) );
- }
+ public function testCheck( $ip, $pass ) {
+ $ok = [];
+ $request = $this->getMockBuilder( FauxRequest::class )
+ ->onlyMethods( [ 'getIP' ] )->getMock();
+
+ $request->method( 'getIP' )
+ ->willReturn( $ip );
+ $ok['ip'] = $pass;
+
+ /* If we ever add more restrictions, add nested for loops here:
+ * foreach ( self::provideCheckFoo() as $checkFoo ) {
+ * $request->method( 'getFoo' )->willReturn( $checkFoo[0] );
+ * $ok['foo'] = $checkFoo[1];
+ *
+ * foreach ( self::provideCheckBar() as $checkBar ) {
+ * $request->method( 'getBar' )->willReturn( $checkBar[0] );
+ * $ok['bar'] = $checkBar[1];
+ *
+ * // etc.
+ * }
+ * }
+ */
+
+ $expect = Status::newGood();
+ $expect->setResult( $ok === array_filter( $ok ), $ok );
- public function provideCheck() {
- $ret = [];
-
- $mockBuilder = $this->getMockBuilder( FauxRequest::class )
- ->onlyMethods( [ 'getIP' ] );
-
- foreach ( self::provideCheckIP() as $checkIP ) {
- $ok = [];
- $request = $mockBuilder->getMock();
-
- $request->method( 'getIP' )
- ->willReturn( $checkIP[0] );
- $ok['ip'] = $checkIP[1];
-
- /* If we ever add more restrictions, add nested for loops here:
- * foreach ( self::provideCheckFoo() as $checkFoo ) {
- * $request->method( 'getFoo' )->willReturn( $checkFoo[0] );
- * $ok['foo'] = $checkFoo[1];
- *
- * foreach ( self::provideCheckBar() as $checkBar ) {
- * $request->method( 'getBar' )->willReturn( $checkBar[0] );
- * $ok['bar'] = $checkBar[1];
- *
- * // etc.
- * }
- * }
- */
-
- $status = Status::newGood();
- $status->setResult( $ok === array_filter( $ok ), $ok );
- $ret[] = [ $request, $status ];
- }
-
- return $ret;
+ $this->assertEquals( $expect, self::$restrictionsForChecks->check( $request ) );
}
}
diff --git a/tests/phpunit/unit/includes/watchlist/WatchedItemQueryServiceUnitTest.php b/tests/phpunit/unit/includes/watchlist/WatchedItemQueryServiceUnitTest.php
index bb67daf83c9..52f221718b7 100644
--- a/tests/phpunit/unit/includes/watchlist/WatchedItemQueryServiceUnitTest.php
+++ b/tests/phpunit/unit/includes/watchlist/WatchedItemQueryServiceUnitTest.php
@@ -647,7 +647,7 @@ class WatchedItemQueryServiceUnitTest extends MediaWikiUnitTestCase {
$this->assertSame( [], $items );
}
- public function getWatchedItemsWithRecentChangeInfoInvalidOptionsProvider() {
+ public static function getWatchedItemsWithRecentChangeInfoInvalidOptionsProvider() {
return [
[
[ 'rcTypes' => [ 1337 ] ],
@@ -700,7 +700,7 @@ class WatchedItemQueryServiceUnitTest extends MediaWikiUnitTestCase {
'Bad value for parameter $startFrom: must be a two-element array',
],
[
- [ 'watchlistOwner' => $this->getMockUserWithId( 2 ) ],
+ [ 'watchlistOwner' => 2 ],
null,
'Bad value for parameter $options[\'watchlistOwnerToken\']',
],
@@ -720,6 +720,9 @@ class WatchedItemQueryServiceUnitTest extends MediaWikiUnitTestCase {
$startFrom,
$expectedInExceptionMessage
) {
+ if ( isset( $options['watchlistOwner'] ) && is_int( $options['watchlistOwner'] ) ) {
+ $options['watchlistOwner'] = $this->getMockUserWithId( $options['watchlistOwner'] );
+ }
$mockDb = $this->getMockDb();
$mockDb->expects( $this->never() )
->method( $this->anything() );

File Metadata

Mime Type
text/x-diff
Expires
Sat, Jul 5, 5:32 AM (7 h, 57 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
227501
Default Alt Text
(92 KB)

Event Timeline